【问题标题】:Hashing using SHA 256 and encrypting using AES使用 SHA 256 散列并使用 AES 加密
【发布时间】:2017-02-13 17:40:35
【问题描述】:

为了让我使用 Web 服务,我需要为名为 Authorization 的标头生成一个值。生成header的步骤如下:

1. Hash Generation

   HashValue = SHA2(username, password, id)

2. Auth Key Generation

   Authkey = AES(Salt + anotherId + "=" + HashValue)

这些是算法细节:

Algorithm - AES
Mode - ECB
Padding - PKCS5Padding
Secret key - someString

现在我将使用上述详细信息和作为​​字符串的密钥执行 AES 加密。

加密后,我将在我的休息服务调用中使用上面生成的加密值作为header

到目前为止我已经这样做了:

String username = "username";
String password = "password";
String id = "123456"; 

String toBeHashed = username + password + id;
MessageDigest sha256 = MessageDigest.getInstance("SHA-256");
byte[] hashed = sha256.digest(toBeHashed.getBytes("UTF-8"));

String hashString = "=" + Base64.encodeBase64String(hashed);
System.out.println(hashString);

String salt = "salt";
String anotherId = "123";
byte[] forAuth = (salt + orgId + hashString).getBytes("UTF-8");

//Mocked "secret key". Original key string is of size 16 bytes.
byte[] secKey = "secret key".getBytes("UTF-8");

SecretKey secretKey = new SecretKeySpec(secKey, 0, secKey.length, "AES");

Cipher aesCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
aesCipher.init(Cipher.ENCRYPT_MODE, secretKey);

byte[] authorizationKey = aesCipher.doFinal(forAuth);

System.out.println("-------------------");
System.out.println("-------------------");
System.out.println(Base64.encodeBase64String(authorizationKey));

但后端服务仍然说我的授权密钥无效。如果我遗漏了什么,请告诉我。

【问题讨论】:

  • AES 密钥的长度为 16、24 或 32 字节,因此您的 AES 密钥原则上是无效的。您的提供者可能会以与您预期不同的方式解释此类无效密钥。
  • 其实我这里已经模拟过秘钥了。当我尝试将原始密钥字符串转换为字节并获取长度时,它是 16。所以我认为这不是问题。我将在问题中对此进行编辑。
  • 看起来不一致(一个哈希函数只有一个输入,一个分组密码正好有两个输入)和不完整(1.SHA-2?有不同的长度。2.编码是如何完成的?) Web 服务文档。只需向他们询问示例代码或更好的文档即可。

标签: java encryption hash aes


【解决方案1】:

你需要改变这个:

String hashString = "=" + Base64.encodeBase64String(hashed);
System.out.println(hashString);

收件人:

String hashString = "=" + new String(hashed);
System.out.println(hashString);

因为散列密钥在授权密钥生成之前进行 base64 编码。

【讨论】:

  • hashed 是一个包含二进制数据的byte[]。永远不要尝试使用非字符串数据调用new String(byte[])!!!
  • 你可以试试这个:ByteArrayOutputStream outputStream = new ByteArrayOutputStream( ); outputStream.write( (salt + orgId +"=").getByte()); outputStream.write(散列); byte forAuth[] = outputStream.toByteArray();
猜你喜欢
  • 1970-01-01
  • 2011-05-18
  • 2011-06-28
  • 2019-02-24
  • 2013-08-24
  • 1970-01-01
  • 1970-01-01
  • 2017-03-02
  • 1970-01-01
相关资源
最近更新 更多