RSA加解密java中的使用
- 使用環(huán)境: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>
-
目錄結(jié)構(gòu)昼扛,包含三個類韭脊。
生成密鑰撤蚊,公鑰和私鑰
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()
}
}
-
運(yùn)行該類main方法控制臺輸入如下初澎,獲得公鑰和私鑰金抡,公鑰用于加密举农,私鑰用于解密:
-
RSA加密解密類
- RsaUtil.java內(nèi)容如下:
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內(nèi)容如下:
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中運(yùn)行獲得公鑰私鑰串
-
運(yùn)行RSATest.java的main方法荆针,得到運(yùn)行結(jié)果如下: