我将使用2个不同的密钥使用AES算法对字符串进行两次加密。在那之后,我想使用相同的2个密钥解密加密的字符串。我使用了此功能,它只能用于一种加密和解密,而不能用于第二种加密/解密:
public String encryptDecryptAes(String key , String input , int mode) throws NoSuchPaddingException, NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, ShortBufferException, BadPaddingException, IllegalBlockSizeException {
java.security.Security.addProvider(new BouncyCastleProvider());
String result = null;
byte[] inputBytes = input.getBytes();
byte[] keyBytes = key.getBytes() ;
SecretKeySpec secretKey = new SecretKeySpec(keyBytes , "AES") ;
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding", "BC");
if(mode==0) {
//Encrypt
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
cipherText = new byte[cipher.getOutputSize(inputBytes.length)];
ctLength = cipher.update(inputBytes, 0, inputBytes.length, cipherText, 0);
ctLength += cipher.doFinal(cipherText, ctLength);
result = new String(cipherText);
}
if(mode==1) {
//DECRYPT
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] output = new byte[cipher.getOutputSize(ctLength)];
int ptLength = cipher.update(cipherText, 0, ctLength, output, 0);
ptLength += cipher.doFinal(output, ptLength);
result = new String(output);
}
return result ;
}
加密的次数应该是无限的,因为您只是从纯文本开始,然后以新的密文结束。解密时,您需要确保以相反的顺序使用密钥。该过程将类似于以下内容:
以称为plainText的文本开头。
加密:
解密:
在此示例中,使用变量是为了简化说明,实际上并不需要多个文本副本。
编辑:如果您认为用于加密的密钥是一个堆栈,那么后进先出。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句