基于java 使用FishermanJCE配合加密卡进行SM2加密的代码示例
时间: 2024-03-05 22:48:19 浏览: 158
SM2加密解密java代码完整示例
以下是基于Java使用FishermanJCE配合加密卡进行SM2加密的代码示例:
```java
import java.security.*;
import java.util.Arrays;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import com.feinno.security.sm.SM2PublicKey;
import com.feinno.security.sm.SM2PrivateKey;
import com.feinno.security.sm.SM2Engine;
import com.feinno.security.sm.SM2Cipher;
import com.feinno.security.sm.SM2Util;
import com.feinno.security.sm.SM2Constants;
import com.feinno.security.sm.SM2KeyPairGenerator;
import com.feinno.security.sm.SM2KeyPair;
import com.feinno.security.sm.SM2KeyExchange;
public class SM2EncryptWithFishermanJCE {
public static void main(String[] args) throws Exception {
// 添加BouncyCastleProvider支持
Security.addProvider(new BouncyCastleProvider());
// 生成SM2公私钥对
SM2KeyPairGenerator generator = new SM2KeyPairGenerator();
generator.initialize(SM2Constants.DEFAULT_CURVE, new SecureRandom());
SM2KeyPair keyPair = generator.generateKeyPair();
SM2PrivateKey privateKey = keyPair.getPrivateKey();
SM2PublicKey publicKey = keyPair.getPublicKey();
// 生成随机明文
byte[] plaintext = new byte[256];
new SecureRandom().nextBytes(plaintext);
// 初始化SM2加密引擎
SM2Engine engine = new SM2Engine();
engine.init(SM2Engine.ENCRYPT_MODE, publicKey);
// 使用FishermanJCE进行加密
SM2Cipher cipher = new SM2Cipher();
cipher.setCipherProviderName("FishermanJCE");
cipher.setMode(SM2Cipher.MODE_C1C3C2);
cipher.init(engine, privateKey, publicKey);
byte[] ciphertext = cipher.doFinal(plaintext);
// 初始化SM2解密引擎
engine.init(SM2Engine.DECRYPT_MODE, privateKey);
// 使用FishermanJCE进行解密
cipher = new SM2Cipher();
cipher.setCipherProviderName("FishermanJCE");
cipher.setMode(SM2Cipher.MODE_C1C3C2);
cipher.init(engine, privateKey, publicKey);
byte[] decrypted = cipher.doFinal(ciphertext);
// 验证解密结果是否与原始明文相同
if (Arrays.equals(plaintext, decrypted)) {
System.out.println("SM2 Encrypt with FishermanJCE success!");
} else {
System.out.println("SM2 Encrypt with FishermanJCE failed!");
}
}
}
```
注意,上面的代码示例仅供参考,实际运行需要根据自己的具体情况进行调整。另外,FishermanJCE是一款商业加密软件,需要进行购买和授权才能使用。
阅读全文