Java 使用SHA 256进行散列,使用AES进行加密
为了使用Web服务,我需要为名为Java 使用SHA 256进行散列,使用AES进行加密,java,encryption,hash,aes,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 - PKCS5Pad
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加密
加密后,我将在rest服务调用中使用上面生成的加密值作为头
到目前为止,我已经做到了:
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));
但是后端服务仍然说我的授权密钥无效。如果我遗漏了什么,请告诉我。您需要更改此项:
String hashString = "=" + Base64.encodeBase64String(hashed);
System.out.println(hashString);
致:
由于哈希密钥在生成授权密钥之前已进行Base64编码。您需要更改此设置:
String hashString = "=" + Base64.encodeBase64String(hashed);
System.out.println(hashString);
致:
由于哈希密钥在生成授权密钥之前已进行Base64编码。AES密钥的长度为16、24或32字节,因此您的AES密钥原则上无效。您的提供程序可能会以另一种超出您预期的方式解释此类无效密钥。实际上,我在这里模拟了密钥。当我尝试将原始密钥字符串转换为字节并获得长度时,它是16。所以我认为这不是问题所在。我将在问题中对此进行编辑。它看起来不一致(哈希函数只有一个输入,分组密码只有两个输入)和不完整(1.SHA-2?长度不同。2.编码是如何完成的?)web服务文档。只要向他们询问示例代码或更好的文档即可。AES密钥的长度为16、24或32字节,因此您的AES密钥原则上无效。您的提供程序可能会以另一种超出您预期的方式解释此类无效密钥。实际上,我在这里模拟了密钥。当我尝试将原始密钥字符串转换为字节并获得长度时,它是16。所以我认为这不是问题所在。我将在问题中对此进行编辑。它看起来不一致(哈希函数只有一个输入,分组密码只有两个输入)和不完整(1.SHA-2?长度不同。2.编码是如何完成的?)web服务文档。只需向他们询问示例代码或更好的文档。
hashed
是包含二进制数据的byte[]
。永远不要尝试使用非字符串数据调用新字符串(字节[])
!!!你能试试这个吗:ByteArrayOutputStream outputStream=newbytearrayoutputstream();write((salt+orgId+“=”).getByte();outputStream.write(散列);字节forAuth[]=outputStream.toByteArray()<代码>哈希是包含二进制数据的字节[]
。永远不要尝试使用非字符串数据调用新字符串(字节[])
!!!你能试试这个吗:ByteArrayOutputStream outputStream=newbytearrayoutputstream();write((salt+orgId+“=”).getByte();outputStream.write(散列);字节forAuth[]=outputStream.toByteArray();