使用SHA 256进行哈希处理并使用AES加密

时间:2016-10-05 10:12:56

标签: java encryption hash aes

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

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));

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

1 个答案:

答案 0 :(得分:-1)

你需要改变这个:

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

要:

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

由于散列密钥在授权密钥生成之前获得base64encoded。