Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[CryptoService] Leverage browser native Crypto API to hash strings. #3850

Merged
merged 6 commits into from
Jul 1, 2016
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 21 additions & 8 deletions extensions/amp-analytics/0.1/crypto-impl.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,16 @@

import * as lib from '../../../third_party/closure-library/sha384-generated';
import {getService} from '../../../src/service';
import {dev} from '../../../src/log';

/** @const {string} */
const TAG = 'Crypto';

export class Crypto {

constructor(win) {
if (win.crypto) {
this.subtle = win.crypto.subtle || win.crypto.webkitSubtle;
}
/** @private @const {?SubtleCrypto} */
this.subtle = getSubtle(win);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Still need to append a _ it can be minified better.

}

/**
Expand All @@ -38,9 +41,13 @@ export class Crypto {
return this.subtle.digest('SHA-384', str2ab(str))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe these can take a UInt8Array, not just a ArrayBuffer.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good point.

// [].slice.call(Unit8Array) is a shim for Array.from(Unit8Array)
.then(buffer => [].slice.call(new Uint8Array(buffer)),
() => lib.sha384(str));
e => {
dev.info(TAG, 'Crypto digest promise has rejected, ' +
'fallback to closure lib.', e);
return lib.sha384(str);
});
} catch (e) {
// ignore, fallback to closure lib.
dev.info(TAG, 'Crypto digest has thrown, fallback to closure lib.', e);
}
}
return Promise.resolve(lib.sha384(str));
Expand All @@ -61,17 +68,23 @@ export class Crypto {
}
}

function getSubtle(win) {
if (!win.crypto) {
return null;
}
return win.crypto.subtle || win.crypto.webkitSubtle || null;
}

// A shim for TextEncoder
function str2ab(str) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add JSDoc.

const buf = new ArrayBuffer(str.length);
const bufView = new Uint8Array(buf);
const buf = new Uint8Array(str.length);
for (let i = 0; i < str.length; i++) {
// Apply the same check as in closure lib:
// https://github.com/google/closure-library/blob/master/closure/goog/crypt/sha2_64bit.js#L169
if (str.charCodeAt(i) > 255) {
throw Error('Characters must be in range [0,255]');
}
bufView[i] = str.charCodeAt(i);
buf[i] = str.charCodeAt(i);
}
return buf;
}
Expand Down
23 changes: 22 additions & 1 deletion extensions/amp-analytics/0.1/test/test-crypto-impl.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@
*/

import {Crypto} from '../crypto-impl';
import {Platform} from '../../../../src/platform';
import * as lib from '../../../../third_party/closure-library/sha384-generated';
import * as sinon from 'sinon';

describe('crypto-impl', () => {

Expand Down Expand Up @@ -69,7 +72,25 @@ describe('crypto-impl', () => {
return Promise
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you make sure that native API is actually called? E.g. by counting calls into fallback?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added a test case runs only under Chrome48+.

.all([new Crypto(window).sha384('abc'), new Crypto({}).sha384('abc')])
.then(results => {
expect(results[0]).to.deep.equal(results[1]);
expect(results[0]).to.jsonEqual(results[1]);
});
});

it('should not call closure lib when native API is available', () => {
const platform = new Platform(window);
if (!platform.isChrome() || platform.getMajorVersion() < 48) {
// Run this test only on browsers that we're confident about the existence
// of native Crypto API.
return this.skip();
}

const nativeApiSpy = sinon.spy(window.crypto.subtle, 'digest');
const libSpy = sinon.spy(lib, 'sha384');
return new Crypto(window).sha384Base64('abc').then(hash => {
expect(hash).to.equal(
'ywB1P0WjXou1oD1pmsZQBycsMqsO3tFjGotgWkP_W-2AhgcroefMI1i67KE0yCWn');
expect(nativeApiSpy).to.have.been.calledOnce;
expect(libSpy).to.not.have.been.called;
});
});
});