项目中需要使用非对称加密,其实和Java后台数据交互,只需要对某些关键字段使用此种加密即可,因为加密强度大自然效率低。并且移动端和后台双方实现也都不是很难。
一、简介
RSA算法1978年出现,是第一个既能用于数据加密也能用于数字签名的算法,易于理解和操作。发明者:Ron Rivest, Adi Shamir 和 Leonard Adleman。早在1973年,英国国家通信总局的数学家Clifford Cocks就发现类似的算法,但其发现被列为绝密,直到1998年才公诸于世。
RSA基于一个数论事实:将两个大素数相乘十分容易,但想要对其乘积进行因式分解却极其困 难,因此可以将乘积公开作为加密密钥,即公钥,而两个大素数组合成私钥。公钥是可提供给任何人使用,私钥则为自己所有,供解密之用。
大感算法精妙和知识的伟大。前人种树,我辈在此乘凉。
二、原理
RSA算法是一种非对称密码算法,所谓非对称,就是指该算法需要一对密钥(公钥和私钥),使用其中一个加密,则需要用另一个才能解密。
RSA的算法涉及三个参数:n、e1、e2
n:是两个大质数p、q的积,n的二进制表示时所占用的位数,就是所谓的密钥长度。
e1和e2是一对相关的值:
e1可以任意取,但要求e1与(p-1)*(q-1)互质; 再选择e2,要求(e2*e1)mod((p-1)*(q-1))=1。
(n,e1),(n,e2)就是密钥对,其中(n,e1)为公钥,(n,e2)为私钥。
RSA加解密的算法完全相同,设A为明文,B为密文:
A=B^e2 mod n;
B=A^e1 mod n;
公钥加密,私钥解密,当然e1和e2可以互换使用
A=B^e1 mod n;
B=A^e2 mod n;
三、实现
1.获取公钥、私钥
public static final String KEY_ALGORITHM = "RSA";
private static final String PUBLIC_KEY = "RSAPublicKey";
private static final String PRIVATE_KEY = "RSAPrivateKey";
protected String publicKey;
protected String privateKey;
public void init() throws Exception {
hashMap = initKey();
privateKey = getPrivateKey(hashMap);
publicKey = getPublicKey(hashMap);
}
/**
* 初始化密钥
*
* @return
* @throws Exception
*/
public static Map<String, Object> initKey() throws Exception {
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
keyPairGen.initialize(1024);
KeyPair keyPair = keyPairGen.generateKeyPair();
// 公钥
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
// 私钥
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
Map<String, Object> keyMap = new HashMap<>(2);
keyMap.put(PUBLIC_KEY, publicKey);
keyMap.put(PRIVATE_KEY, privateKey);
return keyMap;
}
/**
* 取得私钥
*/
public static String getPrivateKey(Map<String, Object> keyMap) throws Exception {
Key key = (Key) keyMap.get(PRIVATE_KEY);
return encryptBASE64(key.getEncoded());
}
/**
* 取得公钥
*/
public static String getPublicKey(Map<String, Object> keyMap) throws Exception {
Key key = (Key) keyMap.get(PUBLIC_KEY);
return encryptBASE64(key.getEncoded());
}
public static byte[] decryptBASE64(String key) throws Exception {
return Base64.decode(key, Base64.DEFAULT);
}
public static String encryptBASE64(byte[] key) throws Exception {
return Base64.encodeToString(key, Base64.DEFAULT);
}
这是安卓端可实现的方法,其中Base64是属于安卓的类(android.util.Base64)
正常操作下,我们可以通过工具获取私钥和公钥文件。
支付宝官网:生成密钥对:链接
点击下载,文件解压目录:
点击运行,即可生成1024或2048长度的密钥。
2.加密工具类
下面贴一下加密工具代码:适合安卓和Java后端公用
RSA工具类
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;
/**
* RSA工具类
*/
public class RSAUtils {
//private static String RSA = "RSA/ECB/PKCS1Padding";
private static String RSA = "RSA";
/**
* 随机生成RSA密钥对范围:512~2048
* (默认密钥长度为1024)
*/
public static KeyPair generateRSAKeyPair() {
return generateRSAKeyPair(1024);
}
/**
* 随机生成RSA密钥对
*/
public static KeyPair generateRSAKeyPair(int keyLength) {
try {
KeyPairGenerator kpg = KeyPairGenerator.getInstance(RSA);
kpg.initialize(keyLength);
return kpg.genKeyPair();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}
/**
* 用公钥加密
*/
public static byte[] encryptDataPublic(byte[] data, PublicKey publicKey) {
try {
// 对数据加密
Cipher cipher = Cipher.getInstance(RSA);
// 编码前设定编码方式及密钥
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
// 传入编码数据并返回编码结果
return cipher.doFinal(data);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 用私钥解密
*/
public static byte[] decryptDataPrivate(byte[] data, PrivateKey privateKey) {
try {
// 对数据解密
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return cipher.doFinal(data);
} catch (Exception e) {
return null;
}
}
/**
* 用公钥解密
*/
public static byte[] decryptDataPublic(byte[] data, PublicKey publicKey) {
try {
// 对数据解密
Cipher cipher = Cipher.getInstance(RSA);
cipher.init(Cipher.DECRYPT_MODE, publicKey);
return cipher.doFinal(data);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 用私钥加密
*/
public static byte[] encryptDataPrivate(byte[] data, PrivateKey privateKey) {
try {
// 对数据加密
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
return cipher.doFinal(data);
} catch (Exception e) {
return null;
}
}
/**
* 通过公钥byte[](publicKey.getEncoded())将公钥还原,适用于RSA算法
*
* @param keyBytes
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
*/
public static PublicKey getPublicKey(byte[] keyBytes) throws NoSuchAlgorithmException,
InvalidKeySpecException {
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(RSA);
PublicKey publicKey = keyFactory.generatePublic(keySpec);
return publicKey;
}
/**
* 通过私钥byte[]将公钥还原,适用于RSA算法
*
* @param keyBytes
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
*/
public static PrivateKey getPrivateKey(byte[] keyBytes) throws NoSuchAlgorithmException,
InvalidKeySpecException {
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(RSA);
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
return privateKey;
}
/**
* 使用N、e值还原公钥
*
* @param modulus
* @param publicExponent
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
*/
public static PublicKey getPublicKey(String modulus, String publicExponent)
throws NoSuchAlgorithmException, InvalidKeySpecException {
BigInteger bigIntModulus = new BigInteger(modulus);
BigInteger bigIntPrivateExponent = new BigInteger(publicExponent);
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(bigIntModulus, bigIntPrivateExponent);
KeyFactory keyFactory = KeyFactory.getInstance(RSA);
PublicKey publicKey = keyFactory.generatePublic(keySpec);
return publicKey;
}
/**
* 使用N、d值还原私钥
*
* @param modulus
* @param privateExponent
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
*/
public static PrivateKey getPrivateKey(String modulus, String privateExponent)
throws NoSuchAlgorithmException, InvalidKeySpecException {
BigInteger bigIntModulus = new BigInteger(modulus);
BigInteger bigIntPrivateExponent = new BigInteger(privateExponent);
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(bigIntModulus, bigIntPrivateExponent);
KeyFactory keyFactory = KeyFactory.getInstance(RSA);
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
return privateKey;
}
/**
* 从字符串中加载公钥
*
* @param publicKeyStr 公钥数据字符串
* @throws Exception 加载公钥时产生的异常
*/
public static PublicKey loadPublicKey(String publicKeyStr) throws Exception {
try {
byte[] buffer = Base64Utils.decode(publicKeyStr);
KeyFactory keyFactory = KeyFactory.getInstance(RSA);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
return keyFactory.generatePublic(keySpec);
} catch (NoSuchAlgorithmException e) {
throw new Exception("无此算法");
} catch (InvalidKeySpecException e) {
throw new Exception("公钥非法");
} catch (NullPointerException e) {
throw new Exception("公钥数据为空");
}
}
/**
* 从字符串中加载私钥<br>
* 加载时使用的是PKCS8EncodedKeySpec(PKCS#8编码的Key指令)。
*
* @param privateKeyStr
* @return
* @throws Exception
*/
public static PrivateKey loadPrivateKey(String privateKeyStr) throws Exception {
try {
byte[] buffer = Base64Utils.decode(privateKeyStr);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
KeyFactory keyFactory = KeyFactory.getInstance(RSA);
return keyFactory.generatePrivate(keySpec);
} catch (NoSuchAlgorithmException e) {
throw new Exception("无此算法");
} catch (InvalidKeySpecException e) {
throw new Exception("私钥非法");
} catch (NullPointerException e) {
throw new Exception("私钥数据为空");
}
}
/**
* 从文件中输入流中加载公钥
*
* @param in 公钥输入流
* @throws Exception 加载公钥时产生的异常
*/
public static PublicKey loadPublicKey(InputStream in) throws Exception {
try {
return loadPublicKey(readKey(in));
} catch (IOException e) {
throw new Exception("公钥数据流读取错误");
} catch (NullPointerException e) {
throw new Exception("公钥输入流为空");
}
}
/**
* 从文件中加载私钥
*
* @param in 私钥文件名
* @return 是否成功
* @throws Exception
*/
public static PrivateKey loadPrivateKey(InputStream in) throws Exception {
try {
return loadPrivateKey(readKey(in));
} catch (IOException e) {
throw new Exception("私钥数据读取错误");
} catch (NullPointerException e) {
throw new Exception("私钥输入流为空");
}
}
/**
* 读取密钥信息
*
* @param in
* @return
* @throws IOException
*/
private static String readKey(InputStream in) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String readLine = null;
StringBuilder sb = new StringBuilder();
while ((readLine = br.readLine()) != null) {
if (readLine.charAt(0) == '-') {
continue;
} else {
sb.append(readLine);
sb.append('\r');
}
}
return sb.toString();
}
/**
* 打印公钥信息
* @param publicKey
*/
public static void printPublicKeyInfo(PublicKey publicKey) {
RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;
System.out.println("----------RSAPublicKey----------");
System.out.println("Modulus.length=" + rsaPublicKey.getModulus().bitLength());
System.out.println("Modulus=" + rsaPublicKey.getModulus().toString());
System.out.println("PublicExponent.length=" + rsaPublicKey.getPublicExponent().bitLength());
System.out.println("PublicExponent=" + rsaPublicKey.getPublicExponent().toString());
}
/**
* 打印公钥信息
* @param privateKey
*/
public static void printPrivateKeyInfo(PrivateKey privateKey) {
RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) privateKey;
System.out.println("----------RSAPrivateKey ----------");
System.out.println("Modulus.length=" + rsaPrivateKey.getModulus().bitLength());
System.out.println("Modulus=" + rsaPrivateKey.getModulus().toString());
System.out.println("PrivateExponent.length=" + rsaPrivateKey.getPrivateExponent().bitLength());
System.out.println("PrivatecExponent=" + rsaPrivateKey.getPrivateExponent().toString());
}
/**
* 得到密钥字符串(经过base64编码)
*/
public static String getKeyString(Key key) throws Exception {
byte[] keyBytes = key.getEncoded();
String s = Base64Utils.encode(keyBytes);
return s;
}
/**
* 16进制字符串转字节数组
* @param src 16进制字符串
* @return 字节数组
* @throws
*/
public static byte[] hexString2Bytes(String src) {
int l = src.length() / 2;
byte[] ret = new byte[l];
for (int i = 0; i < l; i++) {
ret[i] = (byte) Integer
.valueOf(src.substring(i * 2, i * 2 + 2), 16).byteValue();
}
return ret;
}
/**
* 16进制字符串转字符串
* @param src 16进制字符串
* @return 字节数组
* @throws
*/
public static String hexString2String(String src) {
String temp = "";
for (int i = 0; i < src.length() / 2; i++) {
temp = temp
+ (char) Integer.valueOf(src.substring(i * 2, i * 2 + 2),
16).byteValue();
}
return temp;
}
/**
* 字符串转16进制字符串
* @param strPart 字符串
* @return 16进制字符串
* @throws
*/
public static String string2HexString(String strPart) {
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < strPart.length(); i++) {
int ch = (int) strPart.charAt(i);
String strHex = Integer.toHexString(ch);
hexString.append(strHex);
}
return hexString.toString();
}
/**
* 字节数组转16进制字符串
* @param b 字节数组
* @return 16进制字符串
* @throws
*/
public static String bytes2HexString(byte[] b) {
StringBuffer result = new StringBuffer();
String hex;
for (int i = 0; i < b.length; i++) {
hex = Integer.toHexString(b[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
result.append(hex.toUpperCase());
}
return result.toString();
}
}
Base64工具类
import java.io.UnsupportedEncodingException;
/**
* Base64工具类
*/
public class Base64Utils {
private static char[] base64EncodeChars = new char[]
{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', '+', '/'};
private static byte[] base64DecodeChars = new byte[]
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53,
54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29,
30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1,
-1, -1, -1};
/**
* 加密
* @param data
* @return
*/
public static String encode(byte[] data) {
return decodePublic(data);
}
/**
* 解密
* @param str
* @return
*/
public static byte[] decode(String str) {
try {
return decodePrivate(str);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return new byte[]{};
}
private static byte[] decodePrivate(String str) throws UnsupportedEncodingException {
StringBuffer sb = new StringBuffer();
byte[] data = str.getBytes("US-ASCII");
int len = data.length;
int i = 0;
int b1, b2, b3, b4;
while (i < len) {
do {
b1 = base64DecodeChars[data[i++]];
} while (i < len && b1 == -1);
if (b1 == -1)
break;
do {
b2 = base64DecodeChars[data[i++]];
} while (i < len && b2 == -1);
if (b2 == -1)
break;
sb.append((char) ((b1 << 2) | ((b2 & 0x30) >>> 4)));
do {
b3 = data[i++];
if (b3 == 61)
return sb.toString().getBytes("iso8859-1");
b3 = base64DecodeChars[b3];
} while (i < len && b3 == -1);
if (b3 == -1)
break;
sb.append((char) (((b2 & 0x0f) << 4) | ((b3 & 0x3c) >>> 2)));
do {
b4 = data[i++];
if (b4 == 61)
return sb.toString().getBytes("iso8859-1");
b4 = base64DecodeChars[b4];
} while (i < len && b4 == -1);
if (b4 == -1)
break;
sb.append((char) (((b3 & 0x03) << 6) | b4));
}
return sb.toString().getBytes("iso8859-1");
}
private static String decodePublic(byte[] data) {
StringBuffer sb = new StringBuffer();
int len = data.length;
int i = 0;
int b1, b2, b3;
while (i < len) {
b1 = data[i++] & 0xff;
if (i == len) {
sb.append(base64EncodeChars[b1 >>> 2]);
sb.append(base64EncodeChars[(b1 & 0x3) << 4]);
sb.append("==");
break;
}
b2 = data[i++] & 0xff;
if (i == len) {
sb.append(base64EncodeChars[b1 >>> 2]);
sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]);
sb.append(base64EncodeChars[(b2 & 0x0f) << 2]);
sb.append("=");
break;
}
b3 = data[i++] & 0xff;
sb.append(base64EncodeChars[b1 >>> 2]);
sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]);
sb.append(base64EncodeChars[((b2 & 0x0f) << 2) | ((b3 & 0xc0) >>> 6)]);
sb.append(base64EncodeChars[b3 & 0x3f]);
}
return sb.toString();
}
}
3.使用加密
这是一个JUnit下的单元测试(上篇:Android Studio中的单元测试)
import org.junit.Test;
import java.security.PrivateKey;
import java.security.PublicKey;
/**
* To work on unit tests, switch the Test Artifact in the Build Variants view.
*/
public class ExampleUnitTest {
//生成的公钥
private String publicKeyStr = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCKqs8+U6gJAzmJQeu2IiAttobx67DUs5hYu95Xrc/tWoOu12W+osarqvLNOohaqhoogHj6T+/NUEZxR77sXfm5WZ1lO3RjPjGO9w2Q9SZC6J9mUpwJytIunwEwR8y+e2FIotwc/fbRNzQFYIVJdUBIZkoEBwux3okZskxxrBsvyQIDAQAB";
//生成的私钥
private String privateKeyStr = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAIqqzz5TqAkDOYlB67YiIC22hvHrsNSzmFi73letz+1ag67XZb6ixquq8s06iFqqGiiAePpP781QRnFHvuxd+blZnWU7dGM+MY73DZD1JkLon2ZSnAnK0i6fATBHzL57YUii3Bz99tE3NAVghUl1QEhmSgQHC7HeiRmyTHGsGy/JAgMBAAECgYAXgmQGdhpsBL7xdVqoE1sPRP3V8BaXyScQDDHi/ZXd8NWYg+49Bs3V9vKZNs49SM+MhFN+ZKUMUwrOU9KbskcPFDpQFvMIXQYeRxhyMygBR5ZsiFsnp6hpjxY7IZceQDZLAguL+JfVvBQV4sHBtWHo1wtdZ1qmX6pN6gyAa5JB3QJBANQ9kp6KbxpUr2IGWleaeArBgBE4CKu8uWqHW5XTX71AMAK5ZYrq8gWRQwu5D0rZ/GdZLDnwm+6+NyqDB7xOUZsCQQCnQei/ofgCcX+61/N2WZPm7a3hjOxvhAXc826hkE9vtfoisRrXe7OakKxgpg/WZ1oBYNqwDQOuexszhOGhCHxrAkBR7wMvGRoS/CZInVM7BnLZFCIwg4U1Z0HdEiwVBuiq0qC2LIQ6wMB1zcIoQGTa7JQ4AYDFTVGlNOFvE+5kj4eJAkEAgEV+z4DTKGSNFelKMSiv0jnT0Zf3N+rjaDlVThjToxPH2tVChaG78z0ixhh1KvQmRcpWzQ+eFDEbgl5Vf993MwJAASssnHLpAwv3D6DjK6lphMAPexZFHMHYWy9C0S4KHcf+gTGfXT2qPh8gLysAvS1+D1YFmEy9zMS8X77dHMLiTA==";
private PublicKey publicKey;
private PrivateKey privateKey;
//明文
String source = "zachary,加油吧";
@Test
public void test() throws Exception {
// 初始化获得公钥、私钥
publicKey = RSAUtils.loadPublicKey(publicKeyStr);
privateKey = RSAUtils.loadPrivateKey(privateKeyStr);
//加密
byte[] encryptByte = RSAUtils.encryptDataPublic(source.getBytes(), publicKey);
//传输数据:加密
//String afterencrypt = Base64Utils.encode(encryptByte);
//传输数据:解密
//byte[] encryptContent = Base64Utils.decode(afterencrypt);
//解密
byte[] decryptByte = RSAUtils.decryptDataPrivate(encryptByte, privateKey);
//获得明文
String decryptStr = new String(decryptByte);
System.out.print(decryptStr);
//私钥加密、公钥解密
encryptByte = RSAUtils.encryptDataPrivate(source.getBytes(), privateKey);
decryptByte = RSAUtils.decryptDataPublic(encryptByte, publicKey);
decryptStr = new String(decryptByte);
System.out.print(decryptStr);
}
}
RSA只适合用作关键、私密字段加密,正常的数据传输可以用AES加密。