//java提供的公钥私钥生成类
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
SecureRandom secureRandom = new SecureRandom("参与随机秘钥的生成,此处固定则生成的秘钥固定".getBytes("utf-8"));
keyPairGenerator.initialize(1024, secureRandom);
KeyPair keypair = keyPairGenerator.generateKeyPair();
//此处即是产生的公钥和私钥
PrivateKey privateKey= keypair.getPrivate();
PublicKey publicKey = keypair.getPublic();
//我们往往把公钥私钥转换成字符串来保存或者传递
String privstr = new BASE64Encoder().encode(privateKey.getEncoded());
String pubstr = new BASE64Encoder().encode(publicKey.getEncoded());
System.out.println("私钥:" + privstr );
System.out.println("公钥:" + pubstr );
//接收方 把字符串格式的转换回来
//公钥转换 java中提供了字节数组转公钥的类 X509EncodedKeySpec
X509EncodedKeySpec x509 = new X509EncodedKeySpec(new BASE64Decoder().decodeBuffer(pubstr));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey pubkey = keyFactory.generatePublic(x509);
//接收方 把字符串格式的转换回来
//私钥转换 java中提供了字节数组转公钥的类 PKCS8EncodedKeySpec
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(new BASE64Decoder().decodeBuffer(privstr));
PrivateKey priKey = keyFactory.generatePrivate(keySpec);
//公钥加密
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, pubkey);
byte[] b = cipher.doFinal("要加密的字符串".getBytes("utf-8"));
//用base64把字节数组转换为字符串
String basestr = new BASE64Encoder().encode(b);
System.out.println("加密后在用base64转换成的字符串:" + basestr);
//私钥解密
cipher.init(Cipher.DECRYPT_MODE, priKey);
//先把字符串转换成原来的字节数组
byte[] bytetext = cipher.doFinal(new BASE64Decoder().decodeBuffer(basestr));
System.out.println("解密后的数据"+ new String(bytetext,"utf-8"));
//私钥加密
cipher.init(Cipher.ENCRYPT_MODE, priKey);
byte[] pb = cipher.doFinal("私钥加密的字符串".getBytes("utf-8"));
//用base64把字节数组转换为字符串
String pbasestr = new BASE64Encoder().encode(pb);
System.out.println("私钥加密后在用base64转换成的字符串:" + pbasestr);
//公钥解密
cipher.init(Cipher.DECRYPT_MODE, pubkey);
//先把字符串转换成原来的字节数组
byte[] pbytetext = cipher.doFinal(new BASE64Decoder().decodeBuffer(pbasestr));
System.out.println("公钥解密后的数据:"+ new String(pbytetext,"utf-8"));
java加密解密初探-RSA
最新推荐文章于 2024-09-10 10:21:38 发布