公司最近进行安全问题修改,所以要用国密系列的sm2,sm3,sm4,这些加密都用在登录模块,因此作为菜鸟的我,从网上找了一堆资料,整理修改后形成符合项目的加密,需要的可以自己去查看相关代码和jar包:sm2、sm3、sm4国密js+后台代码国密加密.rar_sm2js解密-Java文档类资源-CSDN下载
具体为:
1.为了保证传输性所以采用sm2加密;ps:sm2 js加密(C1C2C3-0模式),后台sm2解密(C1C2C3-0模式)
2.为了保证完整性所以采用sm3加密;ps: sm3 js加密,后台sm3加密(因为sm3杂凑算法所以不需要解密)
3.为了保证安全性所以采用sm4加密。ps:sm4 加密 CBC模式,解密(CBC模式)
sm2 js加密
sm3 js加密
sm2 后台加密
public class SM2UtilTest {
public static void main(String[] args) {
//获取公私钥
SM2KeyPair sm2Keys = SM2Util.getSm2Keys(false);
System.out.println("公钥 :" + sm2Keys.getPublicKey());
System.out.println("私钥 :" + sm2Keys.getPrivateKey());
//需要加密的数据
String data = "5fcd0320ed15fcdf5b08e9c4a9f48a5069f48dcba813eba568327906fd97c8ee";
//公钥加密,获取密文
String encrypt = SM2Util.encrypt(sm2Keys.getPublicKey(), data);
System.out.println("密文 :" + encrypt);
//私钥解密
String decrypt = SM2Util.decrypt(sm2Keys.getPrivateKey(), encrypt);
System.out.println("解密数据 : " + decrypt);
System.out.println("明文密文是否相同 :" + data.equals(decrypt));
}
}
sm3后台
public static void main(String[] args){
//测试
String str = "123456";
String hex = sm3Util.encrypt(str);
System.out.println(hex);
String str1 = "sdfsd";
String hex1 = sm3Util.encrypt(str1);
System.out.println(hex1);
String str2 = "sdfsf...";
String hex2 = sm3Util.encrypt(str2);
System.out.println(hex2);
String strpre = "";
String hexpre = sm3Util.encrypt(strpre);
System.out.println(hexpre);
//验证加密后的16进制字符串与加密前的字符串是否相同
boolean flag = sm3Util.vertify(str, hex);
System.out.println(flag);
}
sm4
public static void main(String[] args) throws IOException
{
String plainText = "";
SM4Utils sm4 = new SM4Utils();
sm4.secretKey = "JeF8U9wHFOMfs2Y8";
sm4.hexString = false;
System.out.println("ECB模式");
String cipherText = sm4.encryptData_ECB(plainText);
System.out.println("密文: " + cipherText);
System.out.println("");
plainText = sm4.decryptData_ECB(cipherText);
System.out.println("明文: " + plainText);
System.out.println("");
System.out.println("CBC模式");
sm4.iv = "UISwD9fW6cFh9SNS";
cipherText = sm4.encryptData_CBC(plainText);
System.out.println("密文: " + cipherText);
System.out.println("");
plainText = sm4.decryptData_CBC(cipherText);
System.out.println("明文: " + plainText);
}