Android RSA 加密
项目中遇到需要向后台传递的密码(纯数字)进行RSA加密,在踩了无数坑之后,终于实现了~~~~~~~~~
相信来看本文的同学,都是在项目中遇到了此需求,那么我就将我整理的跟大家分享一下。
首先,什么事RSA?这个的解释我就不说了,随便百度一下,N多解释内容,
其次,RSA的公钥和私钥,网上有很多生成方式(仅限于自己玩哈,真正上生产了可不能泄露了私钥~),在这我也不说了,我们项目中使用的公钥和私钥是后台同学用OpenSSL生成的,然后我要关心的就是公钥~~~
第一步是将你的明文密码进行RSA加密
此处需要注意的东西都在备注里边写了
public static byte[] encryptByPublicKey(String password,InputStream inputStream) {
//获取明文密码的字节数组
byte[] keyBytes = password.getBytes();
try {
//获取RSAPublicKey
RSAPublicKey publicKey = loadPublicKeyFromFile(new BufferedInputStream(inputStream));
//获取Cipher
//new BouncyCastleProvider() 要添加,不然每次生成的加密后的密文,是不同的~~~~
Cipher cipher = Cipher.getInstance(RSA);
//用公钥加密
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] encryptedData = cipher.doFinal(keyBytes);
return encryptedData;
} catch ( NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
e.printStackTrace();
return null;
}
}
public static String encryptPwdByPublicKey(String password,InputStream inputStream) {
try {
String encodePwd = encode(encryptByPublicKey(password,inputStream));
return encodePwd;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
两个参数:password是你的明文密码;inputStream是公钥文件读取之后的流
一般我们把公钥文件放在assets或者是raw里边~
InputStream inputStream = getResources().openRawResource(R.raw.rsa_public_key);
开始我用IDEA写的Java程序测试,输出了加密后的密文,给后台,解密成功(一定注意:直接RSA加密之后是乱码的,一定要base64处理一下);
但是当我将代码迁移到了AS里边的时候,发现行不通了,因为引入了两个jar包,之后就在编译的时候一直报
app:transformClassesWithMultidexlistForDahuoDebug
这个错,Google了N多资料也找出个所以然来。。。后来果断把jar删了,然后重新写了base64的工具类,就成功了~~~~
具体的代码以及使用方法,请参考:
http://download.csdn.net/detail/ivenes/9878835