Skip to content

Commit

Permalink
Merge pull request forcedotcom#92 from forcedotcom/identityToken
Browse files Browse the repository at this point in the history
feat(crypto): add CSPRNG token generation
  • Loading branch information
sfdctaka authored Jun 13, 2024
2 parents c4a574c + fa07732 commit 4cfb3fc
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 1 deletion.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@salesforce/lwc-dev-mobile-core",
"description": "Core module supporting Salesforce CLI mobile extension plug-ins",
"version": "4.0.0-alpha.3",
"version": "4.0.0-alpha.4",
"author": {
"name": "Meisam Seyed Aliroteh",
"email": "[email protected]",
Expand Down
11 changes: 11 additions & 0 deletions src/common/CryptoUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
* SPDX-License-Identifier: MIT
* For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT
*/
import { randomBytes } from 'node:crypto';
import forge from 'node-forge';
import { Messages } from '@salesforce/core';

Expand Down Expand Up @@ -129,4 +130,14 @@ export class CryptoUtils {
pemPublicKey: publicKey
};
}

/**
* Generates a cryptographically secure pseudorandom number generator(CSPRNG) token.
*
* @param {number} byteSize the size of the token to be generated. Default is 32(256-bit).
* @returns the generated CSPRNG token expressed in base64.
*/
public static generateIdentityToken(byteSize: number = 32): string {
return randomBytes(byteSize).toString('base64');
}
}
12 changes: 12 additions & 0 deletions test/unit/common/CryptoUtils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,4 +72,16 @@ describe('CryptoUtils tests', () => {
expect(cert.pemPublicKey.startsWith('-----BEGIN PUBLIC KEY-----')).to.be.true;
expect(cert.pemPrivateKey.startsWith('-----BEGIN RSA PRIVATE KEY-----')).to.be.true;
}).timeout(10000); // increase timeout for this test

it('generateIdentityToken succeeds to generate tokens with correct size', async () => {
let token = CryptoUtils.generateIdentityToken();
let b64string = Buffer.from(token, 'base64');
let byteSize = b64string.byteLength;
expect(byteSize).to.equal(32);

token = CryptoUtils.generateIdentityToken(64);
b64string = Buffer.from(token, 'base64');
byteSize = b64string.byteLength;
expect(byteSize).to.equal(64);
});
});

0 comments on commit 4cfb3fc

Please sign in to comment.