RSA加解密java中的使用
- 使用环境:eclipse + maven,无maven猿友可自行下载这两个jar包:bcprov-jdk16-1.4.5.jar 和 commons-codec-1.6.jar
- maven的猿友添加如下依赖:
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk16</artifactId>
<version>1.45</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.6</version>
</dependency>
-
目录结构,包含三个类。
生成密钥,公钥和私钥
package com.luo.util;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Security;
import org.apache.commons.codec.binary.Base64;
public class RSAKeyCreater
public class RSAKeyCreater {
public static void createKeyPairs() {
try {
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", "BC");
generator.initialize(512, new SecureRandom());
KeyPair pair = generator.generateKeyPair();
PublicKey pubKey = pair.getPublic();
PrivateKey privKey = pair.getPrivate();
byte[] pk = pubKey.getEncoded();
byte[] privk = privKey.getEncoded();
String strpk = new String(Base64.encodeBase64(pk));
String strprivk = new String(Base64.encodeBase64(privk));
System.out.println("公钥Base64编码:" + strpk);
System.out.println("私钥Base64编码:" + strprivk);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String args[]){
creatkeyPairs()
}
}
-
运行该类main方法控制台输入如下,获得公钥和私钥,公钥用于加密,私钥用于解密:
-
RSA加密解密类
- RsaUtil.java内容如下:
package com.luo.util;
import java.security.PrivateKey;
import java.security.PublicKey;
import javax.crypto.Cipher;
import org.apache.commons.codec.binary.Base64;
public class RsaUtil {
/**
* luoguohui
* 2015-12-26
* RSA加密
*/
public String encryptData(String data, PublicKey publicKey) {
try {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] dataToEncrypt = data.getBytes("utf-8");
byte[] encryptedData = cipher.doFinal(dataToEncrypt);
String encryptString = Base64.encodeBase64String(encryptedData);
return encryptString;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* luoguohui
* 2015-12-26
* RSA解密
*/
public String decryptData(String data, PrivateKey privateKey) {
try {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] descryptData = Base64.decodeBase64(data);
byte[] descryptedData = cipher.doFinal(descryptData);
String srcData = new String(descryptedData, "utf-8");
return srcData;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
- 加密解密测试
- RSATest.java内容如下:
package com.luo.util;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Security;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import org.apache.commons.codec.binary.Base64;
public class RSATest {
public static void testRsa() {
try {
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
String strpk = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAJPSsAm9Po08VtGKQx86TuOYu/7BTOtwYlFQvjQCEs3aTeUOH3p9pgd3pw14Num0n/l3Sk3d1av4hzZJvlODfScCAwEAAQ==";
String strprivk = "MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEAk9KwCb0+jTxW0YpDHzpO45i7/sFM63BiUVC+NAISzdpN5Q4fen2mB3enDXg26bSf+XdKTd3Vq/iHNkm+U4N9JwIDAQABAkAch9iUOKNfDRtQnBfyagWZ5fu64sIe2vUO7r+XOCM6+a/BvKV+5aMRpR6ts8OyEz9F+KCagc8eSEO0DAFjurQ5AiEA72jh09XwAHpvUONQu8JyziZtB5Cpf/y2iCC3ucxJ510CIQCeEQ+2sd4jC7P+wdCB0K1HxXtslxD3Bq50yVtsyI3CUwIhAJUpQ4o4QNALeE9tUV+qRt0qE8Qi3Xhge1lVCSM5pNIBAiACY0OXgOxYHy8i5A6gR2S2ttb8dvO8p48vGHOXGxh5HQIgfiKMcSTfflaQBBgzDFvaVnsfs2ajbv9tNcWuAP7u6aA=";
X509EncodedKeySpec pubX509 = new X509EncodedKeySpec(Base64.decodeBase64(strpk.getBytes()));
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decodeBase64(strprivk.getBytes()));
KeyFactory keyf = KeyFactory.getInstance("RSA", "BC");
PublicKey pubKey = keyf.generatePublic(pubX509);
PrivateKey privKey = keyf.generatePrivate(priPKCS8);
RsaUtil rsaUtil = new RsaUtil();
String data = "luoguohui";
System.out.println("加密前字符串:data=" + data);
String encryptData = null;
if (pubKey != null && (data != null && !data.equals(""))) {
encryptData = rsaUtil.encryptData(data, pubKey);
System.out.println("加密后字符串:encryptData=" + encryptData);
}
String descryptData = null;
if (privKey != null && (encryptData != null && !encryptData.equals(""))) {
descryptData = rsaUtil.decryptData(encryptData, privKey);
System.out.println("解密后字符串:descryptData=" + descryptData);
}
}catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String args[]) {
testRsa();
}
}
其中strpk和strprivk是2.1中运行获得公钥私钥串
-
运行RSATest.java的main方法,得到运行结果如下: