我有.pem文件由客户端提供并使用此文件我必须使用以下点生成client_secret密钥 -
1.服务帐户具有来自所提供的公钥 - 私钥对的公钥 由客户。
2.时间戳被格式化为表示时间的十进制字符串 1970年1月1日00:00:00 GMT之后的毫秒数。
3.然后使用服务的私钥对时间戳进行签名/加密 与客户端关联的帐户和Base 64编码。
我已根据上述要求实施了代码,但Web API服务器返回错误 -
远程服务器返回错误:(400)错误请求。 {“error”:“invalid_grant”,“error_description”:“无法进行身份验证。[clientId:”我的密钥“]。”}。
这是我生成client_secret密钥的函数 -
private string getsecretkey()
{
string privateKeyPath = @"C:\Users\vijay.birari.DGSL\Desktop\Temp\familysearchserviceaccount1.PEM";
StreamReader sr = new StreamReader(privateKeyPath);
PemReader pr = new PemReader(sr);
AsymmetricCipherKeyPair KeyPair = (AsymmetricCipherKeyPair)pr.ReadObject();
RSAParameters rsa = DotNetUtilities.ToRSAParameters((RsaPrivateCrtKeyParameters)KeyPair.Private);
//RsaKeyParameters publickey = (RsaKeyParameters)KeyPair.Public;
RsaKeyParameters privatekey = (RsaKeyParameters)KeyPair.Private;
// Timestamps code
TimeSpan ts = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc));
long millis = (long)ts.TotalMilliseconds;
string sTimestamp = Convert.ToString(millis);
byte[] Timstamp = Encoding.UTF8.GetBytes(sTimestamp);
IAsymmetricBlockCipher cipher = new OaepEncoding(new RsaEngine());
cipher.Init(true, privatekey);
byte[] bytesTimestampUtf8Encrypted = cipher.ProcessBlock(Timstamp, 0, Timstamp.Length);
string encode = Convert.ToBase64String(bytesTimestampUtf8Encrypted);
string secret = HttpUtility.UrlEncode(encode, UTF8Encoding.UTF8);
return secret;
}
在下面的代码中调用上面的函数 -
string respones = string.Empty;
try
{
StringBuilder sb = new StringBuilder("https://ident.familysearch.org/cis-web/oauth2/v3/token?");
sb.Append("grant_type=client_credentials&client_id=");
sb.Append(client_id);
sb.Append("&client_secret=");
// sb.Append("=");
sb.Append(getsecretkey());
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(sb.ToString());
request.Method = "POST";
// request.ContentType = "application/x-www-form-urlencoded";
// request.ContentType = "application/json";
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
respones = sr.ReadToEnd();
}
if (!string.IsNullOrEmpty(respones))
{
dynamic jsonResponse = JsonConvert.DeserializeObject(respones.ToString());
dynamic data = JObject.Parse(respones);
respones = data.access_token;
}
}
return webresponse;
}
}
catch (WebException wex)
{
if (wex.Response != null)
{
using (var errorResponse = (HttpWebResponse)wex.Response)
{
using (var reader = new StreamReader(errorResponse.GetResponseStream()))
{
respones = reader.ReadToEnd();
//TODO: use JSON.net to parse this string and look at the error message
}
}
}
return respones;
}
答案 0 :(得分:1)
最后我解决了我的问题 我用Pkcs1Encoding()替换了OaepEncoding()。
e.g。 - IAsymmetricBlockCipher cipher = new Pkcs1Encoding(new RsaEngine());