首页 > 解决方案 > 加密后编码,如何在Java小程序中用AES正确解密和解码

问题描述

我有一种将字节数组转换为单个String的方法。它也按预期工作。如下所示:

主.java

private static String HexToStr(byte[] allBytes) throws InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
    StringBuilder sb = new StringBuilder();
    for (byte b : AllBytes) {
        sb.append(String.format("%02x", (int) b & 0xFF));
    }
    return sb.toString();
}

但是现在我正在尝试编写另一种方法来执行相反的操作(strToHex)并使用与上述方法相同的方法规范解码原始加密和编码文本,这意味着:

private static String strToHex(byte[] allBytes) throws InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
    StringBuilder sb = new StringBuilder();
    
   // start here 
   ...
    for (byte b : bytes) {
        ... // here is where i'm missing something

    }
    return sb.toString();
}

后来,我用一个小的“主要”方法测试了所有内容,如下所示:

public static void main(String[] args) {
    
    String str = "Alpha Beta Gamma"; // text to encode and decode
    Secret myKey = KeyGenerator.getInstance("AES").generateKey();
    Cipher myCipher = Cipher.getInstance("AES");
    // encrypt then encode
    myCipher.init(Cipher.ENCRYPT_MODE, myKey);
    byte[] encryptResBytes = myCipher.doFinal(str.getBytes());
    String encryptResBytesEncoded = HexToStr(encryptResBytes);
    System.out.println("decrypt or decode should be first ?: " + encryptResBytesEncoded);
    
    // Decode then decrypt or decrypt then decode ? 
    // I,m not sure here anymore, so be free to say how you think i could go ahead :)
    ...
    myCipher.init(Cipher.DECRYPT_MODE, myKey);
    byte[] decryptResBytes = myCipher.doFinal(encryptResBytesEncoded.getBytes());
    String decryptResBytesDecoded = StrToHex(decryptResBytes);
    System.out.println("Encrypt and encoded custom text: " + encryptResBytesEncoded);
    ...
    ...
    

}

希望能得到您关于如何在这一点上继续的想法或帮助。

标签: javaencodingaes

解决方案


推荐阅读