我目前正在开发一个使用Google的目录API的程序来重置我域中某人的密码。我已经完成了所有工作,但我想向Google发送加密密码而不是明文。 由于API似乎仅限于我可用于加密的内容,因此我尝试使用SHA-1进行加密。问题是,当我在SHA-1中对其进行加密时,Google并不接受它。
以下是我发送给Google的原始代码:
//create a template of the user to update
var body = new Google.Apis.Admin.Directory.directory_v1.Data.User();
//Encrypt the password using SHA1
byte[] bytes = System.Text.Encoding.Unicode.GetBytes(model.NewPassword);
SHA1 sha = new SHA1CryptoServiceProvider();
byte[] password = sha.ComputeHash(bytes);
//Put the password and hash function into the request body
body.HashFunction = "SHA-1";
body.Password = password.ToString();
//send the request
var request = users.Update(body, email);
request.execute();
当我运行它时,它会抛出一个错误,说密码无效。
当我更改它以便它发送严格的十六进制时,就像这样
//create a template of the user to update
var body = new Google.Apis.Admin.Directory.directory_v1.Data.User();
//Encrypt the password using SHA1
byte[] bytes = System.Text.Encoding.Unicode.GetBytes(model.NewPassword);
SHA1 sha = new SHA1CryptoServiceProvider();
byte[] password = sha.ComputeHash(bytes);
//Convert the hashcode to Hex
System.Text.StringBuilder builder = new System.Text.StringBuilder();
for (int i = 0; i < password.Length; i++)
{
builder.Append(password[i].ToString("x2"));
}
//Put the password and hash function into the request
body.HashFunction = "SHA-1";
body.Password = builder.ToString();
//send the request
var request = users.Update(body, email);
request.execute();
然后Google接受了我提供的内容,但进入帐户后,我无法访问该帐户,因为密码已更改为完全不同的内容。
我只是错误地加密密码,还是我缺少某些东西?
答案 0 :(得分:1)
(免责声明:我在谷歌工作,但我之前没有看过这个API。)
嗯,调用password.ToString()
时的问题是它没有提供十六进制表示 - 这就是第一段代码失败的原因。它看起来基本上是期望它是十六进制。 documentation州:
我们建议将密码属性值作为基本16位编码哈希值发送。如果指定了hashFunction,则密码必须是有效的散列键。
现在,我怀疑第二段代码的问题是您将原始文本密码转换为字节的方式。你正在使用:
Encoding.Unicode.GetBytes(model.NewPassword)
那是使用小端UTF-16。虽然文档没有陈述预期的编码,但使用UTF-8会更常见。所以我建议使用
Encoding.UTF8.GetBytes(model.NewPassword)
而不是......然后像以前一样对结果进行散列和十六进制编码。
这只是一个有根据的猜测,但值得一试。