使用Google Apps脚本执行SHA256withRSA

时间:2014-01-29 18:35:13

标签: javascript 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()

2 个答案:

答案 0 :(得分:4)

如下所示的功能应该可以解决问题。有两点需要注意:

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

答案 1 :(得分:1)

我使用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&#34; RS256&#34;

生成令牌