[英]Java AES 128 ECB to AES 256 ECB conversion
我在 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 is\n"+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 is\n"+decryptedString);
decrypted=decryptedString;
}
catch (Exception e)
{
e.printStackTrace();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.