Java AES 128 ECB到AES 256 ECB的转换



我在ECB模式中将AES 128位加密升级为AES 256时遇到问题。但我找不到任何解决方案。大多数解决方案都适用于AES 256 CBC模式。非常感谢您的帮助。

我得到的例外是由于填充不好

PS:我知道AES中ECB模式的漏洞,但这正是我目前需要实现的。

import org.apache.tomcat.util.codec.binary.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.GeneralSecurityException;
public class Decrypt {
public static String decryptPayload(String payload) throws Exception {
byte[] keyBytes = {
0x74, 0x68, 0x69, 0x73, 0x49, 0x73, 0x43, 0x53, 0x75, 0x63, 0x72, 0x65, 0x44, 0x4b, 0x55, 0x79
};
try {
payload = payload.replace(' ', '+');
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
final SecretKeySpec secretKey = new SecretKeySpec(keyBytes, "AES");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
return new String(cipher.doFinal(
Base64.decodeBase64(payload)));
} catch (GeneralSecurityException e) {
e.printStackTrace();
}
return null;
}
}

我尝试的AES 256 ECB的实现如下:

public static String decrypt(String strToDecrypt, String secretKey) {
try
{
IvParameterSpec ivspec = new IvParameterSpec(iv);
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
KeySpec spec = new PBEKeySpec(secretKey.toCharArray(), salt.getBytes(), 65536, 256);
SecretKey tmp = factory.generateSecret(spec);
SecretKeySpec secretKey = new SecretKeySpec(tmp.getEncoded(), "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, secretKey, ivspec);
return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));
}
catch (Exception e) {
System.out.println("Error while decrypting: " + e.toString());
}
return null;
}

感谢@MichaelFehr ,整个解决方案对我有效

public void tester() {
System.out.println("Program starts");
String key = "5u7x!A%D*G-KaPdSgVkYp3s6v9y/B?E(";
String payload = "Test string to test AES 256 ECB";
String encrypted = "";
String decrypted = "";
// Encryption
try{
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
final SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
final String encryptedString = Base64.encodeBase64String(cipher.doFinal(payload.getBytes()));
System.out.println("The encrypted string isn"+encryptedString);
encrypted = encryptedString;
}
catch(Exception e){
e.printStackTrace();
}

// Decryption
try
{
decrypted = encrypted.replace(' ', '+');
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
final SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
final String decryptedString = new String(cipher.doFinal(Base64.decodeBase64(encrypted)));
System.out.println("The decrypted string isn"+decryptedString);
decrypted=decryptedString;
}
catch (Exception e)
{
e.printStackTrace();
}
}

相关内容

  • 没有找到相关文章

最新更新