java rsa非对称加密算法_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));

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值