java 非对称加密算法RSA实现详解

现在就为大家介绍一种基于因子分解的RSA算法,这种加密算法有两种实现形式:1、公钥加密,私钥解密;2、私钥加密,公钥解密。下面就为大家分析一下实现代码,相对于DH算法,RSA显得有些简单。

初始化密钥:

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));

根据输出的结果不难发现,公钥和私钥并不一致,私钥的长度要大于公钥。

以上是 java 非对称加密算法RSA实现详解 的全部内容, 来源链接: utcz.com/z/332624.html

回到顶部