被这个小问题困了2天,终于被干掉了。
安卓中利用RSA算法加密和解密
整个流程大致为:生成密钥对->获取公私钥->对明(密)文加(解)密。
package com.cc.encrypttest;
import android.util.Base64;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
/**
* Created by hcc on 2016/11/8.
*/
public class SignUtils {
private static final String ALGORITHM = "RSA";
/**
* 从字符串中加载公钥
*
* @param publicKeyStr 公钥数据字符串
* @return
* @throws Exception 加载公钥时产生的异常
*/
public static RSAPublicKey loadPublicKeyByStr(String publicKeyStr) throws Exception {
try {
byte[] buffer = Base64.decode(publicKeyStr, Base64.DEFAULT);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
return (RSAPublicKey) keyFactory.generatePublic(keySpec);
} catch (NoSuchAlgorithmException e) {
throw new Exception("无此算法");
} catch (InvalidKeySpecException e) {
throw new Exception("公钥非法");
} catch (NullPointerException e) {
throw new Exception("公钥数据为空");
}
}
/**
* 从字符串中加载私钥
*
* @param privateKeyStr
* @return
* @throws Exception
*/
public static RSAPrivateKey loadPrivateKeyByStr(String privateKeyStr) throws Exception {
try {
byte[] buffer = Base64Utils.decode(privateKeyStr);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
} catch (NoSuchAlgorithmException e) {
throw new Exception("无此算法");
} catch (InvalidKeySpecException e) {
throw new Exception("私钥非法");
} catch (NullPointerException e) {
throw new Exception("私钥数据为空");
}
}
/**
* 公钥加密过程
*
* @param publicKey 公钥
* @param plainTextData 明文数据
* @return
* @throws Exception 加密过程中的异常信息
*/
public static String encrypt(RSAPublicKey publicKey, byte[] plainTextData) throws Exception {
if (publicKey == null) {
throw new Exception("加密公钥为空, 请设置");
}
Cipher cipher = null;
try {
// 必须使用RSA/ECB/PKCS1Padding而不是RSA,否则每次加密结果一样
cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] output = cipher.doFinal(plainTextData);
return Base64Utils.encode(output);
} catch (NoSuchAlgorithmException e) {
throw new Exception("无此加密算法");
} catch (NoSuchPaddingException e) {
e.printStackTrace();
return null;
} catch (InvalidKeyException e) {
throw new Exception("加密公钥非法,请检查");
} catch (IllegalBlockSizeException e) {
throw new Exception("明文长度非法");
} catch (BadPaddingException e) {
throw new Exception("明文数据已损坏");
}
}
/**
* 私钥解密过程
*
* @param privateKey 私钥
* @param cipherData 密文数据
* @return 明文
* @throws Exception 解密过程中的异常信息
*/
public static byte[] decrypt(RSAPrivateKey privateKey, byte[] cipherData) throws Exception {
if (privateKey == null) {
throw new Exception("解密私钥为空,请设置");
}
Cipher cipher = null;
try {
// 必须使用RSA/ECB/PKCS1Padding而不是RSA,否则解密会乱码
cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] output = cipher.doFinal(cipherData);
return output;
} catch (NoSuchAlgorithmException e) {
throw new Exception("无此解密算法");
} catch (NoSuchPaddingException e) {
e.printStackTrace();
return null;
} catch (InvalidKeyException e) {
throw new Exception("解密私钥非法,请检查");
} catch (IllegalBlockSizeException e) {
throw new Exception("密文长度非法");
} catch (BadPaddingException e) {
throw new Exception("密文数据已损坏");
}
}
/**
* 生成公私钥对
*
* @return
* @throws NoSuchAlgorithmException
*/
public static Map<String, String> generateKey() throws NoSuchAlgorithmException {
Map<String, String> keyMap = new HashMap<>();
KeyPairGenerator keygen = KeyPairGenerator.getInstance(ALGORITHM);
SecureRandom random = new SecureRandom();
// 初始化加密
keygen.initialize(1024, random);
// 取得密钥对
KeyPair kp = keygen.generateKeyPair();
RSAPrivateKey privateKey = (RSAPrivateKey) kp.getPrivate();
String privateKeyString = Base64Utils.encode(privateKey.getEncoded());
RSAPublicKey publicKey = (RSAPublicKey) kp.getPublic();
String publicKeyString = Base64Utils.encode(publicKey.getEncoded());
keyMap.put("publicKey", publicKeyString);
keyMap.put("privateKey", privateKeyString);
return keyMap;
}
}
RSA算法每次加密结果会不相同,因此这里for循环10次测试
package com.cc.encrypttest;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private String publicKey;
private String privateKey;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
Map<String, String> map = SignUtils.generateKey();
publicKey = map.get("publicKey");
privateKey = map.get("privateKey");
Log.d("====公私钥", publicKey + "\n" + privateKey);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
new Thread() {
@Override
public void run() {
super.run();
for (int i = 0; i < 10; i++) {
String a = encryptByPublic("123456");
Log.d("===加密", a);
String b = decryptByPrivate(a);
Log.d("===解密", b);
}
}
}.start();
}
// 公钥加密
private String encryptByPublic(String num) {
String encrypt = null;
try {
encrypt = SignUtils.encrypt(SignUtils.loadPublicKeyByStr(publicKey), num.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
return encrypt;
}
//私钥解密
private String decryptByPrivate(String encryptStr) {
byte[] decrypt = null;
try {
decrypt = SignUtils.decrypt(SignUtils.loadPrivateKeyByStr(privateKey), Base64Utils.decode(encryptStr));
} catch (Exception e) {
e.printStackTrace();
}
return new String(decrypt);
}
}
先获取到公私钥的字符串,然后调用 loadPublicKeyByStr(String) 和 loadPrivateKeyByStr(String)
得到返回值类型为 RSAPublicKey 和 RSAPrivateKey 的公私钥。
得到的公私钥:
公钥:
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC+lPAao8SRhomkqFbNZRcLW+TNIoAflw3iMh+V9bSX3/Dl7YsqHr+yS4QUVTFM/WRNC2cxm5PRoi1H93rezWe/6HuaDeo7xpZxNG09jIirGvSzW9Z/bmwBw4rm3Af88fJJk5zSf1NMIxOuRGA4WtzZQluVvmThofgEMR5AUEL8RQIDAQAB
私钥:MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAL6U8BqjxJGGiaSoVs1lFwtb5M0igB+XDeIyH5X1tJff8OXtiyoev7JLhBRVMUz9ZE0LZzGbk9GiLUf3et7NZ7/oe5oN6jvGlnE0bT2MiKsa9LNb1n9ubAHDiubcB/zx8kmTnNJ/U0wjE65EYDha3NlCW5W+ZOGh+AQxHkBQQvxFAgMBAAECgYBJAiFg8y/QV+vOyjZGhN1pGpDyDK9sap+E8ZKsDe5a6A0O6AsR3amuEcPNTj2OstuDsESd+m2MN0aFdUb6p1GAx8CmpxhjqDzWvtFnN1Wklcg3GAaIUm84dEXQwAUscYoZWI319VhvbyNTHGzF22gzOxGY62pC71BaseDcme10WQJBAN2m/+gyeYXljw2bq1hlBETmdcZ43EuecOGXl+/2KbtBEElGPUL4sYLIaQ7EH2pCw+g9tJ1EqiBEivRMHb226OsCQQDcHVy0R0KqFGTRBYNZgwh3QiIXLKYAZ11qHYMxRAJBFmMXKFM/1lLYY453LRexqrfQeOqPsAIPPUsAyWwQDGOPAkEA0g77RXXYX0G/wdi+mOYbFqUGBtLxi6SbO+BruJkk0XaG1bqAQmDn8Za2oazSTOT7PrSD3+t8A1qSCZW9NdcLgwJAOOpWuD7c3AGd9/ZG+nRJUh0Fl5xx6BTSMMgkzi5Zrt7NDIXe0NjoXw+PHP3J7KTKFtvNOw412h7tL+zlRlkNvQJAZxDhrnDB4vJWmsMQLKNrb0b57gigKBeUhXYr3EtSdU278imGNdfIFA9uMy/3jY7TpkkT7wwP0RjMch7VC7aNRg==
然后利用这对公私钥对字符串“123456”进行加密解密。
得到十次加解密结果为:
===加密: RQcLoT03vIYfmMC9FqXCXzZkN83VOhZp1PwBz5Z1f4NPJZljkQe2EPsKRdz2POcXbYguXyydvYp6f/DpzLVYxqWX3wKvIZeQnKOroIv8+Orfi9tcYAs1Y0s1mtqYjYURAP45sWiqv/py60QsZBrRnsDI56pK7afJNXRsG37Ei+Q=
===解密: 123456
===加密: BvYfWijM6rDS6D1xCSZD1ebFEFvgEbgA5Lf9IO6wtzJkiO8eMttTt2+Wpr3bgjcWIsTjAruQcksT8PRcr2EDWhmXog1rVvND8GES978sxOUC31Tc/25CPHUuJBPxFKvHh1F0Mv0NNQX51zjs64zRn4MESjM2wl5wjkhAmXxyyOg=
===解密: 123456
===加密: Xz0wtJ/hPMIk1FgBZ8udQAeDg6jTBomDcgTDTiVHhtuw+5cSMrHfxREKS/3OzDfonzmBUFb84myDAes8+df6J/kKQH2om5ledI/hVog8ACKSQ3SPdd+5yxDDqBzY8LeOgek4Afs7S0v2l02fysiB6BOfGiD2rceWjTKUYTcoFWM=
===解密: 123456
===加密: fOkd33yu1i9OksNW5e4xaTPmA0V5G6gK2QQKT9cwAJec1B9WenhsvxyT6uakKkfsoLNHCjRTvZJTgggVdK/nz/3UbFal+jfE/A0CdhhtCaGo5azOl2jgJ79qexB6DAFYmVtNWrPilE34OwoJ541yJaV/SUcl2GrYvs5yrN6aN+Q=
===解密: 123456
===加密: iF0XUozewljyWLn31tcfcwRT47W51ME17c/ekFVHGaaopDm+o+/EJ+NnFzA0GFnziIw4uGB849Tcw1tnWmQrkVXWSRAahdLVXzzh8GAeK9REO0XxVILzA4G7eGidod6e1QKOEVWPiM610af9B65uUXl3erlDdrSbRUfz4dmDZ/E=
===解密: 123456
===加密: qICAi6mDTstJeKzhLvxSSPWlaS95FHKwjtkcL4zv2XpWjpSBGBrtBrerrA8mJWjIsJPbW8BJ2kjKNxo7b/RMBG+jzmw7YwoTpxkNQHWQYrnSJmiuspMO8wPqg5xkkjQ92kKvYcgfYwOFYiJ+NI6vOElHFmgX7Srssn6j89GCAq0=
===解密: 123456
===加密: rZQ1Kw/sf5IBYmFfERq836LYla+JvFANIP56Mrjv0CbC60UlIp4M2wVG839NgaTL9vTFa22YRsowXrrMYklmW6Z9WV2K+U8uXfk8OJS6PUTI4E8ORWl3OuB/xDmG+FXB6D0Joj9MBUtLu1n9vcaCu2RNk4nRZNb3dZ644TEF+RI=
===解密: 123456
===加密: feyQuCnKSahc33WRc91VDY08Bba2JbmY4uk5wlPv32NIaPlZVpzxzhEDobOqsKKxJNNeYetTuqv814vBH8oDuG7szOK8+8hyPwdnXHTmUhEb84/T2m9wo5CM6kuwBz2ns+w0A8OLBfSn5h1TnJiSn0WwPAEm5zvqU4eGJ1sUP4I=
===解密: 123456
===加密: KM/1JN+piLGC9aSa3akuZKe2Zac0aeZdBsqWxuCG69TmmKTwoZFHh2y38hzGHevKQWeO+gnE+toAzdiVzLQPrlUS6dtVf31XNwZFo0bwtrHamRztb90Ui2mNuuXYuPME7OL/0W6QR3supN4KdkmGWva+B4m+qI8NjJ/kdT1gvTg=
===解密: 123456
===加密: WhKtrS6Zuoj/72jsJ0W/L9YpHl0MxmSdij5xtl8QXWKMO49vrkewqJXiilbEQ1U/OBxSUkj+9EgJ4ElA3oTk7dluZIsRlHstuTxUD99l6bKjMkkrwCR50yYs3qzw82V5ZJaSbNmp9Nu3J9nLKdRSgrV18vpH2XaBsK8J9ay671Y=
===解密: 123456
可以发现虽然十次加密结果不一样,但是解密的结果却是一样的,说明算法没问题。
这里还用到了Base64工具类对字节进行编码和解码。
注意:这类的Base64并不是android.util包下的类
package com.cc.encrypttest;
public final class Base64Utils {
private static final int BASELENGTH = 128;
private static final int LOOKUPLENGTH = 64;
private static final int TWENTYFOURBITGROUP = 24;
private static final int EIGHTBIT = 8;
private static final int SIXTEENBIT = 16;
private static final int FOURBYTE = 4;
private static final int SIGN = -128;
private static char PAD = '=';
private static byte[] base64Alphabet = new byte[BASELENGTH];
private static char[] lookUpBase64Alphabet = new char[LOOKUPLENGTH];
static {
for (int i = 0; i < BASELENGTH; ++i) {
base64Alphabet[i] = -1;
}
for (int i = 'Z'; i >= 'A'; i--) {
base64Alphabet[i] = (byte) (i - 'A');
}
for (int i = 'z'; i >= 'a'; i--) {
base64Alphabet[i] = (byte) (i - 'a' + 26);
}
for (int i = '9'; i >= '0'; i--) {
base64Alphabet[i] = (byte) (i - '0' + 52);
}
base64Alphabet['+'] = 62;
base64Alphabet['/'] = 63;
for (int i = 0; i <= 25; i++) {
lookUpBase64Alphabet[i] = (char) ('A' + i);
}
for (int i = 26, j = 0; i <= 51; i++, j++) {
lookUpBase64Alphabet[i] = (char) ('a' + j);
}
for (int i = 52, j = 0; i <= 61; i++, j++) {
lookUpBase64Alphabet[i] = (char) ('0' + j);
}
lookUpBase64Alphabet[62] = (char) '+';
lookUpBase64Alphabet[63] = (char) '/';
}
private static boolean isWhiteSpace(char octect) {
return (octect == 0x20 || octect == 0xd || octect == 0xa || octect == 0x9);
}
private static boolean isPad(char octect) {
return (octect == PAD);
}
private static boolean isData(char octect) {
return (octect < BASELENGTH && base64Alphabet[octect] != -1);
}
/**
* Encodes hex octects into Base64Utils
*
* @param binaryData
* Array containing binaryData
* @return Encoded Base64Utils array
*/
public static String encode(byte[] binaryData) {
if (binaryData == null) {
return null;
}
int lengthDataBits = binaryData.length * EIGHTBIT;
if (lengthDataBits == 0) {
return "";
}
int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP;
int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP;
int numberQuartet = fewerThan24bits != 0 ? numberTriplets + 1
: numberTriplets;
char encodedData[] = null;
encodedData = new char[numberQuartet * 4];
byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0;
int encodedIndex = 0;
int dataIndex = 0;
for (int i = 0; i < numberTriplets; i++) {
b1 = binaryData[dataIndex++];
b2 = binaryData[dataIndex++];
b3 = binaryData[dataIndex++];
l = (byte) (b2 & 0x0f);
k = (byte) (b1 & 0x03);
byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2)
: (byte) ((b1) >> 2 ^ 0xc0);
byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4)
: (byte) ((b2) >> 4 ^ 0xf0);
byte val3 = ((b3 & SIGN) == 0) ? (byte) (b3 >> 6)
: (byte) ((b3) >> 6 ^ 0xfc);
encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)];
encodedData[encodedIndex++] = lookUpBase64Alphabet[(l << 2) | val3];
encodedData[encodedIndex++] = lookUpBase64Alphabet[b3 & 0x3f];
}
// form integral number of 6-bit groups
if (fewerThan24bits == EIGHTBIT) {
b1 = binaryData[dataIndex];
k = (byte) (b1 & 0x03);
byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2)
: (byte) ((b1) >> 2 ^ 0xc0);
encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
encodedData[encodedIndex++] = lookUpBase64Alphabet[k << 4];
encodedData[encodedIndex++] = PAD;
encodedData[encodedIndex++] = PAD;
} else if (fewerThan24bits == SIXTEENBIT) {
b1 = binaryData[dataIndex];
b2 = binaryData[dataIndex + 1];
l = (byte) (b2 & 0x0f);
k = (byte) (b1 & 0x03);
byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2)
: (byte) ((b1) >> 2 ^ 0xc0);
byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4)
: (byte) ((b2) >> 4 ^ 0xf0);
encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)];
encodedData[encodedIndex++] = lookUpBase64Alphabet[l << 2];
encodedData[encodedIndex++] = PAD;
}
return new String(encodedData);
}
/**
* Decodes Base64Utils data into octects
*
* @param encoded
* string containing Base64Utils data
* @return Array containind decoded data.
*/
public static byte[] decode(String encoded) {
if (encoded == null) {
return null;
}
char[] base64Data = encoded.toCharArray();
// remove white spaces
int len = removeWhiteSpace(base64Data);
if (len % FOURBYTE != 0) {
return null;// should be divisible by four
}
int numberQuadruple = (len / FOURBYTE);
if (numberQuadruple == 0) {
return new byte[0];
}
byte decodedData[] = null;
byte b1 = 0, b2 = 0, b3 = 0, b4 = 0;
char d1 = 0, d2 = 0, d3 = 0, d4 = 0;
int i = 0;
int encodedIndex = 0;
int dataIndex = 0;
decodedData = new byte[(numberQuadruple) * 3];
for (; i < numberQuadruple - 1; i++) {
if (!isData((d1 = base64Data[dataIndex++]))
|| !isData((d2 = base64Data[dataIndex++]))
|| !isData((d3 = base64Data[dataIndex++]))
|| !isData((d4 = base64Data[dataIndex++]))) {
return null;
}// if found "no data" just return null
b1 = base64Alphabet[d1];
b2 = base64Alphabet[d2];
b3 = base64Alphabet[d3];
b4 = base64Alphabet[d4];
decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
decodedData[encodedIndex++] = (byte) (b3 << 6 | b4);
}
if (!isData((d1 = base64Data[dataIndex++]))
|| !isData((d2 = base64Data[dataIndex++]))) {
return null;// if found "no data" just return null
}
b1 = base64Alphabet[d1];
b2 = base64Alphabet[d2];
d3 = base64Data[dataIndex++];
d4 = base64Data[dataIndex++];
if (!isData((d3)) || !isData((d4))) {// Check if they are PAD characters
if (isPad(d3) && isPad(d4)) {
if ((b2 & 0xf) != 0)// last 4 bits should be zero
{
return null;
}
byte[] tmp = new byte[i * 3 + 1];
System.arraycopy(decodedData, 0, tmp, 0, i * 3);
tmp[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
return tmp;
} else if (!isPad(d3) && isPad(d4)) {
b3 = base64Alphabet[d3];
if ((b3 & 0x3) != 0)// last 2 bits should be zero
{
return null;
}
byte[] tmp = new byte[i * 3 + 2];
System.arraycopy(decodedData, 0, tmp, 0, i * 3);
tmp[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
tmp[encodedIndex] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
return tmp;
} else {
return null;
}
} else { // No PAD e.g 3cQl
b3 = base64Alphabet[d3];
b4 = base64Alphabet[d4];
decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
decodedData[encodedIndex++] = (byte) (b3 << 6 | b4);
}
return decodedData;
}
/**
* remove WhiteSpace from MIME containing encoded Base64Utils data.
*
* @param data
* the byte array of base64 data (with WS)
* @return the new length
*/
private static int removeWhiteSpace(char[] data) {
if (data == null) {
return 0;
}
// count characters that's not whitespace
int newSize = 0;
int len = data.length;
for (int i = 0; i < len; i++) {
if (!isWhiteSpace(data[i])) {
data[newSize++] = data[i];
}
}
return newSize;
}
}
整个加密解密过程也就完成了。下面说说我踩到的坑。
在上面代码注释中也提到了。加密方法encrypt()方法和解密方法decrypt()中,
// 必须使用RSA/ECB/PKCS1Padding而不是RSA,否则每次加密结果一样
cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
//Android中错误写法
cipher = Cipher.getInstance("RSA");
// 必须使用RSA/ECB/PKCS1Padding而不是RSA,否则解密会乱码
cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
//Android中错误写法
cipher = Cipher.getInstance("RSA");
此处如果不是使用 RSA/ECB/PKCS1Padding 而是 RSA ,加密结果或者解密结果
就会出现问题。
上面用 RSA 加密后结果会一致,而下面用 RSA ,解密的结果则会乱码。