码匪周子

 

hutool工具类实现的Sm2.Sm3,Sm4加解密

  String uuid = UUID.randomUUID().toString().replace("-", "");;
        //签名/验签时,将参数名ASCII码从小到大排序
        //请求参数
        Map<String, Object> map = new TreeMap<String,Object>();
        map.put("flowNo", uuid);
        map.put("userId", "123456");
        map.put("integral","10");
        map.put("summary","周周周111");
        map.put("goodsType","1");
        map.put("toUrl","http://www.baidu.com");
//字符串拼接
        StringBuffer stringBuffer = new StringBuffer();
        map.forEach((key, value) -> {
            if(value != null) {
                stringBuffer.append(key).append("=").append(value).append("&");
            }});
        String content = stringBuffer.deleteCharAt(stringBuffer.length()-1).toString();
        System.out.println("排序拼接参数:"+content);
    
//生成摘要 String hash = SmUtil.sm3(content); System.out.println("sm3生成摘要:"+hash); System.out.println("============================="); //生成公私钥 KeyPair pair = SecureUtil.generateKeyPair("SM2"); String privateKey = HexUtil.encodeHexStr(pair.getPrivate().getEncoded()); String publicKey = HexUtil.encodeHexStr(pair.getPublic().getEncoded()); System.out.println("sm2公钥:"+publicKey); System.out.println("sm2私钥:"+privateKey); System.out.println("============================="); // byte[] privateKey = pair.getPrivate().getEncoded(); // byte[] publicKey = pair.getPublic().getEncoded(); //生成签名 SM2 sm2E = SmUtil.sm2(null, publicKey); SM2 sm2D = SmUtil.sm2(privateKey,null); String encryptStr = sm2E.encryptBcd(hash, KeyType.PublicKey); System.out.println("sm2加密摘要生成签名:"+encryptStr); String decryptStr = StrUtil.utf8Str(sm2D.decryptFromBcd(encryptStr, KeyType.PrivateKey)); System.out.println("sm2解密签名获取摘要:"+decryptStr); System.out.println("============================="); //随机生成sm4加密key String sm4Key = RandomUtil.randomString(RandomUtil.BASE_CHAR_NUMBER, 16); System.out.println("sm4Key:"+sm4Key); //sm4加密业务报文 SymmetricCrypto sm4 = new SymmetricCrypto("SM4/ECB/PKCS5Padding", sm4Key.getBytes()); String sm4Encrypt = sm4.encryptHex(JSON.toJSONString(map)); System.out.println("sm4加密报文:"+sm4Encrypt); String sm4Decrypt = sm4.decryptStr(sm4Encrypt); System.out.println("sm4解密报文:"+sm4Decrypt); System.out.println("============================="); //加密sm4Key String sm4KeyEncryptStr = sm2E.encryptBcd(sm4Key, KeyType.PublicKey); System.out.println("sm4Key加密:"+sm4KeyEncryptStr); String sm4KeyDecryptStr = StrUtil.utf8Str(sm2D.decryptFromBcd(sm4KeyEncryptStr, KeyType.PrivateKey)); System.out.println("sm4Key解密:"+sm4KeyDecryptStr); System.out.println("=============================");

 

hutool工具类

<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.5.1</version>

alibaba-fastjson
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>2.0.4.graal</version>

posted on 2022-06-10 11:02  码匪周子  阅读(9319)  评论(0编辑  收藏  举报

导航