Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/376.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JAVA使用不同的密钥对字符串加密两次并解密_Java_Encryption - Fatal编程技术网

JAVA使用不同的密钥对字符串加密两次并解密

JAVA使用不同的密钥对字符串加密两次并解密,java,encryption,Java,Encryption,我将使用AES算法加密字符串两次,使用2个不同的密钥。然后,我想用加密中使用的相同2个密钥解密加密字符串。 我使用了这个函数,它只适用于一次加密和解密,但不适用于第二次加密/解密: 公共字符串encryptDecryptAes(字符串密钥、字符串输入、int模式)抛出NoSuchPaddingException、NoSuchAlgorithmException、NoSuchProviderException、InvalidKeyException、ShortBufferException、Ba

我将使用AES算法加密字符串两次,使用2个不同的密钥。然后,我想用加密中使用的相同2个密钥解密加密字符串。 我使用了这个函数,它只适用于一次加密和解密,但不适用于第二次加密/解密:

公共字符串encryptDecryptAes(字符串密钥、字符串输入、int模式)抛出NoSuchPaddingException、NoSuchAlgorithmException、NoSuchProviderException、InvalidKeyException、ShortBufferException、BadPaddingException、IllegalBlockSizeException{
java.security.security.addProvider(新的BouncyCastleProvider());
字符串结果=null;
byte[]inputBytes=input.getBytes();
byte[]keyBytes=key.getBytes();
SecretKeySpec secretKey=新SecretKeySpec(keyBytes,“AES”);
Cipher Cipher=Cipher.getInstance(“AES/ECB/PKCS7Padding”,“BC”);
如果(模式==0){
//加密
cipher.init(cipher.ENCRYPT_模式,secretKey);
cipherText=新字节[cipher.getOutputSize(inputBytes.length)];
ctLength=cipher.update(inputBytes,0,inputBytes.length,密文,0);
ctLength+=cipher.doFinal(密文,ctLength);
结果=新字符串(密文);
}
如果(模式==1){
//解密
cipher.init(cipher.DECRYPT_模式,secretKey);
字节[]输出=新字节[cipher.getOutputSize(ctLength)];
int ptLength=cipher.update(密文,0,ctLength,输出,0);
ptLength+=cipher.doFinal(输出,ptLength);
结果=新字符串(输出);
}
返回结果;

}
执行加密的次数应该是无限的,因为您只是从纯文本开始,然后以新密码文本结束。解密时,您需要确保按相反顺序使用密钥。该过程类似于以下内容:

从一个称为明文的文本开始

加密:

  • 使用密钥1加密明文,存储在singleEncryption中
  • Encypt singleEncryption使用密钥2,存储在doubleEncryption中
解密:

  • 使用密钥2解密doubleEncryption,存储在singleEncryption中
  • 使用密钥1解密singleEncryption,以明文形式存储
本例中使用变量是为了简化解释,不要求您实际拥有多个文本副本


编辑:如果您认为用于加密的密钥是一个堆栈,那么后进即先出。

您卡在哪里了!!我需要用不同的密钥进行双重加密。。可能吗?