RSA加密与解密(Java实现)
程序员文章站
2022-05-15 16:59:01
...
RSA的应用
RSA是一种非对称加密算法。现在,很多登陆表单的密码的都采用RSA加密,例如京东中的登陆使用公钥对密码进行加密。
Base64编码
apache.commons-codex包提供了许多编码格式转换,例如Base64。
以下为Base64编码表
使用commons-codec进行Base64对字符串进行编码与解码的程序如下:
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.10</version>
</dependency>
package com.qian.encoded;
import org.apache.commons.codec.binary.Base64;
public class Base64Coded {
public static void main(String[] args) {
String string = "qianyang123";
//编码
String encode = encode(string.getBytes());
System.out.println(string + "\t编码后的字符串为:" + encode);
//解码
String decode = decode(encode.getBytes());
System.out.println(encode + "\t字符串解码后为:" + decode);
}
//base64 解码
public static String decode(byte[] bytes) {
return new String(Base64.decodeBase64(bytes));
}
//base64 编码
public static String encode(byte[] bytes) {
return new String(Base64.encodeBase64(bytes));
}
}
程序的输出结果为:
qianyang123 编码后的字符串为:cWlhbnlhbmcxMjM=
cWlhbnlhbmcxMjM= 字符串解码后为:qianyang123
RSA加密与解密
使用RSA一般需要产生公钥和私钥,当采用公钥加密时,使用私钥解密;采用私钥加密时,使用公钥解密。以下为Java程序:
package com.yinhai.lipan.rsa;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import java.security.*;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
/**
* Hello world!
*
*/
public class App
{
private static Map<Integer,String> keyMap=new HashMap<>();
public static void main( String[] args ) throws Exception {
//生成公钥和私钥
getKeyPair();
//加密字符串
String password="123456";
System.out.println("随机生成的公钥为:"+keyMap.get(0));
System.out.println("随机生成的私钥为:"+keyMap.get(1));
String passwordEn=encrypt(password,keyMap.get(0));
System.out.println(password+"\t加密后的字符串为:"+passwordEn);
String passwordDe=decrypt(passwordEn,keyMap.get(1));
System.out.println("还原后的字符串为:"+passwordDe);
}
/**
* 随机生成**对
* @throws NoSuchAlgorithmException
*/
public static void getKeyPair() throws Exception {
//KeyPairGenerator类用于生成公钥和**对,基于RSA算法生成对象
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
//初始化**对生成器,**大小为96-1024位
keyPairGen.initialize(1024,new SecureRandom());
//生成一个**对,保存在keyPair中
KeyPair keyPair = keyPairGen.generateKeyPair();
// RSAPublicKey privateKey = (RSAPublicKey) keyPair.getPrivate();//得到私钥
// RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();//得到公钥
PrivateKey privateKey = keyPair.getPrivate();//得到私钥
PublicKey publicKey = keyPair.getPublic();//得到公钥
//得到公钥字符串
String publicKeyString=new String(Base64.encodeBase64(publicKey.getEncoded()));
//得到私钥字符串
String privateKeyString=new String(Base64.encodeBase64(privateKey.getEncoded()));
//将公钥和私钥保存到Map
keyMap.put(0,publicKeyString);//0表示公钥
keyMap.put(1,privateKeyString);//1表示私钥
}
/**
* RSA公钥加密
*
* @param str
* 加密字符串
* @param publicKey
* 公钥
* @return 密文
* @throws Exception
* 加密过程中的异常信息
*/
public static String encrypt(String str,String publicKey) throws Exception {
//base64编码的公钥
byte[] decoded = Base64.decodeBase64(publicKey);
RSAPublicKey pubKey= (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
//RAS加密
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE,pubKey);
String outStr=Base64.encodeBase64String(cipher.doFinal(str.getBytes("UTF-8")));
return outStr;
}
/**
* RSA私钥解密
*
* @param str
* 加密字符串
* @param privateKey
* 私钥
* @return 铭文
* @throws Exception
* 解密过程中的异常信息
*/
public static String decrypt(String str,String privateKey) throws Exception {
//Base64解码加密后的字符串
byte[] inputByte = Base64.decodeBase64(str.getBytes("UTF-8"));
//Base64编码的私钥
byte[] decoded = Base64.decodeBase64(privateKey);
PrivateKey priKey = KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
//RSA解密
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE,priKey);
String outStr=new String(cipher.doFinal(inputByte));
return outStr;
}
}
在程序中,我们首先利用genKeyPair()函数生成公钥和私钥并将其保存到Map集合中。然后,基于产生的公钥对明文进行加密。针对已经已经加密的密文,我们再次使用私钥解密,得到明文。
上述程序的输出结果为:
随机生成的公钥为:MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCcjCMNuYGDhMD6ekWrKAZU4yE2Bj2mhJn6hJLiw6mpyu6sXITjbqyt+ZCpgmHNTrEYxaRPYTdrKTAEynl28Sk6pzquXEEk4oHivFcDZiDOam8JuyYlT1zDRs/muWtyv1hrDPZA0/EvTH6WCHIxToVYRvLDRH4/TB5u2MPAGKMx3wIDAQAB
随机生成的私钥为:MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAJyMIw25gYOEwPp6RasoBlTjITYGPaaEmfqEkuLDqanK7qxchONurK35kKmCYc1OsRjFpE9hN2spMATKeXbxKTqnOq5cQSTigeK8VwNmIM5qbwm7JiVPXMNGz+a5a3K/WGsM9kDT8S9MfpYIcjFOhVhG8sNEfj9MHm7Yw8AYozHfAgMBAAECgYBZz1O05f3VU+3aRRd+78FiJcPB2Ka5x00HGdOi4JmPXWq724Apci8CyDAj7zbosAKNsaVoHN/MTJ7NwNMaV5RMuVSHWYLPlJgvNRGgHgDZtgpTF8bpBefwZmHCuHplR+/n/uAqwAhvZMKq9L/vX3STolzX7rstGePC/VriiOO0UQJBANrM5YbrBKz/URT+4kRQero4DV2Tfs1QnBexqA52KsIK5VIEeufHSSGymBB9LhNS3z3vOksYIvZF/Ef/m/lfLMsCQQC3Kbtkcbi33FanMFSOIugoE/QH4FkLcahcHC5WqBxwCbFeq2KzxzOaaE/lm5/5w6TnupG0wgSbIHBFJc7uWWC9AkBCd74+d0TLXSB/lVKdWCmASqjcxYLe0l8o34JjKkig+/hgKxY/NQ4lW4DQeYa2vhUtVnBKAcIVOHuET8VNQzlzAkEAhfl3gXwRUiNQGtCmOKVdzNrzd8NpPo6vSFiwqGAlFOpyG74e30NJAptkPZ28wVOSzpFQPLhh6BotJNcH6p3jvQJBALEkM2ju44rTXdPyTneX6ZPCQ96pZotOZUuufUGHgsk1iqrzDFrS5h/5WIk8ttO5Nubpu+L8qd2G4i/vOqtFQLQ=
123456 加密后的字符串为:iOtM4l+nrkePMxEcLeCa6n7jw1VwiWwtC1o6m0DpDowpsbZ7Pm1ZL2isb+TkoZU0uCgq6T3AJW7GzZ/3oESrQQwKjXHVA6yH3BfAJvXfw9uKUJIudOYpvgIn+1zvw3hsocuYiWLBARInZV+40leHl0nVfv2EcmxsEhKuOr5xFcM=
还原后的字符串为:123456
上一篇: java实现非对称加密