在我们的一个内部软件中,我们正在实现一个新的 API 端点,外部源必须通过互联网访问该端点,然后必须以某种方式保护它的安全。
由于我们不允许使用库作为 OAuth
或公钥和私钥,因此我们选择 javax.crypto AES
来加密每个中的“自定义授权 token ”通过这种方式外部来源:
...
Key aesKey = new SecretKeySpec("API-KEY".getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, aesKey);
byte[] applicationIdEncrypted = cipher.doFinal(applicationId.getBytes());
...
token
包含一个自定义applicationId
,用于在另一端识别谁正在联系该端点。
由于我们必须执行 HTTP 调用,因此我们将 applicationIdEncrypted
转换为 base64 字符串
String base64Encoded = Base64.getEncoder().encodeToString(applicationIdEncrypted);
另一边
我们正在获取 header 并从 Base64 对其进行解码
String base64Decoded = new String(Base64.getDecoder().decode(header));
但是当尝试执行最后一个操作时
Key aesKey = new SecretKeySpec("API-KEY".getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, aesKey);
String headerDecoded = new String(cipher.doFinal(base64Decoded.getBytes())); //<- THIS
我们得到javax.crypto.BadPaddingException:给定的最终 block 未正确填充
base64Encoded
和 base64Decoded
两端的值相同。
尝试在其中一端执行相同的操作(不使用 HTTP channel )不会引发异常 - 但是 - 返回不同的 headerDecoded
new String(cipher.doFinal(base64Decoded.getBytes()));
查找字节applicationIdEncrypted
和base64Decoded.getBytes()
,它们略有不同:
applicationIdEncrypted
[-28, -103, 107, 70, -112, 121, 4, -14, -80, -114, -14, 92, -81, -13, -128, 97]
base64Decoded.getBytes()
[-28, -103, 107, 70, 63, 121, 4, -14, -80, -114, -14, 92, -81, -13, -128, 97]
我读到,从字节传递到字符串可能会丢失信息(也许?),但我无法弄清楚为什么会出现这种行为,因为 base64Encoded
和 base64Decoded
在两种情况和场景下具有相同的值。
如何仅使用 Java 1.7 javax.crypto
库实现“自定义授权 token ”的通过?
编辑
“API-KEY”
类似于02E30E6BE24BF1EA
最佳答案
正如 @James K Polk 所说,我对数千个 String
转换感到一团糟,因此我设法首先获得更清晰的代码,以获得更好的综合代码。
在客户端
Key aesKey = new SecretKeySpec("API-KEY".getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, aesKey);
byte[] applicationIdEncrypted = cipher.doFinal(applicationId.getBytes());
byte[] base64Encoded = Base64.getEncoder().encode(applicationIdEncrypted);
String out = new String(base64Encoded);
其中 out
是 String
中唯一的一个转换,它是 HTTP header 的有效负载。
另一边
byte[] in = out.getBytes();
byte[] base64Decoded = Base64.getDecoder().decode(in);
Key aesKey = new SecretKeySpec("API-KEY".getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, aesKey);
byte[] applicationIdDecrypted = cipher.doFinal(base64Decoded);
String applicationId= new String(applicationIdDecrypted);
我只有两次转换为String
:out
( header 的base64值)和applicationId
。
通过这种方式,我曾经拥有相同的 applicationId
值。
关于java - 如何使用 javax.crypto 通过 HTTP header 传递加密的 AES 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50273179/