我已经使用下面的库在iOS中进行加密和解密.
https://github.com/dev5tec/FBEncryptor
现在,我想要Android中的相同功能. Android也有支持吗?如果没有,那么我又该如何使用该库来满足我在Android中的需求,或者建议另一个与FBEncryptor相同的加密库.
我已经实现了以下代码.
public class AESHelper {
private final Cipher cipher;
private final SecretKeySpec key;
private AlgorithmParameterSpec spec;
private static final String KEY = "VHJFTFRGJHGHJDhkhjhd/dhfdh=";
public AESHelper() throws Exception {
byte[] keyBytes = KEY.getBytes("UTF-8");
Arrays.fill(keyBytes, (byte) 0x00);
cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
key = new SecretKeySpec(keyBytes, "AES");
spec = getIV();
}
public AlgorithmParameterSpec getIV() {
final byte[] iv = new byte[16];
Arrays.fill(iv, (byte) 0x00);
return new IvParameterSpec(iv);
}
public String encrypt(String plainText) throws Exception {
cipher.init(Cipher.ENCRYPT_MODE, key, spec);
byte[] encrypted = cipher.doFinal(plainText.getBytes("UTF-8"));
String encryptedText = new String(Base64.encode(encrypted, Base64.DEFAULT), "UTF-8");
return encryptedText;
}
public String decrypt(String cryptedText) throws Exception {
cipher.init(Cipher.DECRYPT_MODE, key, spec);
byte[] bytes = Base64.decode(cryptedText, Base64.DEFAULT);
byte[] decrypted = cipher.doFinal(bytes);
String decryptedText = new String(decrypted, "UTF-8");
return decryptedText;
}
}
但是它抛出javax.crypto.BadPaddingException:填充块损坏
解决方法:
终于,我为自己的问题找到了解决方案.
对于android中的加密,您可以使用https://gist.github.com/m1entus/f70d4d1465b90d9ee024.
此类的工作方式与ios中的https://github.com/dev5tec/FBEncryptor相同.