Android RSA加密与解密

首先定义一个公钥和私钥

1
2
3
public static String pubKey="";

public static String priKey="";

RSA加密

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
* 加密
* @params str 要加密的字符串
*/
public static String Encrypt(String str) throws Exception {
// base64编码的公钥
byte[] decoded = Base64.decode(pubKey.getBytes(), Base64.DEFAULT);
RSAPublicKey rsaPublicKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
// RSA加密
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, rsaPublicKey);
String outStr = Base64.encodeToString(cipher.doFinal(str.getBytes()), Base64.DEFAULT);
return outStr;
}

RSA解密

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
* 解密
* @params str 要解密的字符串
*/
public static String Decrypt(String encryptData) throws Exception {
byte[] decode = Base64.decode(encryptData.getBytes("UTF-8"), Base64.DEFAULT);
// base64编码的私钥
byte[] decoded = Base64.decode(priKey, Base64.DEFAULT);
RSAPrivateKey rsaPriKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
// RSA解密
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, rsaPriKey);
String outStr = new String(cipher.doFinal(decode));
return outStr;
}

使用的时候

1
2
3
4
5
6
7
8
9
10
11
try {

String jiami=Encrypt("123456789");
Log.d(TAG, "加密: "+ jiami);
Log.d(TAG, "解密: "+ Decrypt(jiami));

}
catch (Exception exception)
{

}