基于RSA的签名算法,目前KMI支持NONEwithRSA, MD2withRSA, MD5withRSA, SHA1withRSA, SHA256withRSA, SHA384withRSA, SHA512withRSA, SHA1withDSA
代码如下:
public void testRSA() throws Exception{
// 生成一对密钥
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); //获取密钥生成器实例
keyPairGenerator.initialize(512); // 初始化长度
KeyPair keyPair = keyPairGenerator.generateKeyPair();
RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();//生成公钥
RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate(); // 生成私钥
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
//私钥格式转换
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(rsaPrivateKey.getEncoded()); //私钥转换成pkcs8格式
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec); // 用key工厂对象生成私钥
//公钥格式转换
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(rsaPublicKey.getEncoded());
PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
Signature signature = Signature.getInstance("MD5withRSA"); // md5 RSA签名对象
//用私钥进行签名
signature.initSign(privateKey); //初始化签名
String originalData = "hello world";
signature.update(originalData.getBytes());
byte[] result = signature.sign(); //对消息进行签名
System.out.println("originalData:"+originalData);
System.out.println("签名结果:" + result.toString());
//用公钥进行验证
signature.initVerify(publicKey);
signature.update(originalData.getBytes());
boolean verify = signature.verify(result);
System.out.println("验证结果:" + verify);
Cipher cipher = Cipher.getInstance("RSA/NONE/NoPadding", new BouncyCastleProvider());
//对数据进行加密
originalData="51NB51NB";
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] encryptData = cipher.doFinal(originalData.getBytes());
System.out.println("originalData:"+originalData);
System.out.println("加密数据:"+encryptData);
//对数据进行解密
cipher.init(Cipher.DECRYPT_MODE,privateKey);
byte[] decryptData=cipher.doFinal(encryptData);
System.out.println("解密数据:"+new String(decryptData));
}
代码解读:
1.利用KeyPairGenerator类生成一对公钥私钥。公钥用于验签和加密,私钥用于签名和解密。
2.对数据进行签名和验签,使用Signature类,采用”MD5withRSA”算法。
3.对数据进行加密解密,使用Cipher类,采用”RSA/NONE/NoPadding”算法。