国密算法SM2加解密数据,解密出现异常

参考开源项目:https://github.com/ZZMarquis/gmhelper

旧标准的加密排序C!C2C3 新标准 C!C3C2
C1为65字节第1字节为压缩标识,这里固定为0x04,后面64字节为xy分量各32字节。C3为32字节。C2长度与原文一致。

如果密文转成byte数组 第一个元素不是0x04,那么需要进行数组copy

  public void testYouChu(){
//密文
        String miwei = "gcFp1B4g6FZ3WzDk40WN1E5Lk6VN6w6MPErq3DhKH5GDj1buZD/5l03kVdnKE3l1YsBx9wuvzsTPLuR3MAw++OSHx/ekERIKthJts3VXBzLCxAPVRDZbfVyOlUwM3wOrlbZmD5pvDeZlqc2UrCoYHw==";

        BASE64Decoder decoder = new BASE64Decoder();
        try {
            byte[] bytes = decoder.decodeBuffer(miwei);
            byte[] bytes1 = new byte[bytes.length+1];
            bytes1[0]=04;
            System.arraycopy(bytes, 0, bytes1, 1, bytes.length);
            System.out.println("SM2 decrypt result:\n" + ByteUtils.toHexString(bytes1));
//私钥            
String priHex = "5CBC68F46DA40C3FCA12EFF7C99F1306577B25BB86837FD99558DD1FD1AEC430";
            ECPrivateKeyParameters priKey = new ECPrivateKeyParameters(
                    new BigInteger(ByteUtils.fromHexString(priHex)), SM2Util.DOMAIN_PARAMS);
            byte[] decryptedData = SM2Util.decrypt(Mode.C1C3C2, priKey, bytes1);
            System.out.println("SM2 decrypt result:\n" + ByteUtils.toHexString(decryptedData));
        } catch (Exception ex) {
            ex.printStackTrace();
            Assert.fail();
        }

    }

 

你可能感兴趣的:(java)