Android RSA对字符串进行加密解密
RSA的应用
RSA是一种非对称加密算法。现在,很多登陆表单的密码的都采用RSA加密,例如京东中的登陆使用公钥对密码进行加密。
RSA加密与解密
使用RSA一般需要产生公钥和私钥,当采用公钥加密时,使用私钥解密;采用私钥加密时,使用公钥解密。以下为Java程序:
/** 使用公钥加密 */
public static byte[] encryptByPublicKey(byte[] data, byte[] publicKey) throws Exception {
// 得到公钥对象
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey pubKey = keyFactory.generatePublic(keySpec);
// 加密数据
cp = Cipher.getInstance(TRANSFORMATION);
cp.init(Cipher.ENCRYPT_MODE, pubKey);
return cp.doFinal(data);
}
这里是通过私钥进行一个解密
/** 使用私钥解密 */
public static byte[] decryptByPrivateKey(byte[] encrypted, byte[] privateKey) throws Exception {
// 得到私钥对象
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKey);
KeyFactory kf = KeyFactory.getInstance(RSA);
PrivateKey keyPrivate = kf.generatePrivate(keySpec);
// 解密数据
Cipher cp = Cipher.getInstance(TRANSFORMATION);
cp.init(Cipher.DECRYPT_MODE, keyPrivate);
arr = cp.doFinal(encrypted);
return arr;
}
public static KeyPair generateRSAKeyPair(int keyLength) throws NoSuchAlgorithmException {
KeyPairGenerator kpg = KeyPairGenerator.getInstance(RSA);
kpg.initialize(keyLength);
return kpg.genKeyPair();
}
这里是为了获取到公钥
/** 获取公钥*/
public static byte[] getPublicKey(KeyPair keyPair) {
RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
return rsaPublicKey.getEncoded();
}
获取私钥跟或许公钥是一样的 这里就不多做解释
/** 获取私钥 */
public static byte[] getPrivateKey(KeyPair keyPair) {
RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
return rsaPrivateKey.getEncoded();
}
然后调用咱们的工具类对字符串进行加密和解密
int keyLength = 2048;
//生成密钥对
KeyPair keyPair = null;
try {
keyPair = RSAUtils.generateRSAKeyPair(keyLength);
//获取公钥
byte[] publicKey = RSAUtils.getPublicKey(keyPair);
//获取私钥
byte[] privateKey = RSAUtils.getPrivateKey(keyPair);
Gson gson = new Gson();
String json = gson.toJson(data);
byte[] bytes = json.getBytes();
//用公钥加密
byte[] encrypt = RSAUtils.encryptByPublicKey(bytes, publicKey);
//用私钥解密
byte[] decrypt = RSAUtils.decryptByPrivateKey(encrypt, privateKey);
Log.d("TAG", "加密后的数据:" + encrypt.toString());
Log.d("TAG", "解密后的数据:" + new String(decrypt, "utf-8"));
Log.d("TAG","字符串的长度是"+bytes.length);
rsa_show.setText(encrypt.toString());
} catch (Exception e) {
e.printStackTrace();
}
特别注意这行代码int keyLength = 1024;
如果你的字符串比较长的话他就就可能解不出来。
所以你可将咱们的值设置的大一点比如int keyLength = 2048; 总之要看你的需求。