之前在做一个项目时,要求安全性,于是就用到了RSA和AES加密。
我的部分就是完成安卓端的编写,别人在C#端把服务器写好了,不是很会RSA加密于是就在Java项目下完成RSA加密算法的编写,之后又实现了AES加解密。
但是发现一个小问题,那就是我知道了密钥,可是Java端能够完美加解密,可是安卓就是不可以,后来发现C#和Java都有默认填充模式和加密模式,不用指定,可是安卓就需要指定才能得到正确的密文和明文。
现在贴一些安卓的代码:
1.RAS已知xml密钥,加解密,需要关注的是 Cipher.getInstance("RSA/NONE/PKCS1Padding");这一句
// 公钥加密
public static byte[] Encrypt(byte[] content) throws Exception {
// 创建RSA加密方式
Cipher cipher = Cipher.getInstance("RSA/NONE/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] bytes = {};
// 分块儿加密并且组装
for (int i = 0; i < content.length; i += 117) {
int bolckSize = content.length - i;
bolckSize = bolckSize >= 117 ? 117 : bolckSize;
byte[] byteClip = new byte[bolckSize];
System.arraycopy(content, i, byteClip, 0, bolckSize);
bytes = unitByteArray(bytes, cipher.doFinal(byteClip));
}
return bytes;
}
// 公钥加密
public static byte[] Encrypt(JSONObject jsonObject) throws Exception {
byte[] jsonBytes = jsonObject.toString().getBytes("UTF-8");
return Encrypt(jsonBytes);
}
// 获取公钥对象
private static RSAPublicKey getRSAPublicKey(String Modulus, String Exponent) {
RSAPublicKey publicKey = null;
try {
byte[] m =Base64.decode(Modulus.getBytes(),Base64.NO_WRAP);
byte[] e = Base64.decode(Exponent.getBytes(),Base64.NO_WRAP);
BigInteger b1 = new BigInteger(1, m);
BigInteger b2 = new BigInteger(1, e);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(b1, b2);
// 初始化publicKey
publicKey = (RSAPublicKey) keyFactory.generatePublic(keySpec);
} catch (Exception e) {
System.out.println("获取公钥对象失败!");
}
return publicKey;
}
2.AES加解密
public static byte[] Encrypt(byte[] data, byte[] key, byte[] IV) {
byte[] encrypted = {};
try {
SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(IV));
encrypted = cipher.doFinal(data);
} catch (Exception e) {
}
return encrypted;
}
//AES解密
public static byte[] Decrypt(byte[] data, byte[] Key, byte[] IV) {
byte[] result = {};
try {
SecretKeySpec skeySpec = new SecretKeySpec(Key, "AES");
// 创建密码器
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
// 初始化解密器
cipher.init(Cipher.DECRYPT_MODE, skeySpec, new IvParameterSpec(IV));
// 解密
result = cipher.doFinal(data);
} catch (Exception e) {
}
return result;
}