java - 加密后编码,如何在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);
...
...
}
希望能得到您关于如何在这一点上继续的想法或帮助。
解决方案
推荐阅读
- android - 使用 AWS Lambda 连接 Android 和 AWS SageMaker
- node.js - 在 nodeJs 退出代码 1 中生成 mongodump 集群
- php - 联系表格提交失败?
- javascript - Javascript 以编程方式更改列表项的图像 url 属性
- wordpress - 需要在 WordPress 代码中删除 Foreach 循环中的重复帖子
- batch-file - 将变量名存储在批处理文件的变量中
- javascript - Angular 2+:路由器更改路由/路由器插座无法识别并显示旧组件
- javascript - 无法在 Next.js 中禁用自动前缀
- math - 如何将 Math.max 或 Math.min 转换为伪代码?
- python - Python Dash - 时间滑块上的格式标记