53 lines
2.1 KiB
Java
53 lines
2.1 KiB
Java
package com.sunyard.cisd;
|
|
|
|
import com.sunyard.cisd.device.tool.SM2SignedEnvelopeUtil;
|
|
import com.sunyard.cisd.device.tool.SM2SignedEnvelopeUtil.DecryptedResult;
|
|
import com.sunyard.cisd.device.tool.SM2SignedEnvelopeUtil.SM2KeyPair;
|
|
import org.junit.Assert;
|
|
import org.junit.Test;
|
|
|
|
import java.nio.charset.StandardCharsets;
|
|
|
|
public class SM2EnvelopeTest {
|
|
|
|
/**
|
|
* 1-1 验证普通 SM2 数字信封可以生成并解密回原文。
|
|
*
|
|
* @param 无参数。
|
|
* @return 无返回值。
|
|
* @throws Exception 生成密钥、加密或解密失败时抛出。
|
|
*/
|
|
@Test
|
|
public void test1_1CreateAndOpenEnvelope() throws Exception {
|
|
SM2KeyPair encryptionKeyPair = SM2SignedEnvelopeUtil.generateKeyPair();
|
|
byte[] plaintext = "1-1 普通 SM2 数字信封".getBytes(StandardCharsets.UTF_8);
|
|
|
|
byte[] envelope = SM2SignedEnvelopeUtil.createEnvelopedData(plaintext, encryptionKeyPair.publicKey);
|
|
byte[] opened = SM2SignedEnvelopeUtil.openEnvelopedData(envelope, encryptionKeyPair.privateKey);
|
|
|
|
Assert.assertArrayEquals(plaintext, opened);
|
|
}
|
|
|
|
/**
|
|
* 1-2 验证带签名的 SM2 数字信封可以生成、解密并验签通过。
|
|
*
|
|
* @param 无参数。
|
|
* @return 无返回值。
|
|
* @throws Exception 生成密钥、签名、加密、解密或验签失败时抛出。
|
|
*/
|
|
@Test
|
|
public void test1_2CreateAndOpenSignedEnvelope() throws Exception {
|
|
SM2KeyPair signingKeyPair = SM2SignedEnvelopeUtil.generateKeyPair();
|
|
SM2KeyPair encryptionKeyPair = SM2SignedEnvelopeUtil.generateKeyPair();
|
|
byte[] plaintext = "1-2 带签名 SM2 数字信封".getBytes(StandardCharsets.UTF_8);
|
|
|
|
byte[] envelope = SM2SignedEnvelopeUtil.createSignedAndEnvelopedData(
|
|
plaintext, signingKeyPair.privateKey, encryptionKeyPair.publicKey);
|
|
DecryptedResult result = SM2SignedEnvelopeUtil.openAndVerifySignedEnvelopedData(
|
|
envelope, encryptionKeyPair.privateKey, signingKeyPair.publicKey);
|
|
|
|
Assert.assertArrayEquals(plaintext, result.plaintext);
|
|
Assert.assertTrue(result.signatureValid);
|
|
}
|
|
}
|