切换到不同的密码库

时间:2019-03-02 21:08:01

标签: javascript cryptography

有一小段代码将CryptoJS用作项目中的npm依赖项,但我的安全团队要求我将库切换为msrcrypto之类的东西。

  // let secret = CryptoJS.enc.Base64.parse("storageaccountaccesskeyfromAzureViaEnvironmentVariable");
  // let hash = CryptoJS.HmacSHA256(strToSign, secret);
  // let hashInBase64 = CryptoJS.enc.Base64.stringify(hash);

目标是按照以下说明构建Authentication标头:https://docs.microsoft.com/en-us/rest/api/storageservices/authorize-with-shared-key。到目前为止,CryptoJS方法对我来说一直有效。

有人可以帮忙吗?我尝试使用在HTML中看到的示例,但是我不理解HMAC示例中的许多单词。我通过在线教程获得了有关Microsoft身份验证标头的信息,但我个人对此并不了解。

我尝试捕获这3个步骤的一些示例输出,并查看是否可以使用NodeJS的Buffer.from生成相同的输出,以便进出base64,但是我尚未看到与我相同的输出从CryptoJS看到。

2 个答案:

答案 0 :(得分:1)

这是一个计算HMACSHA256(secret: [1, 2, 3, 4, 5, 6], message: [7, 8, 9, 10])的示例。两个库产生相同的结果:

const secret = [1, 2, 3, 4, 5, 6];
const data = [7, 8, 9, 10];

// msrcrypto
const algorithm = {
    name: 'HMAC',
    hash: {
        name: 'SHA-256'
    }
};
const jwkKey = {
    kty: "oct",
    alg: "HS256",
    k: msrCrypto.toBase64(secret),
    ext: true
};
// I don't know why, but with async mode I am getting an error in my browser
// with no meaningful message
msrCrypto.subtle.forceSync = 1;
msrCrypto.subtle.importKey("jwk", jwkKey, algorithm, true, ['sign', 'verify']).then(key => {
    msrCrypto.subtle.sign(algorithm, key, data).then(hmac => {
        const arr = new Uint8Array(hmac);
        console.log('msrCrypto: ' + msrCrypto.toBase64(arr));
    });
});

// cryptojs
const cryptoJsSecret = new CryptoJS.lib.WordArray.init(new Uint8Array(secret));
const cryptoJsData = new CryptoJS.lib.WordArray.init(new Uint8Array(data));
const hash = CryptoJS.HmacSHA256(cryptoJsData, cryptoJsSecret);
console.log('CryptoJS: ' + CryptoJS.enc.Base64.stringify(hash));
<script src="https://cdn.jsdelivr.net/npm/msrcrypto@1.5.3/msrcrypto.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/crypto-js.js"></script>

答案 1 :(得分:1)

  let secret = CryptoJS.enc.Base64.parse("azureAccessKeyInBase64" as string);
  let hash = CryptoJS.HmacSHA256(strToSign, secret);
  let hashInBase64 = CryptoJS.enc.Base64.stringify(hash);
  let auth = "SharedKey storageaccount:" + hashInBase64;

  console.log("auth: " + auth);

  let secret2 = Buffer.from("azureAccessKeyInBase64" as string, 'base64');
  let hmac = crypto.createHmac('sha256', secret2);
  hmac.write(strToSign);
  hmac.end();
  let hash2 = hmac.read();
  let hash2InBase64 = Buffer.from(hash2).toString('base64');
  let auth2 = "SharedKey storageaccount:" + hash2InBase64;
  console.log("auth2: " + auth);

Auth2通过此代码对我来说等于auth:)