Flask接口签名sign原理与实例代码浅析
439
2023-01-01
java 非对称加密算法RSA实现详解
现在就为大家介绍一种基于因子分解的RSA算法,这种加密算法有两种实现形式:1、公钥加密,私钥解密;2、私钥加密,公钥解密。下面就为大家分析一下实现代码,相对于DH算法,bkzsEgmHfqbkzsEgmHfqRSA显得有些简单。
初始化密钥:
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(512);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
RSAPrivateKey rsaprivateKey = (RSAPrivateKey)keyPair.getPrivate();//私有密钥
RSAPublicKey rsapublicKey = (RSAPublicKey)keyPair.getPublic();//公有密钥
System.out.println("privateKey : "+Base64.encodeBase64String(rsaprivateKey.getEncoded()));
System.out.println("publicKey : "+Base64.encodeBase64String(rsapublicKey.getEncoded()));
1、私钥加密,公钥解密:
//私钥加密,公钥解密--加密
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(rsaprivateKey.getEncoded());
KeyFactory privateKeyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = privateKeyFactory.generatePrivate(pkcs8EncodedKeySpec);
Cipher privateCipher = Cipher.getInstance("RSA");
privateCipher.init(Cipher.ENCRYPT_MODE, privateKey);
byte[] result = privateCipher.doFinal(src.getBytes());
System.out.println("私钥加密,公钥解密--加密:"+Base64.encodeBase64String(result));
//私钥加密,公钥解密--解密
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(rsapublicKey.getEncoded());
KeyFactory publicKeyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = publicKeyFactory.generatePublic(x509EncodedKeySpec);
Cipher publicCipher = Cipher.getInstance("RSA");
publicCipher.init(Cipher.DECRYPT_MODE, publicKey);
result = publicCipher.doFinal(result);
System.out.println("私钥加密,公钥解密--解密:"+new String(result));
2、公钥加密,私钥解密:
//公钥加密,私钥解密---加密
x509EncodedKeySpec = new X509EncodedKeySpec(rsapublicKey.getEncoded());
publicKeyFactory = KeyFactory.getInstance("RSA");
publicKey = publicKeyFactory.generatePublic(x509EncodedKeySpec);
publicCipher = Cipher.getInstance("RSA");
publicCipher.init(Cipher.ENCRYPT_MODE, publicKey);
result = publicCipher.doFinal(src.getBytes());
System.out.println("公钥加密,私钥解密---加密:"+Base64.encodeBase64String(result));
//公钥加密,私钥解密---解密
pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(rsaprivateKey.getEncoded());
privateKeyFactory = KeyFactory.getInstance("RSA");
privateKey = privateKeyFactory.generatePrivate(pkcs8EncodedKeySpec);
privateCipher = Cipher.getInstance("RSA");
privateCipher.init(Cipher.DECRYPT_MODE, privateKey);
result = privateCipher.doFinal(result);
System.out.println("公钥加密,私钥解密---解密:"+new String(result));
根据输出的结果不难发现,公钥和私钥并不一致,私钥的长度要大于公钥。
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~