我正在使用下面的类在android中生成AES 256密钥,初始化向量,加密和解密。我面临的几个问题
1)当我调用getInitializationVector()时,它返回24个字符而不是16个字符。(例如:WoiUFsQpizjG705OXja1Jw ==]2)当我调用generateKey()时,它返回44个字符而不是32个字符。(例如:tEf + dcrzI4x + kSMS8UZxjwziGySMMkDxO0aVgsj0oBs =)3)下面的类是对称方法,如何使其不对称。
您可以看到textKey和testIV为默认值。但是我无法创建它。我已经在堆栈溢出中搜索了解决方案,但是,所有人都给我发了相同长度的文本。有谁知道如何做到这一点?我做错了吗?感谢您宝贵的时间。
public class CryptoDataHandler {
//32 characters
String testKey = "82a645babc5cd41c9a2cb4d0d3ba17ad";
//16 characters
String testIV = "acf30ad32b693849";
String edType = "AES";
String chiperInstanceType = "AES/CBC/PKCS5PADDING";
private static CryptoDataHandler instance = null;
public static CryptoDataHandler getInstance() {
if (instance == null) {
Security.setProperty("crypto.policy", "unlimited");
instance = new CryptoDataHandler();
}
return instance;
}
public String encrypt(String message) throws NoSuchAlgorithmException,
NoSuchPaddingException, IllegalBlockSizeException,
BadPaddingException, InvalidKeyException,
UnsupportedEncodingException, InvalidAlgorithmParameterException {
byte[] srcBuff = message.getBytes(StandardCharsets.UTF_8);
//here using substring because AES takes only 16 or 24 or 32 byte of key
SecretKeySpec skeySpec = new
SecretKeySpec(testKey.substring(0, 32).getBytes(), edType);
IvParameterSpec ivSpec = new
IvParameterSpec(testIV.substring(0, 16).getBytes());
Cipher ecipher = Cipher.getInstance(chiperInstanceType);
ecipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivSpec);
byte[] dstBuff = ecipher.doFinal(srcBuff);
return Base64.encodeToString(dstBuff, Base64.DEFAULT);
}
public String decrypt(String encrypted) throws NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException,
InvalidAlgorithmParameterException, IllegalBlockSizeException,
BadPaddingException, UnsupportedEncodingException {
SecretKeySpec skeySpec = new
SecretKeySpec(testKey.substring(0, 32).getBytes(), edType);
IvParameterSpec ivSpec = new
IvParameterSpec(testIV.substring(0, 16).getBytes());
Cipher ecipher = Cipher.getInstance(chiperInstanceType);
ecipher.init(Cipher.DECRYPT_MODE, skeySpec, ivSpec);
byte[] raw = Base64.decode(encrypted, Base64.DEFAULT);
byte[] originalBytes = ecipher.doFinal(raw);
return new String(originalBytes, StandardCharsets.UTF_8);
}
public String generateKey() {
try {
Key key;
SecureRandom rand = new SecureRandom();
KeyGenerator generator = KeyGenerator.getInstance(edType);
generator.init(256, rand);
key = generator.generateKey();
return Base64.encodeToString(key.getEncoded(), Base64.DEFAULT);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return null;
}
public String getInitializationVector() {
byte[] IV = new byte[16];
SecureRandom random = new SecureRandom();
random.nextBytes(IV);
return Base64.encodeToString(IV, Base64.DEFAULT);
}
}
我正在使用下面的类在android中生成AES 256密钥,初始化向量,加密和解密。我面临的问题很少:1)当我调用getInitializationVector()时...
嗯,我找到了解决方案。在这里发布。如果这对其他人有帮助。