cognito-srp
Version:
Secure Remote Password protocol implementation compatible with Amazon Cognito.
62 lines (61 loc) • 1.9 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const crypto = require("crypto");
const BigInteger_1 = require("./BigInteger");
exports.HASH_TYPE = 'sha256';
function getHash(data, length) {
const hash = crypto
.createHash(exports.HASH_TYPE)
.update(data)
.digest('hex');
return length ? hash.padStart(length * 2, '0') : hash;
}
exports.getHash = getHash;
function padHex(data) {
const hex = data instanceof Buffer ? data.toString('hex') : data;
if (hex.length % 2) {
return '0' + hex;
}
else if ('89ABCDEFabcdef'.includes(hex[0])) {
return '00' + hex;
}
else {
return hex;
}
}
exports.padHex = padHex;
function randomBytes(size = 32) {
return new Promise((resolve, reject) => {
crypto.randomBytes(size, (err, result) => {
if (err)
reject(err);
else
resolve(result);
});
});
}
exports.randomBytes = randomBytes;
function calculateScramblingParameter(A, B) {
const hash = crypto
.createHash(exports.HASH_TYPE)
.update(Buffer.from(padHex(A), 'hex'))
.update(Buffer.from(padHex(B), 'hex'))
.digest();
return BigInteger_1.BigInteger.fromBuffer(hash);
}
exports.calculateScramblingParameter = calculateScramblingParameter;
function calculatePrivateKey(poolname, user, salt) {
const hash = getHash(`${poolname}${user.username}:${user.password}`, 32);
const buffer = Buffer.from(padHex(salt) + hash, 'hex');
return new BigInteger_1.BigInteger(getHash(buffer, 32), 16);
}
exports.calculatePrivateKey = calculatePrivateKey;
function getBigInteger(data) {
if (data instanceof Buffer) {
return BigInteger_1.BigInteger.fromBuffer(data);
}
else {
return new BigInteger_1.BigInteger(data, 16);
}
}
exports.getBigInteger = getBigInteger;