我对加密和解密的东西很新。我发现很难找到一个好的材料或教程。我在StackOverflow中查看了与之相关的问题,没有找到我的好答案。
如果我想通过转换加密和解密,这是我的问题:
“AES / GCM / NoPadding”
我可以在下面做点什么:
public DaoEncryptionResult<byte[]> getEncryptionResult(final ByteBuffer bufferToEncrypt) {
try {
final Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
final SecretKey secretKey = new SecretKeySpec(BinaryKey, "AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey, mSecureRandom);
final byte[] bytesToEncrypt = bufferToEncrypt.array();
final byte[] cipherText = cipher.doFinal(bytesToEncrypt,
bufferToEncrypt.arrayOffset(), bufferToEncrypt.limit());
final byte[] iv = cipher.getIV();
return new DaoEncryptionResult<>(cipherText, iv);
} catch (final GeneralSecurityException securityException) {
throw new RuntimeException("Could not encrypt data", securityException);
}
}
public byte[] getDecryptionResult(final byte[] encodedData, final byte[] encodedIv) {
try {
final Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
final SecretKey secretKey = new SecretKeySpec(BinaryKey, "AES");
cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(encodedIv));
return cipher.doFinal(encodedData);
} catch (final GeneralSecurityException securityException) {
throw new RuntimeException("Could not decrypt data", securityException);
}
}
mSecureRandom在整个应用程序生命周期中通过调用
进行一次初始化新的SecureRandom()
BinaryKey是一个byte [],由Base64从带有Base64.DEFAULT的String解码
encodedData和encodedIv将与getEncryptionResult方法中返回的结果相同。
通过这样做,我总能找到与解密问题相关的一些例外。例如:
javax.crypto.BadPaddingException: mac check in GCM failed
at com.android.org.bouncycastle.jcajce.provider.symmetric.util.BaseBlockCipher.engineDoFinal(BaseBlockCipher.java:854)
at javax.crypto.Cipher.doFinal(Cipher.java:1340)
at com.amazon.rabbit.android.data.dao.DaoEncryptionManagerImpl.getDecryptionResult(DaoEncryptionManagerImpl.java:250)
答案 0 :(得分:0)
由于篇幅和格式化而作为答案提供,回答评论:(关于此加密和解密内容的好材料,您能否共享链接)
有书:
该书的免费PDF:Handbook of Applied Cryptography,Alfred J. Menezes,Paul C. van Oorschot和Scott A. Vanstone,请参阅免费下载。章是当前密码的合理开端。
H. X. Mel和Doris M. Baker的Cryptography Decrypted(我非常喜欢的好首发)
Bruce Schneier的 Niels Ferguson,Bruce Schneier和Tadayoshi Kohno的