[英]Node CryptoJS vs Jsrsasign SHA256withRSA with encrypted pem
[英]Doing a SHA256withRSA with Google Apps Script
我正在尝试通过构造描述的JWS / JWT东西在Google Apps脚本中执行Google oAuth2方法。
现在,我可以从云端硬盘或其他来源读取密钥文件,但是如何用该文件签名? 有什么方法或JavaSCript片段可以做到这一点吗?
function Auth20(user) {
var header = Utilities.base64Encode(JSON.stringify( {"alg":"RS256","typ":"JWT"} ) );
var claimdata = {
"iss":"1002979611916q0iraclc6q33xxxxxxxx@developer.gserviceaccount.com",
"prn": user,
"scope":"https://www.googleapis.com/auth/plus.circles.read",
"aud":"https://accounts.google.com/o/oauth2/token",
"exp":new Date().getTime()/1000,
"iat":(new Date().getTime()/1000)+3600
}
var claim = Utilities.base64Encode(JSON.stringify( claimdata ))
var jws = header+"."+claim;
var jwsbytes = [];
for (var i = 0; i < jws.length; ++i)
{
jwsbytes.push(jws.charCodeAt(i));
}
var key = DriveApp.getFileById("0B_5HSTQXtXmsU29fTE5xNWhvOVE").getBlob()
下面的函数应该可以解决问题。 需要注意的两件事:
1)私钥必须采用私钥格式,而不是RSA私钥。 如果密钥是后者,则需要openssl,这将允许您对存储在private.pem
文件中的密钥运行以下命令。 注意在GAS中使用的带有显式\\n
的字符串格式:
openssl pkcs8 -topk8 -inform pem -in private.pem -outform pem -nocrypt -out newPrivate.pem
2) Utilities.base64EncodeWebSafe()
可能以=
符号的形式返回终端填充。 这些需要删除,因此我包含了.replace(/=+$/, '')
放在一起:
function Auth20(user) {
var privateKey = "-----BEGIN PRIVATE KEY-----\n{privatekeyhere}\n-----END PRIVATE KEY-----\n"
var header = {
alg: 'RS256',
typ: 'JWT'
};
var now = new Date();
var claimSet = {
iss: {your_iss},
prn: user,
scope: "https://www.googleapis.com/auth/plus.circles.read",
aud:"https://accounts.google.com/o/oauth2/token",
exp: (now.getTime() / 1000) + 3000,
iat: now.getTime() / 1000
};
var toSign = Utilities.base64EncodeWebSafe(JSON.stringify(header)) + '.' + Utilities.base64EncodeWebSafe(JSON.stringify(claimSet));
toSign = toSign.replace(/=+$/, '');
var signatureBytes = Utilities.computeRsaSha256Signature(toSign, privateKey);
var signature = Utilities.base64EncodeWebSafe(signatureBytes);
signature = signature.replace(/=+$/, '');
return toSign + '.' + signature;
};
我使用kjur https://kjur.github.io/jsrsasign/
load('auth/jsrsasign-latest-all-min.js');
var sHead=JSON.stringify({"alg":"RS256","typ":"JWT"});
var iat=timeStampf();
var exp=iat+3600;
var sPayload=JSON.stringify({
"iss":client_email,
"scope":scope,
"aud":"https://www.googleapis.com/oauth2/v3/token",
"exp":exp,
"iat":iat
});
var sJWS = KJUR.jws.JWS.sign("RS256", sHead,sPayload, private_key);
sJWS变量是head(base64).playload(base64).token(base64)令牌是使用sha256withrsa“ RS256”生成的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.