From 0b2bceb84294e02548d0f862a9d96bc8439cf1ec Mon Sep 17 00:00:00 2001 From: AlphaX-Projects <77661270+AlphaX-Projects@users.noreply.github.com> Date: Fri, 10 May 2024 18:00:47 +0200 Subject: [PATCH] Remove use strict make api full esm compatible --- crypto/api.js | 18 +- crypto/api/PhraseWallet.js | 15 +- crypto/api/api.js | 10 +- crypto/api/bitcoin/AltcoinHDWallet.js | 1272 +++-- crypto/api/bitcoin/ecbn.js | 4978 ++++++++--------- crypto/api/bitcoin/jsbn.js | 3875 +++++++------ crypto/api/constants.js | 2 - crypto/api/createTransaction.js | 16 +- crypto/api/createWallet.js | 8 +- crypto/api/decryptStoredWallet.js | 10 +- crypto/api/deps/Base58.js | 171 +- crypto/api/deps/Base64.js | 19 +- crypto/api/deps/bcrypt.js | 2670 ++++----- crypto/api/deps/broken-ripemd160.js | 343 +- crypto/api/deps/deps.js | 5 +- crypto/api/deps/ed2curve.js | 476 +- crypto/api/deps/nacl-fast.js | 3947 +++++++------ crypto/api/deps/qora.js | 88 +- crypto/api/deps/ripemd160.js | 2 + crypto/api/deps/sha256.js | 245 +- crypto/api/deps/utils.js | 119 +- crypto/api/fetch-request.js | 2 +- crypto/api/kdf.js | 12 +- crypto/api/registerUsername.js | 2 +- crypto/api/storeWallet.js | 6 +- crypto/api/tradeRequest.js | 10 +- crypto/api/transactions/AirdropTransaction.js | 2 +- .../api/transactions/DeployAtTransaction.js | 4 +- crypto/api/transactions/PaymentTransaction.js | 2 +- .../api/transactions/PublicizeTransaction.js | 32 +- crypto/api/transactions/TransactionBase.js | 2 +- .../transactions/TransferPrivsTransaction.js | 4 +- crypto/api/transactions/arbitraryV3.js | 62 +- crypto/api/transactions/chat/ChatBase.js | 236 +- .../api/transactions/chat/ChatTransaction.js | 4 +- .../transactions/chat/GroupChatTransaction.js | 2 +- .../transactions/chat/decryptChatMessage.js | 2 +- .../groups/AddGroupAdminTransaction.js | 2 +- .../groups/CancelGroupBanTransaction.js | 2 +- .../groups/CancelGroupInviteTransaction.js | 2 +- .../groups/CreateGroupTransaction.js | 2 +- .../groups/GroupBanTransaction.js | 2 +- .../groups/GroupInviteTransaction.js | 2 +- .../groups/GroupKickTransaction.js | 2 +- .../groups/JoinGroupTransaction.js | 2 +- .../groups/LeaveGroupTransaction.js | 2 +- .../groups/RemoveGroupAdminTransaction.js | 2 +- .../groups/UpdateGroupTransaction.js | 2 +- .../transactions/names/BuyNameTransacion.js | 2 +- .../names/CancelSellNameTransacion.js | 2 +- .../names/RegisterNameTransaction.js | 2 +- .../transactions/names/SellNameTransacion.js | 2 +- .../names/UpdateNameTransaction.js | 2 +- .../polls/CreatePollTransaction.js | 6 +- .../polls/VoteOnPollTransaction.js | 4 +- .../api/transactions/registerName_dnsthing.js | 60 +- .../RemoveRewardShareTransaction.js | 4 +- .../reward-share/RewardShareTransaction.js | 4 +- crypto/api/utils/randomBase58Generator.js | 18 +- crypto/api/utils/stateAwait.js | 40 +- crypto/api/wallet/base58PublicKeyToAddress.js | 2 +- crypto/api/wallet/publicKeyToAddress.js | 14 +- crypto/api/wallet/validateAddress.js | 4 +- crypto/config.js | 2 +- 64 files changed, 9391 insertions(+), 9472 deletions(-) diff --git a/crypto/api.js b/crypto/api.js index e7ea9034..244be3a5 100644 --- a/crypto/api.js +++ b/crypto/api.js @@ -1,9 +1,9 @@ -import {Sha256} from 'asmcrypto.js' +import { Sha256 } from 'asmcrypto.js' import Base58 from './api/deps/Base58' import Base64 from './api/deps/Base64' -import {base58PublicKeyToAddress} from './api/wallet/base58PublicKeyToAddress' -import {validateAddress} from './api/wallet/validateAddress' -import {decryptChatMessage, decryptChatMessageBase64} from './api/transactions/chat/decryptChatMessage' +import { base58PublicKeyToAddress } from './api/wallet/base58PublicKeyToAddress' +import { validateAddress } from './api/wallet/validateAddress' +import { decryptChatMessage, decryptChatMessageBase64 } from './api/transactions/chat/decryptChatMessage' import _ from 'lodash' window.Sha256 = Sha256 @@ -15,8 +15,8 @@ window.validateAddress = validateAddress window.decryptChatMessage = decryptChatMessage window.decryptChatMessageBase64 = decryptChatMessageBase64 -export { initApi, store } from './api_deps.js' -export * from './api/deps/deps.js' -export * from './api/api.js' -export * from './api/registerUsername.js' -export { createWallet } from './api/createWallet.js' +export { initApi, store } from './api_deps' +export * from './api/deps/deps' +export * from './api/api' +export * from './api/registerUsername' +export { createWallet } from './api/createWallet' diff --git a/crypto/api/PhraseWallet.js b/crypto/api/PhraseWallet.js index bfe81999..8c7732cb 100644 --- a/crypto/api/PhraseWallet.js +++ b/crypto/api/PhraseWallet.js @@ -1,15 +1,12 @@ /* Copyright 2017-2018 @ irontiga and vbcs (original developer) */ -'use strict' -import Base58 from './deps/Base58.js' -import {Sha256, Sha512} from 'asmcrypto.js' -import nacl from './deps/nacl-fast.js' -import utils from './deps/utils.js' - -import {generateSaveWalletData} from './storeWallet.js' - -import publicKeyToAddress from './wallet/publicKeyToAddress.js' +import Base58 from './deps/Base58' +import { Sha256, Sha512 } from 'asmcrypto.js' +import nacl from './deps/nacl-fast' +import utils from './deps/utils' +import { generateSaveWalletData } from './storeWallet' +import publicKeyToAddress from './wallet/publicKeyToAddress' import AltcoinHDWallet from "./bitcoin/AltcoinHDWallet" export default class PhraseWallet { diff --git a/crypto/api/api.js b/crypto/api/api.js index 36a635cc..3c240b2e 100644 --- a/crypto/api/api.js +++ b/crypto/api/api.js @@ -1,5 +1,5 @@ -export { request } from './fetch-request.js' -export { transactionTypes as transactions } from './transactions/transactions.js' -export { processTransaction, processTransactionVersion2, createTransaction, computeChatNonce, signChatTransaction, signArbitraryTransaction, signArbitraryWithFeeTransaction } from './createTransaction.js' -export { tradeBotCreateRequest, tradeBotRespondRequest, signTradeBotTxn, deleteTradeOffer, sendBtc, sendLtc, sendDoge, sendDgb, sendRvn, sendArrr } from './tradeRequest.js' -export { cancelAllOffers } from './transactions/trade-portal/tradeoffer/cancelAllOffers.js' +export { request } from './fetch-request' +export { transactionTypes as transactions } from './transactions/transactions' +export { processTransaction, processTransactionVersion2, createTransaction, computeChatNonce, signChatTransaction, signArbitraryTransaction, signArbitraryWithFeeTransaction } from './createTransaction' +export { tradeBotCreateRequest, tradeBotRespondRequest, signTradeBotTxn, deleteTradeOffer, sendBtc, sendLtc, sendDoge, sendDgb, sendRvn, sendArrr } from './tradeRequest' +export { cancelAllOffers } from './transactions/trade-portal/tradeoffer/cancelAllOffers' diff --git a/crypto/api/bitcoin/AltcoinHDWallet.js b/crypto/api/bitcoin/AltcoinHDWallet.js index b7391b8a..a802382c 100644 --- a/crypto/api/bitcoin/AltcoinHDWallet.js +++ b/crypto/api/bitcoin/AltcoinHDWallet.js @@ -1,859 +1,845 @@ -'use strict'; -import Base58 from '../deps/Base58.js' -import {Sha256, Sha512} from 'asmcrypto.js' +import Base58 from '../deps/Base58' +import { Sha256, Sha512 } from 'asmcrypto.js' import jsSHA from 'jssha' -import RIPEMD160 from '../deps/ripemd160.js' -import utils from '../deps/utils.js' -import {BigInteger, EllipticCurve} from './ecbn.js' +import RIPEMD160 from '../deps/ripemd160' +import utils from '../deps/utils' +import { BigInteger, EllipticCurve } from './ecbn' export default class AltcoinHDWallet { - constructor(addressParams) { + constructor(addressParams) { - /** - * Seed - 32 bytes - */ + /** + * Seed - 32 bytes + */ - this.seed = new Uint8Array(32) + this.seed = new Uint8Array(32) - /** - * Version Bytes - 4 byte - */ + /** + * Version Bytes - 4 byte + */ - this.versionBytes = addressParams + this.versionBytes = addressParams - /** - * Depth - 1 byte - */ + /** + * Depth - 1 byte + */ - this.depth = 0 + this.depth = 0 - /** - * Parent Fingerprint - 4 bytes - */ + /** + * Parent Fingerprint - 4 bytes + */ - this.parentFingerprint = '0x00000000' // master key + this.parentFingerprint = '0x00000000' // master key - /** - * Child Index - 4 bytes - */ + /** + * Child Index - 4 bytes + */ - this.childIndex = '0x00000000' // master key + this.childIndex = '0x00000000' // master key - /** - * Chain Code - 32 bytes - */ + /** + * Chain Code - 32 bytes + */ - this.chainCode = new Uint8Array(32) + this.chainCode = new Uint8Array(32) - /** - * Key Data - 33 bytes - */ + /** + * Key Data - 33 bytes + */ - this.keyData = new Uint8Array(33) + this.keyData = new Uint8Array(33) - /** - * Seed Hash - 64 bytes - */ + /** + * Seed Hash - 64 bytes + */ - this.seedHash = new Uint8Array(64) + this.seedHash = new Uint8Array(64) - /** - * Private Key - 32 bytes - */ + /** + * Private Key - 32 bytes + */ - this.privateKey = new Uint8Array(32) + this.privateKey = new Uint8Array(32) - /** - * Public Key - 33 bytes (compressed) - */ + /** + * Public Key - 33 bytes (compressed) + */ - this.publicKey = new Uint8Array(33) + this.publicKey = new Uint8Array(33) - /** - * Public Key Hash160 (used to derive the parent fingerprint for derived) - */ + /** + * Public Key Hash160 (used to derive the parent fingerprint for derived) + */ - this.publicKeyHash = new Uint8Array(20) + this.publicKeyHash = new Uint8Array(20) - /** - * Master Private Key (Base58 encoded) - */ + /** + * Master Private Key (Base58 encoded) + */ - this.masterPrivateKey = '' + this.masterPrivateKey = '' - /** - * Master Public Key (Base58 encoded) - */ + /** + * Master Public Key (Base58 encoded) + */ - this.masterPublicKey = '' + this.masterPublicKey = '' - /** - * Testnet Master Private Key (Base58 encoded) - THIS IS TESTNET - */ + /** + * Testnet Master Private Key (Base58 encoded) - THIS IS TESTNET + */ - this._tMasterPrivateKey = '' + this._tMasterPrivateKey = '' - /** - * Testnet Master Public Key (Base58 encoded) - THIS IS TESTNET - */ + /** + * Testnet Master Public Key (Base58 encoded) - THIS IS TESTNET + */ - this._tmasterPublicKey = '' + this._tmasterPublicKey = '' - /** - * Child Keys Derivation from the Parent Keys - */ + /** + * Child Keys Derivation from the Parent Keys + */ - /** - * Child Private Key - 32 bytes - */ + /** + * Child Private Key - 32 bytes + */ - this.childPrivateKey = new Uint8Array(32) + this.childPrivateKey = new Uint8Array(32) - /** - * Child Chain Code - 32 bytes - */ + /** + * Child Chain Code - 32 bytes + */ - this.childChainCode = new Uint8Array(32) + this.childChainCode = new Uint8Array(32) - /** - * Child Public Key - 33 bytes (compressed) - */ + /** + * Child Public Key - 33 bytes (compressed) + */ - this.childPublicKey = new Uint8Array(33) + this.childPublicKey = new Uint8Array(33) - /** - * Child Public Key Hash160 (used to derive the parent fingerprint for derived) - */ + /** + * Child Public Key Hash160 (used to derive the parent fingerprint for derived) + */ - this.childPublicKeyHash = new Uint8Array(20) + this.childPublicKeyHash = new Uint8Array(20) - /** - * Extended Private Child Key - Base58 encoded - */ + /** + * Extended Private Child Key - Base58 encoded + */ - this.xPrivateChildKey = '' + this.xPrivateChildKey = '' - /** - * Extended Public Child Key - Base58 encoded - */ + /** + * Extended Public Child Key - Base58 encoded + */ - this.xPublicChildKey = '' + this.xPublicChildKey = '' - /** - * Grand Child Keys Derivation from the Child Keys - */ + /** + * Grand Child Keys Derivation from the Child Keys + */ - /** - * Grand Child Private Key - 32 bytes - */ + /** + * Grand Child Private Key - 32 bytes + */ - this.grandChildPrivateKey = new Uint8Array(32) + this.grandChildPrivateKey = new Uint8Array(32) - /** - * Grand Child Chain Code - 32 bytes - */ + /** + * Grand Child Chain Code - 32 bytes + */ - this.grandChildChainCode = new Uint8Array(32) + this.grandChildChainCode = new Uint8Array(32) - /** - * Grand Child Public Key - 33 bytes (compressed) - */ + /** + * Grand Child Public Key - 33 bytes (compressed) + */ - this.grandChildPublicKey = new Uint8Array(33) + this.grandChildPublicKey = new Uint8Array(33) - /** - * Grand Public Key Hash160 (used to derive the parent fingerprint for derived) - */ + /** + * Grand Public Key Hash160 (used to derive the parent fingerprint for derived) + */ - this.grandChildPublicKeyHash = new Uint8Array(20) + this.grandChildPublicKeyHash = new Uint8Array(20) - /** - * Extended Private Grand Child Key - Base58 encoded - */ + /** + * Extended Private Grand Child Key - Base58 encoded + */ - this.xPrivateGrandChildKey = '' + this.xPrivateGrandChildKey = '' - /** - * Extended Public Grand Child Key - Base58 encoded - */ + /** + * Extended Public Grand Child Key - Base58 encoded + */ - this.xPublicGrandChildKey = '' + this.xPublicGrandChildKey = '' - /** - * Litecoin Legacy Address - Derived from the Grand Child Public Key Hash - */ + /** + * Litecoin Legacy Address - Derived from the Grand Child Public Key Hash + */ - this.litecoinLegacyAddress = '' + this.litecoinLegacyAddress = '' - /** - * TESTNET Litecoin Legacy Address (Derived from the Grand Child Public Key Hash) - THIS IS TESTNET - */ + /** + * TESTNET Litecoin Legacy Address (Derived from the Grand Child Public Key Hash) - THIS IS TESTNET + */ - this._tlitecoinLegacyAddress = '' + this._tlitecoinLegacyAddress = '' - /** - * Wallet - Wallet Object (keys...) - */ + /** + * Wallet - Wallet Object (keys...) + */ - this.wallet = {} - } + this.wallet = {} + } - setSeed(seed) { - this.seed = seed - } + setSeed(seed) { + this.seed = seed + } - createWallet(seed, isBIP44, indicator = null) { + createWallet(seed, isBIP44, indicator = null) { - // Set Seeed - this.setSeed(seed) + // Set Seeed + this.setSeed(seed) - // Generate Seed Hash - this.generateSeedHash(this.seed, isBIP44, indicator) + // Generate Seed Hash + this.generateSeedHash(this.seed, isBIP44, indicator) - // Generate Private Key - this.generatePrivateKey(this.seedHash) + // Generate Private Key + this.generatePrivateKey(this.seedHash) - // Generate Chain Code - this.generateChainCode(this.seedHash) + // Generate Chain Code + this.generateChainCode(this.seedHash) - // Generate Public Key from Private Key - this.generatePublicKey(this.privateKey) + // Generate Public Key from Private Key + this.generatePublicKey(this.privateKey) - // Generate Mainnet Master Private Key - this.generateMainnetMasterPrivateKey() + // Generate Mainnet Master Private Key + this.generateMainnetMasterPrivateKey() - // Generate Mainnet Master Public Key - this.generateMainnetMasterPublicKey() + // Generate Mainnet Master Public Key + this.generateMainnetMasterPublicKey() - // Generate Testnet Master Private Key - this.generateTestnetMasterPrivateKey() + // Generate Testnet Master Private Key + this.generateTestnetMasterPrivateKey() - // Generate Testnet Master Public Key - this.generateTestnetMasterPublicKey() + // Generate Testnet Master Public Key + this.generateTestnetMasterPublicKey() - // Generate Child and Grand Child Keys - this.generateDerivedChildKeys() + // Generate Child and Grand Child Keys + this.generateDerivedChildKeys() - // Return Wallet Object Specification - return this.returnWallet() - } + // Return Wallet Object Specification + return this.returnWallet() + } - generateSeedHash(seed, isBIP44, indicator = null) { - let buffer + generateSeedHash(seed, isBIP44, indicator = null) { + let buffer - if (isBIP44) { - buffer = utils.appendBuffer(seed.reverse(), utils.int32ToBytes(indicator)) - } else { - if(indicator !== null) { - const indicatorString = utils.stringtoUTF8Array(indicator) - buffer = utils.appendBuffer(seed.reverse(), indicatorString) - } - else - { - buffer = seed.reverse() - } - } + if (isBIP44) { + buffer = utils.appendBuffer(seed.reverse(), utils.int32ToBytes(indicator)) + } else { + if (indicator !== null) { + const indicatorString = utils.stringtoUTF8Array(indicator) + buffer = utils.appendBuffer(seed.reverse(), indicatorString) + } + else { + buffer = seed.reverse() + } + } - const _reverseSeedHash = new Sha256().process(buffer).finish().result - this.seedHash = new Sha512().process(utils.appendBuffer(seed, _reverseSeedHash)).finish().result - } + const _reverseSeedHash = new Sha256().process(buffer).finish().result + this.seedHash = new Sha512().process(utils.appendBuffer(seed, _reverseSeedHash)).finish().result + } - generatePrivateKey(seedHash) { - const SECP256K1_CURVE_ORDER = new BigInteger("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141") + generatePrivateKey(seedHash) { + const SECP256K1_CURVE_ORDER = new BigInteger("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141") - const privateKeyHash = seedHash.slice(0, 32) + const privateKeyHash = seedHash.slice(0, 32) - this.seed58 = Base58.encode(privateKeyHash) + this.seed58 = Base58.encode(privateKeyHash) - const _privateKeyHash = [...privateKeyHash] - let privateKeyBigInt = BigInteger.fromByteArrayUnsigned(_privateKeyHash) + const _privateKeyHash = [...privateKeyHash] + let privateKeyBigInt = BigInteger.fromByteArrayUnsigned(_privateKeyHash) - const privateKey = (privateKeyBigInt.mod(SECP256K1_CURVE_ORDER.subtract(BigInteger.ONE))).add(BigInteger.ONE) - this.privateKey = privateKey.toByteArrayUnsigned() - } + const privateKey = (privateKeyBigInt.mod(SECP256K1_CURVE_ORDER.subtract(BigInteger.ONE))).add(BigInteger.ONE) + this.privateKey = privateKey.toByteArrayUnsigned() + } - generateChainCode(seedHash) { - this.chainCode = new Sha256().process(seedHash.slice(32, 64)).finish().result - } + generateChainCode(seedHash) { + this.chainCode = new Sha256().process(seedHash.slice(32, 64)).finish().result + } - generatePublicKey(privateKey) { - const _privateKey = [...privateKey] - const privateKeyBigInt = BigInteger.fromByteArrayUnsigned(_privateKey) + generatePublicKey(privateKey) { + const _privateKey = [...privateKey] + const privateKeyBigInt = BigInteger.fromByteArrayUnsigned(_privateKey) - const epCurve = EllipticCurve.getSECCurveByName("secp256k1") - const curvePoints = epCurve.getG().multiply(privateKeyBigInt) + const epCurve = EllipticCurve.getSECCurveByName("secp256k1") + const curvePoints = epCurve.getG().multiply(privateKeyBigInt) - const x = curvePoints.getX().toBigInteger() - const y = curvePoints.getY().toBigInteger() + const x = curvePoints.getX().toBigInteger() + const y = curvePoints.getY().toBigInteger() - /** - * Deriving Uncompressed Public Key (65 bytes) - * - * const publicKeyBytes = EllipticCurve.integerToBytes(x, 32) - * this.publicKey = publicKeyBytes.concat(EllipticCurve.integerToBytes(y, 32)) - * this.publicKey.unshift(0x04) // append point indicator - */ + /** + * Deriving Uncompressed Public Key (65 bytes) + * + * const publicKeyBytes = EllipticCurve.integerToBytes(x, 32) + * this.publicKey = publicKeyBytes.concat(EllipticCurve.integerToBytes(y, 32)) + * this.publicKey.unshift(0x04) // append point indicator + */ - // Compressed Public Key (33 bytes) - this.publicKey = EllipticCurve.integerToBytes(x, 32) + // Compressed Public Key (33 bytes) + this.publicKey = EllipticCurve.integerToBytes(x, 32) - if (y.isEven()) { - this.publicKey.unshift(0x02) // append point indicator - } else { - this.publicKey.unshift(0x03) // append point indicator - } + if (y.isEven()) { + this.publicKey.unshift(0x02) // append point indicator + } else { + this.publicKey.unshift(0x03) // append point indicator + } - // PublicKey Hash - const publicKeySHA256 = new Sha256().process(new Uint8Array(this.publicKey)).finish().result + // PublicKey Hash + const publicKeySHA256 = new Sha256().process(new Uint8Array(this.publicKey)).finish().result this.publicKeyHash = new RIPEMD160().update(Buffer.from(publicKeySHA256)).digest('hex') - } + } - generateMainnetMasterPrivateKey() { - // Serialization Variable - const s = [] + generateMainnetMasterPrivateKey() { + // Serialization Variable + const s = [] - // Append Version Byte - s.push(...(utils.int32ToBytes(this.versionBytes.mainnet.private))) + // Append Version Byte + s.push(...(utils.int32ToBytes(this.versionBytes.mainnet.private))) - // Append Depth - s.push(this.depth) + // Append Depth + s.push(this.depth) - // Append Parent Fingerprint - s.push(...(utils.int32ToBytes(this.parentFingerprint))) + // Append Parent Fingerprint + s.push(...(utils.int32ToBytes(this.parentFingerprint))) - // Append Child Number - s.push(...(utils.int32ToBytes(this.childIndex))) + // Append Child Number + s.push(...(utils.int32ToBytes(this.childIndex))) - // Append Chain Code - s.push(...this.chainCode) + // Append Chain Code + s.push(...this.chainCode) - // Append 1 byte '0x00' (to make the key data 33 bytes, DO THIS ONLY FOR PRIVATE KEYS ) - s.push(0) + // Append 1 byte '0x00' (to make the key data 33 bytes, DO THIS ONLY FOR PRIVATE KEYS ) + s.push(0) - //if the private key length is less than 32 let's add leading zeros - if(this.privateKey.length<32){ - for(let i=this.privateKey.length;i<32;i++){ - s.push(0) - } - } + //if the private key length is less than 32 let's add leading zeros + if (this.privateKey.length < 32) { + for (let i = this.privateKey.length; i < 32; i++) { + s.push(0) + } + } - // Append Private Key - s.push(...this.privateKey) + // Append Private Key + s.push(...this.privateKey) - // Generate CheckSum - const _s = new Uint8Array(s) - const _checkSum = new Sha256().process(new Sha256().process(_s).finish().result).finish().result - const checkSum = _checkSum.slice(0, 4) + // Generate CheckSum + const _s = new Uint8Array(s) + const _checkSum = new Sha256().process(new Sha256().process(_s).finish().result).finish().result + const checkSum = _checkSum.slice(0, 4) - // Append CheckSum - s.push(...checkSum) // And this brings us to the end of the serialization... + // Append CheckSum + s.push(...checkSum) // And this brings us to the end of the serialization... - // Save to Private Key as Base58 encoded - this.masterPrivateKey = Base58.encode(s) - } + // Save to Private Key as Base58 encoded + this.masterPrivateKey = Base58.encode(s) + } - generateMainnetMasterPublicKey() { - // Serialization Variable - const s = [] + generateMainnetMasterPublicKey() { + // Serialization Variable + const s = [] - // Append Version Byte - s.push(...(utils.int32ToBytes(this.versionBytes.mainnet.public))) + // Append Version Byte + s.push(...(utils.int32ToBytes(this.versionBytes.mainnet.public))) - // Append Depth - s.push(this.depth) + // Append Depth + s.push(this.depth) - // Append Parent Fingerprint - s.push(...(utils.int32ToBytes(this.parentFingerprint))) + // Append Parent Fingerprint + s.push(...(utils.int32ToBytes(this.parentFingerprint))) - // Append Child Number - s.push(...(utils.int32ToBytes(this.childIndex))) + // Append Child Number + s.push(...(utils.int32ToBytes(this.childIndex))) - // Append Chain Code - s.push(...this.chainCode) + // Append Chain Code + s.push(...this.chainCode) - // Append Public Key - s.push(...this.publicKey) + // Append Public Key + s.push(...this.publicKey) - // Generate CheckSum - const _s = new Uint8Array(s) - const _checkSum = new Sha256().process(new Sha256().process(_s).finish().result).finish().result - const checkSum = _checkSum.slice(0, 4) + // Generate CheckSum + const _s = new Uint8Array(s) + const _checkSum = new Sha256().process(new Sha256().process(_s).finish().result).finish().result + const checkSum = _checkSum.slice(0, 4) - // Append CheckSum - s.push(...checkSum) // And this brings us to the end of the serialization... + // Append CheckSum + s.push(...checkSum) // And this brings us to the end of the serialization... - // Save to Public Key as Base58 encoded - this.masterPublicKey = Base58.encode(s) - } + // Save to Public Key as Base58 encoded + this.masterPublicKey = Base58.encode(s) + } - generateTestnetMasterPrivateKey() { + generateTestnetMasterPrivateKey() { - // To be Used ONLY in Testnet... + // To be Used ONLY in Testnet... - // Serialization Variable - const s = [] + // Serialization Variable + const s = [] - // Append Version Byte - s.push(...(utils.int32ToBytes(this.versionBytes.testnet.private))) + // Append Version Byte + s.push(...(utils.int32ToBytes(this.versionBytes.testnet.private))) - // Append Depth - s.push(this.depth) + // Append Depth + s.push(this.depth) - // Append Parent Fingerprint - s.push(...(utils.int32ToBytes(this.parentFingerprint))) + // Append Parent Fingerprint + s.push(...(utils.int32ToBytes(this.parentFingerprint))) - // Append Child Number - s.push(...(utils.int32ToBytes(this.childIndex))) + // Append Child Number + s.push(...(utils.int32ToBytes(this.childIndex))) - // Append Chain Code - s.push(...this.chainCode) + // Append Chain Code + s.push(...this.chainCode) - // Append 1 byte '0x00' (to make the key data 33 bytes, DO THIS ONLY FOR PRIVATE KEYS ) - s.push(0) + // Append 1 byte '0x00' (to make the key data 33 bytes, DO THIS ONLY FOR PRIVATE KEYS ) + s.push(0) - // Append Private Key - s.push(...this.privateKey) + // Append Private Key + s.push(...this.privateKey) - // Generate CheckSum - const _s = new Uint8Array(s) - const _checkSum = new Sha256().process(new Sha256().process(_s).finish().result).finish().result - const checkSum = _checkSum.slice(0, 4) + // Generate CheckSum + const _s = new Uint8Array(s) + const _checkSum = new Sha256().process(new Sha256().process(_s).finish().result).finish().result + const checkSum = _checkSum.slice(0, 4) - // Append CheckSum - s.push(...checkSum) // And this brings us to the end of the serialization... + // Append CheckSum + s.push(...checkSum) // And this brings us to the end of the serialization... - // Save to Private Key as Base58 encoded - this._tMasterPrivateKey = Base58.encode(s) - } + // Save to Private Key as Base58 encoded + this._tMasterPrivateKey = Base58.encode(s) + } - generateTestnetMasterPublicKey() { + generateTestnetMasterPublicKey() { - // To be Used ONLY in Testnet... + // To be Used ONLY in Testnet... - // Serialization Variable - const s = [] + // Serialization Variable + const s = [] - // Append Version Byte - s.push(...(utils.int32ToBytes(this.versionBytes.testnet.public))) + // Append Version Byte + s.push(...(utils.int32ToBytes(this.versionBytes.testnet.public))) - // Append Depth - s.push(this.depth) + // Append Depth + s.push(this.depth) - // Append Parent Fingerprint - s.push(...(utils.int32ToBytes(this.parentFingerprint))) + // Append Parent Fingerprint + s.push(...(utils.int32ToBytes(this.parentFingerprint))) - // Append Child Number - s.push(...(utils.int32ToBytes(this.childIndex))) + // Append Child Number + s.push(...(utils.int32ToBytes(this.childIndex))) - // Append Chain Code - s.push(...this.chainCode) + // Append Chain Code + s.push(...this.chainCode) - // Append Private Key - s.push(...this.publicKey) + // Append Private Key + s.push(...this.publicKey) - // Generate CheckSum - const _s = new Uint8Array(s) - const _checkSum = new Sha256().process(new Sha256().process(_s).finish().result).finish().result - const checkSum = _checkSum.slice(0, 4) + // Generate CheckSum + const _s = new Uint8Array(s) + const _checkSum = new Sha256().process(new Sha256().process(_s).finish().result).finish().result + const checkSum = _checkSum.slice(0, 4) - // Append CheckSum - s.push(...checkSum) // And this brings us to the end of the serialization... + // Append CheckSum + s.push(...checkSum) // And this brings us to the end of the serialization... - // Save to Private Key as Base58 encoded - this._tmasterPublicKey = Base58.encode(s) - } + // Save to Private Key as Base58 encoded + this._tmasterPublicKey = Base58.encode(s) + } - generateDerivedChildKeys() { + generateDerivedChildKeys() { - // SPEC INFO: https://en.bitcoin.it/wiki/BIP_0032#Child_key_derivation_.28CKD.29_functions - // NOTE: will not be using some of derivations func as the value is known. (So I'd rather shove in the values and rewrite out the derivations later ?) + // SPEC INFO: https://en.bitcoin.it/wiki/BIP_0032#Child_key_derivation_.28CKD.29_functions + // NOTE: will not be using some of derivations func as the value is known. (So I'd rather shove in the values and rewrite out the derivations later ?) - // NOTE: I "re-wrote" and "reduplicate" the code for child and grandChild keys derivations inorder to get the child and grandchild from the child - // TODO: Make this more better in the future + // NOTE: I "re-wrote" and "reduplicate" the code for child and grandChild keys derivations inorder to get the child and grandchild from the child + // TODO: Make this more better in the future - const path = 'm/0/0' - // let p = path.split('/') + const path = 'm/0/0' + // let p = path.split('/') - // Get Public kEY - const derivePublicChildKey = () => { + // Get Public kEY + const derivePublicChildKey = () => { - const _privateKey = [...this.childPrivateKey] - const privateKeyBigInt = BigInteger.fromByteArrayUnsigned(_privateKey) + const _privateKey = [...this.childPrivateKey] + const privateKeyBigInt = BigInteger.fromByteArrayUnsigned(_privateKey) - const epCurve = EllipticCurve.getSECCurveByName("secp256k1") - const curvePoints = epCurve.getG().multiply(privateKeyBigInt) + const epCurve = EllipticCurve.getSECCurveByName("secp256k1") + const curvePoints = epCurve.getG().multiply(privateKeyBigInt) - const x = curvePoints.getX().toBigInteger() - const y = curvePoints.getY().toBigInteger() + const x = curvePoints.getX().toBigInteger() + const y = curvePoints.getY().toBigInteger() - // Compressed Public Key (33 bytes) - this.childPublicKey = EllipticCurve.integerToBytes(x, 32) + // Compressed Public Key (33 bytes) + this.childPublicKey = EllipticCurve.integerToBytes(x, 32) - if (y.isEven()) { + if (y.isEven()) { - this.childPublicKey.unshift(0x02) // append point indicator - } else { + this.childPublicKey.unshift(0x02) // append point indicator + } else { - this.childPublicKey.unshift(0x03) // append point indicator - } + this.childPublicKey.unshift(0x03) // append point indicator + } - // PublicKey Hash - const childPublicKeySHA256 = new Sha256().process(new Uint8Array(this.childPublicKey)).finish().result + // PublicKey Hash + const childPublicKeySHA256 = new Sha256().process(new Uint8Array(this.childPublicKey)).finish().result this.childPublicKeyHash = new RIPEMD160().update(Buffer.from(childPublicKeySHA256)).digest('hex') + // Call deriveExtendedPublicChildKey // WIll be hardcoding the values... + deriveExtendedPublicChildKey(1, 0) + } - // Call deriveExtendedPublicChildKey // WIll be hardcoding the values... - deriveExtendedPublicChildKey(1, 0) - } + const derivePrivateChildKey = (cI) => { - const derivePrivateChildKey = (cI) => { + let ib = [] + ib.push((cI >> 24) & 0xff) + ib.push((cI >> 16) & 0xff) + ib.push((cI >> 8) & 0xff) + ib.push(cI & 0xff) - let ib = [] - ib.push((cI >> 24) & 0xff) - ib.push((cI >> 16) & 0xff) - ib.push((cI >> 8) & 0xff) - ib.push(cI & 0xff) + const s = [...this.publicKey].concat(ib) - const s = [...this.publicKey].concat(ib) + const _hmacSha512 = new jsSHA("SHA-512", "UINT8ARRAY", { numRounds: 1, hmacKey: { value: this.chainCode, format: "UINT8ARRAY" } }) + _hmacSha512.update(new Uint8Array(s)) - const _hmacSha512 = new jsSHA("SHA-512", "UINT8ARRAY", { numRounds: 1, hmacKey: { value: this.chainCode, format: "UINT8ARRAY" } }) - _hmacSha512.update(new Uint8Array(s)) + const IL = BigInteger.fromByteArrayUnsigned([..._hmacSha512.getHMAC('UINT8ARRAY').slice(0, 32)]) + this.childChainCode = _hmacSha512.getHMAC('UINT8ARRAY').slice(32, 64) // IR according to the SPEC + + // SECP256k1 init + const epCurve = EllipticCurve.getSECCurveByName("secp256k1") + + const ki = IL.add(BigInteger.fromByteArrayUnsigned(this.privateKey)).mod(epCurve.getN()) // parse256(IL) + kpar (mod n) ==> ki + this.childPrivateKey = ki.toByteArrayUnsigned() + + // Call deriveExtendedPrivateChildKey + deriveExtendedPrivateChildKey(1, 0) + } - const IL = BigInteger.fromByteArrayUnsigned([..._hmacSha512.getHMAC('UINT8ARRAY').slice(0, 32)]) - this.childChainCode = _hmacSha512.getHMAC('UINT8ARRAY').slice(32, 64) // IR according to the SPEC + const deriveExtendedPrivateChildKey = (i, childIndex) => { + + // Serialization Variable + const s = [] + + // Append Version Byte + s.push(...(utils.int32ToBytes(this.versionBytes.mainnet.private))) + + // Append Depth (using the index as depth) + i = parseInt(i) + s.push(i) + + // Append Parent Fingerprint + s.push(...(this.publicKeyHash.slice(0, 4))) + + // Append Child Index + s.push(childIndex >>> 24) + s.push((childIndex >>> 16) & 0xff) + s.push((childIndex >>> 8) & 0xff) + s.push(childIndex & 0xff) + + // Append Chain Code + s.push(...this.childChainCode) + + // Append 1 byte '0x00' (to make the key data 33 bytes, DO THIS ONLY FOR PRIVATE KEYS ) + s.push(0) + + // Append Private Key + s.push(...this.childPrivateKey) + + // Generate CheckSum + const _s = new Uint8Array(s) + const _checkSum = new Sha256().process(new Sha256().process(_s).finish().result).finish().result + const checkSum = _checkSum.slice(0, 4) + + // Append CheckSum + s.push(...checkSum) // And this brings us to the end of the serialization... + + // Save to Private Key as Base58 encoded + this.xPrivateChildKey = Base58.encode(s) + } + + const deriveExtendedPublicChildKey = (i, childIndex) => { + + // Serialization Variable + const s = [] + + // Append Version Byte + s.push(...(utils.int32ToBytes(this.versionBytes.mainnet.public))) + + // Append Depth + i = parseInt(i) + s.push(i) + + // Append Parent Fingerprint + s.push(...(this.publicKeyHash.slice(0, 4))) + + // Append Child Index + s.push(childIndex >>> 24) + s.push((childIndex >>> 16) & 0xff) + s.push((childIndex >>> 8) & 0xff) + s.push(childIndex & 0xff) + + // Append Chain Code + s.push(...this.childChainCode) + + // Append Public Key + s.push(...this.childPublicKey) + + // Generate CheckSum + const _s = new Uint8Array(s) + const _checkSum = new Sha256().process(new Sha256().process(_s).finish().result).finish().result + const checkSum = _checkSum.slice(0, 4) + + // Append CheckSum + s.push(...checkSum) // And this brings us to the end of the serialization... - // SECP256k1 init - const epCurve = EllipticCurve.getSECCurveByName("secp256k1") + // Save to Public Key as Base58 encoded + this.xPublicChildKey = Base58.encode(s) + } - const ki = IL.add(BigInteger.fromByteArrayUnsigned(this.privateKey)).mod(epCurve.getN()) // parse256(IL) + kpar (mod n) ==> ki - this.childPrivateKey = ki.toByteArrayUnsigned() + /** + * GRAND CHILD KEYS + * + * NOTE: I know this is not the best way to generate this (even though it works the way it ought) + * Things to rewrite will be and not limited to deriving this through a for loop, removing hard code values, etc... + */ - // Call deriveExtendedPrivateChildKey - deriveExtendedPrivateChildKey(1, 0) - } + const derivePublicGrandChildKey = () => { + + const _privateKey = [...this.grandChildPrivateKey] + const privateKeyBigInt = BigInteger.fromByteArrayUnsigned(_privateKey) - const deriveExtendedPrivateChildKey = (i, childIndex) => { + const epCurve = EllipticCurve.getSECCurveByName("secp256k1") + const curvePoints = epCurve.getG().multiply(privateKeyBigInt) - // Serialization Variable - const s = [] + const x = curvePoints.getX().toBigInteger() + const y = curvePoints.getY().toBigInteger() - // Append Version Byte - s.push(...(utils.int32ToBytes(this.versionBytes.mainnet.private))) - - // Append Depth (using the index as depth) - i = parseInt(i) - s.push(i) - - // Append Parent Fingerprint - s.push(...(this.publicKeyHash.slice(0, 4))) - - // Append Child Index - s.push(childIndex >>> 24) - s.push((childIndex >>> 16) & 0xff) - s.push((childIndex >>> 8) & 0xff) - s.push(childIndex & 0xff) - - // Append Chain Code - s.push(...this.childChainCode) - - // Append 1 byte '0x00' (to make the key data 33 bytes, DO THIS ONLY FOR PRIVATE KEYS ) - s.push(0) - - // Append Private Key - s.push(...this.childPrivateKey) - - // Generate CheckSum - const _s = new Uint8Array(s) - const _checkSum = new Sha256().process(new Sha256().process(_s).finish().result).finish().result - const checkSum = _checkSum.slice(0, 4) - - // Append CheckSum - s.push(...checkSum) // And this brings us to the end of the serialization... - - // Save to Private Key as Base58 encoded - this.xPrivateChildKey = Base58.encode(s) - } - - const deriveExtendedPublicChildKey = (i, childIndex) => { - - // Serialization Variable - const s = [] - - // Append Version Byte - s.push(...(utils.int32ToBytes(this.versionBytes.mainnet.public))) - - // Append Depth - i = parseInt(i) - s.push(i) - - // Append Parent Fingerprint - s.push(...(this.publicKeyHash.slice(0, 4))) - - // Append Child Index - s.push(childIndex >>> 24) - s.push((childIndex >>> 16) & 0xff) - s.push((childIndex >>> 8) & 0xff) - s.push(childIndex & 0xff) - - // Append Chain Code - s.push(...this.childChainCode) - - // Append Public Key - s.push(...this.childPublicKey) - - // Generate CheckSum - const _s = new Uint8Array(s) - const _checkSum = new Sha256().process(new Sha256().process(_s).finish().result).finish().result - const checkSum = _checkSum.slice(0, 4) - - // Append CheckSum - s.push(...checkSum) // And this brings us to the end of the serialization... + // Compressed Public Key (33 bytes) + this.grandChildPublicKey = EllipticCurve.integerToBytes(x, 32) - // Save to Public Key as Base58 encoded - this.xPublicChildKey = Base58.encode(s) - } + if (y.isEven()) { + this.grandChildPublicKey.unshift(0x02) // append point indicator + } else { + this.grandChildPublicKey.unshift(0x03) // append point indicator + } - - /** - * GRAND CHILD KEYS - * - * NOTE: I know this is not the best way to generate this (even though it works the way it ought) - * Things to rewrite will be and not limited to deriving this through a for loop, removing hard code values, etc... - */ - - const derivePublicGrandChildKey = () => { - - const _privateKey = [...this.grandChildPrivateKey] - const privateKeyBigInt = BigInteger.fromByteArrayUnsigned(_privateKey) - - - const epCurve = EllipticCurve.getSECCurveByName("secp256k1") - const curvePoints = epCurve.getG().multiply(privateKeyBigInt) - - const x = curvePoints.getX().toBigInteger() - const y = curvePoints.getY().toBigInteger() - - // Compressed Public Key (33 bytes) - this.grandChildPublicKey = EllipticCurve.integerToBytes(x, 32) - - - if (y.isEven()) { - this.grandChildPublicKey.unshift(0x02) // append point indicator - } else { - this.grandChildPublicKey.unshift(0x03) // append point indicator - } - - - // PublicKey Hash - const grandChildPublicKeySHA256 = new Sha256().process(new Uint8Array(this.grandChildPublicKey)).finish().result + // PublicKey Hash + const grandChildPublicKeySHA256 = new Sha256().process(new Uint8Array(this.grandChildPublicKey)).finish().result this.grandChildPublicKeyHash = new RIPEMD160().update(Buffer.from(grandChildPublicKeySHA256)).digest('hex') - // Call deriveExtendedPublicChildKey // WIll be hardcoding the values... - deriveExtendedPublicGrandChildKey(2, 0) + // Call deriveExtendedPublicChildKey // WIll be hardcoding the values... + deriveExtendedPublicGrandChildKey(2, 0) - /** - * Derive Litecoin Legacy Address - */ + /** + * Derive Litecoin Legacy Address + */ - // Append Address Prefix - let prefix = [this.versionBytes.mainnet.prefix] - if (2 == this.versionBytes.mainnet.prefix.length) { - prefix = [this.versionBytes.mainnet.prefix[0]] - prefix.push([this.versionBytes.mainnet.prefix[1]]) - } + // Append Address Prefix + let prefix = [this.versionBytes.mainnet.prefix] + if (2 == this.versionBytes.mainnet.prefix.length) { + prefix = [this.versionBytes.mainnet.prefix[0]] + prefix.push([this.versionBytes.mainnet.prefix[1]]) + } - const k = prefix.concat(...this.grandChildPublicKeyHash) + const k = prefix.concat(...this.grandChildPublicKeyHash) - // Derive Checksum - const _addressCheckSum = new Sha256().process(new Sha256().process(new Uint8Array(k)).finish().result).finish().result - const addressCheckSum = _addressCheckSum.slice(0, 4) + // Derive Checksum + const _addressCheckSum = new Sha256().process(new Sha256().process(new Uint8Array(k)).finish().result).finish().result + const addressCheckSum = _addressCheckSum.slice(0, 4) - // Append CheckSum - const _litecoinLegacyAddress = k.concat(...addressCheckSum) + // Append CheckSum + const _litecoinLegacyAddress = k.concat(...addressCheckSum) - // Convert to Base58 - this.litecoinLegacyAddress = Base58.encode(_litecoinLegacyAddress) + // Convert to Base58 + this.litecoinLegacyAddress = Base58.encode(_litecoinLegacyAddress) - /** - * Derive TESTNET Litecoin Legacy Address - */ + /** + * Derive TESTNET Litecoin Legacy Address + */ - // Append Version Byte - const tK = [this.versionBytes.testnet.prefix].concat(...this.grandChildPublicKeyHash) + // Append Version Byte + const tK = [this.versionBytes.testnet.prefix].concat(...this.grandChildPublicKeyHash) - // Derive Checksum - const _tAddressCheckSum = new Sha256().process(new Sha256().process(new Uint8Array(tK)).finish().result).finish().result - const tAddressCheckSum = _tAddressCheckSum.slice(0, 4) + // Derive Checksum + const _tAddressCheckSum = new Sha256().process(new Sha256().process(new Uint8Array(tK)).finish().result).finish().result + const tAddressCheckSum = _tAddressCheckSum.slice(0, 4) - // Append CheckSum - const _tlitecoinLegacyAddress = tK.concat(...tAddressCheckSum) + // Append CheckSum + const _tlitecoinLegacyAddress = tK.concat(...tAddressCheckSum) - // Convert to Base58 - this._tlitecoinLegacyAddress = Base58.encode(_tlitecoinLegacyAddress) - } + // Convert to Base58 + this._tlitecoinLegacyAddress = Base58.encode(_tlitecoinLegacyAddress) + } - const derivePrivateGrandChildKey = (cI, i) => { + const derivePrivateGrandChildKey = (cI, i) => { - let ib = [] - ib.push((cI >> 24) & 0xff) - ib.push((cI >> 16) & 0xff) - ib.push((cI >> 8) & 0xff) - ib.push(cI & 0xff) + let ib = [] + ib.push((cI >> 24) & 0xff) + ib.push((cI >> 16) & 0xff) + ib.push((cI >> 8) & 0xff) + ib.push(cI & 0xff) - const s = [...this.childPublicKey].concat(ib) + const s = [...this.childPublicKey].concat(ib) - const _hmacSha512 = new jsSHA("SHA-512", "UINT8ARRAY", { numRounds: 1, hmacKey: { value: this.childChainCode, format: "UINT8ARRAY" } }) - _hmacSha512.update(new Uint8Array(s)) + const _hmacSha512 = new jsSHA("SHA-512", "UINT8ARRAY", { numRounds: 1, hmacKey: { value: this.childChainCode, format: "UINT8ARRAY" } }) + _hmacSha512.update(new Uint8Array(s)) - const IL = BigInteger.fromByteArrayUnsigned([..._hmacSha512.getHMAC('UINT8ARRAY').slice(0, 32)]) - this.grandChildChainCode = _hmacSha512.getHMAC('UINT8ARRAY').slice(32, 64) // IR according to the SPEC + const IL = BigInteger.fromByteArrayUnsigned([..._hmacSha512.getHMAC('UINT8ARRAY').slice(0, 32)]) + this.grandChildChainCode = _hmacSha512.getHMAC('UINT8ARRAY').slice(32, 64) // IR according to the SPEC - // SECP256k1 init - const epCurve = EllipticCurve.getSECCurveByName("secp256k1") + // SECP256k1 init + const epCurve = EllipticCurve.getSECCurveByName("secp256k1") - const ki = IL.add(BigInteger.fromByteArrayUnsigned(this.childPrivateKey)).mod(epCurve.getN()) // parse256(IL) + kpar (mod n) ==> ki - this.grandChildPrivateKey = ki.toByteArrayUnsigned() + const ki = IL.add(BigInteger.fromByteArrayUnsigned(this.childPrivateKey)).mod(epCurve.getN()) // parse256(IL) + kpar (mod n) ==> ki + this.grandChildPrivateKey = ki.toByteArrayUnsigned() - // Call deriveExtendedPrivateChildKey - deriveExtendedPrivateGrandChildKey(2, 0) - } + // Call deriveExtendedPrivateChildKey + deriveExtendedPrivateGrandChildKey(2, 0) + } + + const deriveExtendedPrivateGrandChildKey = (i, childIndex) => { + + // Serialization Variable + const s = [] + + // Append Version Byte + s.push(...(utils.int32ToBytes(this.versionBytes.mainnet.private))) + + // Append Depth (using the index as depth) + i = parseInt(i) + s.push(i) + + // Append Parent Fingerprint + s.push(...(this.childPublicKeyHash.slice(0, 4))) + + // Append Child Index + s.push(childIndex >>> 24) + s.push((childIndex >>> 16) & 0xff) + s.push((childIndex >>> 8) & 0xff) + s.push(childIndex & 0xff) + + // Append Chain Code + s.push(...this.grandChildChainCode) + + // Append 1 byte '0x00' (to make the key data 33 bytes, DO THIS ONLY FOR PRIVATE KEYS ) + s.push(0) + + // Append Private Key + s.push(...this.grandChildPrivateKey) + + // Generate CheckSum + const _s = new Uint8Array(s) + const _checkSum = new Sha256().process(new Sha256().process(_s).finish().result).finish().result + const checkSum = _checkSum.slice(0, 4) + + // Append CheckSum + s.push(...checkSum) // And this brings us to the end of the serialization... + + // Save to Private Key as Base58 encoded + this.xPrivateGrandChildKey = Base58.encode(s) + } + + const deriveExtendedPublicGrandChildKey = (i, childIndex) => { + + // Serialization Variable + const s = [] + + // Append Version Byte + s.push(...(utils.int32ToBytes(this.versionBytes.mainnet.public))) + + // Append Depth + i = parseInt(i) + s.push(i) + + // Append Parent Fingerprint + s.push(...(this.childPublicKeyHash.slice(0, 4))) + + // Append Child Index + s.push(childIndex >>> 24) + s.push((childIndex >>> 16) & 0xff) + s.push((childIndex >>> 8) & 0xff) + s.push(childIndex & 0xff) + + // Append Chain Code + s.push(...this.grandChildChainCode) + + // Append Public Key + s.push(...this.grandChildPublicKey) + + // Generate CheckSum + const _s = new Uint8Array(s) + const _checkSum = new Sha256().process(new Sha256().process(_s).finish().result).finish().result + const checkSum = _checkSum.slice(0, 4) + + // Append CheckSum + s.push(...checkSum) // And this brings us to the end of the serialization... + + // Save to Public Key as Base58 encoded + this.xPublicGrandChildKey = Base58.encode(s) + } + + // Hard Code value.. + let childIndex = 0 + + // Call derivePrivateChildKey //Hard code value + derivePrivateChildKey(childIndex) + + // Call derivePublicChildKey + derivePublicChildKey() - const deriveExtendedPrivateGrandChildKey = (i, childIndex) => { + // Call derivePrivateGrandChildKey // Hard Code value... + derivePrivateGrandChildKey(0, 2) - // Serialization Variable - const s = [] + // Call derivePublicGrandChildKey + derivePublicGrandChildKey() + } - // Append Version Byte - s.push(...(utils.int32ToBytes(this.versionBytes.mainnet.private))) + returnWallet() { - // Append Depth (using the index as depth) - i = parseInt(i) - s.push(i) + // Will be limiting the exported Wallet Object to just the Master keys and Legacy Addresses - // Append Parent Fingerprint - s.push(...(this.childPublicKeyHash.slice(0, 4))) + const wallet = { + derivedMasterPrivateKey: this.masterPrivateKey, + derivedMasterPublicKey: this.masterPublicKey, + _tDerivedMasterPrivateKey: this._tMasterPrivateKey, + _tDerivedmasterPublicKey: this._tmasterPublicKey, + seed58: this.seed58, + address: this.litecoinLegacyAddress, + _taddress: this._tlitecoinLegacyAddress + } - // Append Child Index - s.push(childIndex >>> 24) - s.push((childIndex >>> 16) & 0xff) - s.push((childIndex >>> 8) & 0xff) - s.push(childIndex & 0xff) - - // Append Chain Code - s.push(...this.grandChildChainCode) - - // Append 1 byte '0x00' (to make the key data 33 bytes, DO THIS ONLY FOR PRIVATE KEYS ) - s.push(0) - - // Append Private Key - s.push(...this.grandChildPrivateKey) - - // Generate CheckSum - const _s = new Uint8Array(s) - const _checkSum = new Sha256().process(new Sha256().process(_s).finish().result).finish().result - const checkSum = _checkSum.slice(0, 4) - - // Append CheckSum - s.push(...checkSum) // And this brings us to the end of the serialization... - - // Save to Private Key as Base58 encoded - this.xPrivateGrandChildKey = Base58.encode(s) - } - - const deriveExtendedPublicGrandChildKey = (i, childIndex) => { - - // Serialization Variable - const s = [] - - // Append Version Byte - s.push(...(utils.int32ToBytes(this.versionBytes.mainnet.public))) - - // Append Depth - i = parseInt(i) - s.push(i) - - // Append Parent Fingerprint - s.push(...(this.childPublicKeyHash.slice(0, 4))) - - // Append Child Index - s.push(childIndex >>> 24) - s.push((childIndex >>> 16) & 0xff) - s.push((childIndex >>> 8) & 0xff) - s.push(childIndex & 0xff) - - // Append Chain Code - s.push(...this.grandChildChainCode) - - // Append Public Key - s.push(...this.grandChildPublicKey) - - // Generate CheckSum - const _s = new Uint8Array(s) - const _checkSum = new Sha256().process(new Sha256().process(_s).finish().result).finish().result - const checkSum = _checkSum.slice(0, 4) - - // Append CheckSum - s.push(...checkSum) // And this brings us to the end of the serialization... - - // Save to Public Key as Base58 encoded - this.xPublicGrandChildKey = Base58.encode(s) - } - - - - // Hard Code value.. - let childIndex = 0 - - // Call derivePrivateChildKey //Hard code value - derivePrivateChildKey(childIndex) - - // Call derivePublicChildKey - derivePublicChildKey() - - - // Call derivePrivateGrandChildKey // Hard Code value... - derivePrivateGrandChildKey(0, 2) - - // Call derivePublicGrandChildKey - derivePublicGrandChildKey() - } - - returnWallet() { - - // Will be limiting the exported Wallet Object to just the Master keys and Legacy Addresses - - const wallet = { - derivedMasterPrivateKey: this.masterPrivateKey, - derivedMasterPublicKey: this.masterPublicKey, - _tDerivedMasterPrivateKey: this._tMasterPrivateKey, - _tDerivedmasterPublicKey: this._tmasterPublicKey, - seed58: this.seed58, - // derivedPrivateChildKey: this.xPrivateChildKey, - // derivedPublicChildKey: this.xPublicChildKey, - // derivedPrivateGrandChildKey: this.xPrivateGrandChildKey, - // derivedPublicGrandChildKey: this.xPublicGrandChildKey, - address: this.litecoinLegacyAddress, - _taddress: this._tlitecoinLegacyAddress - } - - this.wallet = wallet - return wallet - } + this.wallet = wallet + return wallet + } } diff --git a/crypto/api/bitcoin/ecbn.js b/crypto/api/bitcoin/ecbn.js index 5c08091a..311cc2ef 100644 --- a/crypto/api/bitcoin/ecbn.js +++ b/crypto/api/bitcoin/ecbn.js @@ -6,1998 +6,1988 @@ */ (function () { - - - // Copyright (c) 2005 Tom Wu - // All Rights Reserved. - // See "LICENSE" for details. - - // Basic JavaScript BN library - subset useful for RSA encryption. - - // Bits per digit - var dbits; - - // JavaScript engine analysis - var canary = 0xdeadbeefcafe; - var j_lm = (canary & 0xffffff) == 0xefcafe; - - // (public) Constructor - function BigInteger(a, b, c) { - if (a != null) - if ('number' == typeof a) this.fromNumber(a, b, c); - else if (b == null && 'string' != typeof a) this.fromString(a, 256); - else this.fromString(a, b); - } - - // return new, unset BigInteger - function nbi() { - return new BigInteger(null); - } - - // am: Compute w_j += (x*this_i), propagate carries, - // c is initial carry, returns final carry. - // c < 3*dvalue, x < 2*dvalue, this_i < dvalue - // We need to select the fastest one that works in this environment. - - // am1: use a single mult and divide to get the high bits, - // max digit bits should be 26 because - // max internal value = 2*dvalue^2-2*dvalue (< 2^53) - function am1(i, x, w, j, c, n) { - while (--n >= 0) { - var v = x * this[i++] + w[j] + c; - c = Math.floor(v / 0x4000000); - w[j++] = v & 0x3ffffff; - } - return c; - } - // am2 avoids a big mult-and-extract completely. - // Max digit bits should be <= 30 because we do bitwise ops - // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) - function am2(i, x, w, j, c, n) { - var xl = x & 0x7fff, - xh = x >> 15; - while (--n >= 0) { - var l = this[i] & 0x7fff; - var h = this[i++] >> 15; - var m = xh * l + h * xl; - l = xl * l + ((m & 0x7fff) << 15) + w[j] + (c & 0x3fffffff); - c = (l >>> 30) + (m >>> 15) + xh * h + (c >>> 30); - w[j++] = l & 0x3fffffff; - } - return c; - } - // Alternately, set max digit bits to 28 since some - // browsers slow down when dealing with 32-bit numbers. - function am3(i, x, w, j, c, n) { - var xl = x & 0x3fff, - xh = x >> 14; - while (--n >= 0) { - var l = this[i] & 0x3fff; - var h = this[i++] >> 14; - var m = xh * l + h * xl; - l = xl * l + ((m & 0x3fff) << 14) + w[j] + c; - c = (l >> 28) + (m >> 14) + xh * h; - w[j++] = l & 0xfffffff; - } - return c; - } - var inBrowser = typeof navigator !== 'undefined'; - if (inBrowser && j_lm && navigator.appName == 'Microsoft Internet Explorer') { - BigInteger.prototype.am = am2; - dbits = 30; - } else if (inBrowser && j_lm && navigator.appName != 'Netscape') { - BigInteger.prototype.am = am1; - dbits = 26; - } else { - // Mozilla/Netscape seems to prefer am3 - BigInteger.prototype.am = am3; - dbits = 28; - } - - BigInteger.prototype.DB = dbits; - BigInteger.prototype.DM = (1 << dbits) - 1; - BigInteger.prototype.DV = 1 << dbits; - - var BI_FP = 52; - BigInteger.prototype.FV = Math.pow(2, BI_FP); - BigInteger.prototype.F1 = BI_FP - dbits; - BigInteger.prototype.F2 = 2 * dbits - BI_FP; - - // Digit conversions - var BI_RM = '0123456789abcdefghijklmnopqrstuvwxyz'; - var BI_RC = new Array(); - var rr, vv; - rr = '0'.charCodeAt(0); - for (vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv; - rr = 'a'.charCodeAt(0); - for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; - rr = 'A'.charCodeAt(0); - for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; - - function int2char(n) { - return BI_RM.charAt(n); - } - function intAt(s, i) { - var c = BI_RC[s.charCodeAt(i)]; - return c == null ? -1 : c; - } - - // (protected) copy this to r - function bnpCopyTo(r) { - for (var i = this.t - 1; i >= 0; --i) r[i] = this[i]; - r.t = this.t; - r.s = this.s; - } - - // (protected) set from integer value x, -DV <= x < DV - function bnpFromInt(x) { - this.t = 1; - this.s = x < 0 ? -1 : 0; - if (x > 0) this[0] = x; - else if (x < -1) this[0] = x + this.DV; - else this.t = 0; - } - - // return bigint initialized to value - function nbv(i) { - var r = nbi(); - r.fromInt(i); - return r; - } - - // (protected) set from string and radix - function bnpFromString(s, b) { - // Auto-detect string notations - if (!b && s.length >= 2 && s[0] === '0') { - var isDetected = true; - switch (s[1]) { - case 'x': // Hexadecimal notation - b = 16; - break; - case 'b': // Binary notation - b = 2; - break; - case 'o': // Octal notation - b = 8; - break; - default: - isDetected = false; - } - - // Remove the notation string if any has been detected - if (isDetected) { - s = s.substr(2); - } - } - - var k; - if (b == 16) k = 4; - else if (b == 8) k = 3; - else if (b == 256) k = 8; - // byte array - else if (b == 2) k = 1; - else if (b == 32) k = 5; - else if (b == 4) k = 2; - else { - this.fromRadix(s, b); - return; - } - this.t = 0; - this.s = 0; - var i = s.length, - mi = false, - sh = 0; - while (--i >= 0) { - var x = k == 8 ? s[i] & 0xff : intAt(s, i); - if (x < 0) { - if (s.charAt(i) == '-') mi = true; - continue; - } - mi = false; - if (sh == 0) this[this.t++] = x; - else if (sh + k > this.DB) { - this[this.t - 1] |= (x & ((1 << (this.DB - sh)) - 1)) << sh; - this[this.t++] = x >> (this.DB - sh); - } else this[this.t - 1] |= x << sh; - sh += k; - if (sh >= this.DB) sh -= this.DB; - } - if (k == 8 && (s[0] & 0x80) != 0) { - this.s = -1; - if (sh > 0) this[this.t - 1] |= ((1 << (this.DB - sh)) - 1) << sh; - } - this.clamp(); - if (mi) BigInteger.ZERO.subTo(this, this); - } - - // (protected) clamp off excess high words - function bnpClamp() { - var c = this.s & this.DM; - while (this.t > 0 && this[this.t - 1] == c) --this.t; - } - - // (public) return string representation in given radix - function bnToString(b) { - if (this.s < 0) return '-' + this.negate().toString(b); - var k; - if (b == 16) k = 4; - else if (b == 8) k = 3; - else if (b == 2) k = 1; - else if (b == 32) k = 5; - else if (b == 4) k = 2; - else return this.toRadix(b); - var km = (1 << k) - 1, - d, - m = false, - r = '', - i = this.t; - var p = this.DB - ((i * this.DB) % k); - if (i-- > 0) { - if (p < this.DB && (d = this[i] >> p) > 0) { - m = true; - r = int2char(d); - } - while (i >= 0) { - if (p < k) { - d = (this[i] & ((1 << p) - 1)) << (k - p); - d |= this[--i] >> (p += this.DB - k); - } else { - d = (this[i] >> (p -= k)) & km; - if (p <= 0) { - p += this.DB; - --i; - } - } - if (d > 0) m = true; - if (m) r += int2char(d); - } - } - return m ? r : '0'; - } - - // (public) -this - function bnNegate() { - var r = nbi(); - BigInteger.ZERO.subTo(this, r); - return r; - } - - // (public) |this| - function bnAbs() { - return this.s < 0 ? this.negate() : this; - } - - // (public) return + if this > a, - if this < a, 0 if equal - function bnCompareTo(a) { - var r = this.s - a.s; - if (r != 0) return r; - var i = this.t; - r = i - a.t; - if (r != 0) return this.s < 0 ? -r : r; - while (--i >= 0) if ((r = this[i] - a[i]) != 0) return r; - return 0; - } - - // returns bit length of the integer x - function nbits(x) { - var r = 1, - t; - if ((t = x >>> 16) != 0) { - x = t; - r += 16; - } - if ((t = x >> 8) != 0) { - x = t; - r += 8; - } - if ((t = x >> 4) != 0) { - x = t; - r += 4; - } - if ((t = x >> 2) != 0) { - x = t; - r += 2; - } - if ((t = x >> 1) != 0) { - x = t; - r += 1; - } - return r; - } - - // (public) return the number of bits in "this" - function bnBitLength() { - if (this.t <= 0) return 0; - return ( - this.DB * (this.t - 1) + nbits(this[this.t - 1] ^ (this.s & this.DM)) - ); - } - - // (protected) r = this << n*DB - function bnpDLShiftTo(n, r) { - var i; - for (i = this.t - 1; i >= 0; --i) r[i + n] = this[i]; - for (i = n - 1; i >= 0; --i) r[i] = 0; - r.t = this.t + n; - r.s = this.s; - } - - // (protected) r = this >> n*DB - function bnpDRShiftTo(n, r) { - for (var i = n; i < this.t; ++i) r[i - n] = this[i]; - r.t = Math.max(this.t - n, 0); - r.s = this.s; - } - - // (protected) r = this << n - function bnpLShiftTo(n, r) { - var bs = n % this.DB; - var cbs = this.DB - bs; - var bm = (1 << cbs) - 1; - var ds = Math.floor(n / this.DB), - c = (this.s << bs) & this.DM, - i; - for (i = this.t - 1; i >= 0; --i) { - r[i + ds + 1] = (this[i] >> cbs) | c; - c = (this[i] & bm) << bs; - } - for (i = ds - 1; i >= 0; --i) r[i] = 0; - r[ds] = c; - r.t = this.t + ds + 1; - r.s = this.s; - r.clamp(); - } - - // (protected) r = this >> n - function bnpRShiftTo(n, r) { - r.s = this.s; - var ds = Math.floor(n / this.DB); - if (ds >= this.t) { - r.t = 0; - return; - } - var bs = n % this.DB; - var cbs = this.DB - bs; - var bm = (1 << bs) - 1; - r[0] = this[ds] >> bs; - for (var i = ds + 1; i < this.t; ++i) { - r[i - ds - 1] |= (this[i] & bm) << cbs; - r[i - ds] = this[i] >> bs; - } - if (bs > 0) r[this.t - ds - 1] |= (this.s & bm) << cbs; - r.t = this.t - ds; - r.clamp(); - } - - // (protected) r = this - a - function bnpSubTo(a, r) { - var i = 0, - c = 0, - m = Math.min(a.t, this.t); - while (i < m) { - c += this[i] - a[i]; - r[i++] = c & this.DM; - c >>= this.DB; - } - if (a.t < this.t) { - c -= a.s; - while (i < this.t) { - c += this[i]; - r[i++] = c & this.DM; - c >>= this.DB; - } - c += this.s; - } else { - c += this.s; - while (i < a.t) { - c -= a[i]; - r[i++] = c & this.DM; - c >>= this.DB; - } - c -= a.s; - } - r.s = c < 0 ? -1 : 0; - if (c < -1) r[i++] = this.DV + c; - else if (c > 0) r[i++] = c; - r.t = i; - r.clamp(); - } - - // (protected) r = this * a, r != this,a (HAC 14.12) - // "this" should be the larger one if appropriate. - function bnpMultiplyTo(a, r) { - var x = this.abs(), - y = a.abs(); - var i = x.t; - r.t = i + y.t; - while (--i >= 0) r[i] = 0; - for (i = 0; i < y.t; ++i) r[i + x.t] = x.am(0, y[i], r, i, 0, x.t); - r.s = 0; - r.clamp(); - if (this.s != a.s) BigInteger.ZERO.subTo(r, r); - } - - // (protected) r = this^2, r != this (HAC 14.16) - function bnpSquareTo(r) { - var x = this.abs(); - var i = (r.t = 2 * x.t); - while (--i >= 0) r[i] = 0; - for (i = 0; i < x.t - 1; ++i) { - var c = x.am(i, x[i], r, 2 * i, 0, 1); - if ( - (r[i + x.t] += x.am(i + 1, 2 * x[i], r, 2 * i + 1, c, x.t - i - 1)) >= - x.DV - ) { - r[i + x.t] -= x.DV; - r[i + x.t + 1] = 1; - } - } - if (r.t > 0) r[r.t - 1] += x.am(i, x[i], r, 2 * i, 0, 1); - r.s = 0; - r.clamp(); - } - - // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) - // r != q, this != m. q or r may be null. - function bnpDivRemTo(m, q, r) { - var pm = m.abs(); - if (pm.t <= 0) return; - var pt = this.abs(); - if (pt.t < pm.t) { - if (q != null) q.fromInt(0); - if (r != null) this.copyTo(r); - return; - } - if (r == null) r = nbi(); - var y = nbi(), - ts = this.s, - ms = m.s; - var nsh = this.DB - nbits(pm[pm.t - 1]); // normalize modulus - if (nsh > 0) { - pm.lShiftTo(nsh, y); - pt.lShiftTo(nsh, r); - } else { - pm.copyTo(y); - pt.copyTo(r); - } - var ys = y.t; - var y0 = y[ys - 1]; - if (y0 == 0) return; - var yt = y0 * (1 << this.F1) + (ys > 1 ? y[ys - 2] >> this.F2 : 0); - var d1 = this.FV / yt, - d2 = (1 << this.F1) / yt, - e = 1 << this.F2; - var i = r.t, - j = i - ys, - t = q == null ? nbi() : q; - y.dlShiftTo(j, t); - if (r.compareTo(t) >= 0) { - r[r.t++] = 1; - r.subTo(t, r); - } - BigInteger.ONE.dlShiftTo(ys, t); - t.subTo(y, y); // "negative" y so we can replace sub with am later - while (y.t < ys) y[y.t++] = 0; - while (--j >= 0) { - // Estimate quotient digit - var qd = - r[--i] == y0 ? this.DM : Math.floor(r[i] * d1 + (r[i - 1] + e) * d2); - if ((r[i] += y.am(0, qd, r, j, 0, ys)) < qd) { - // Try it out - y.dlShiftTo(j, t); - r.subTo(t, r); - while (r[i] < --qd) r.subTo(t, r); - } - } - if (q != null) { - r.drShiftTo(ys, q); - if (ts != ms) BigInteger.ZERO.subTo(q, q); - } - r.t = ys; - r.clamp(); - if (nsh > 0) r.rShiftTo(nsh, r); // Denormalize remainder - if (ts < 0) BigInteger.ZERO.subTo(r, r); - } - - // (public) this mod a - function bnMod(a) { - var r = nbi(); - this.abs().divRemTo(a, null, r); - if (this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r, r); - return r; - } - - // Modular reduction using "classic" algorithm - function Classic(m) { - this.m = m; - } - function cConvert(x) { - if (x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m); - else return x; - } - function cRevert(x) { - return x; - } - function cReduce(x) { - x.divRemTo(this.m, null, x); - } - function cMulTo(x, y, r) { - x.multiplyTo(y, r); - this.reduce(r); - } - function cSqrTo(x, r) { - x.squareTo(r); - this.reduce(r); - } - - Classic.prototype.convert = cConvert; - Classic.prototype.revert = cRevert; - Classic.prototype.reduce = cReduce; - Classic.prototype.mulTo = cMulTo; - Classic.prototype.sqrTo = cSqrTo; - - // (protected) return "-1/this % 2^DB"; useful for Mont. reduction - // justification: - // xy == 1 (mod m) - // xy = 1+km - // xy(2-xy) = (1+km)(1-km) - // x[y(2-xy)] = 1-k^2m^2 - // x[y(2-xy)] == 1 (mod m^2) - // if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 - // should reduce x and y(2-xy) by m^2 at each step to keep size bounded. - // JS multiply "overflows" differently from C/C++, so care is needed here. - function bnpInvDigit() { - if (this.t < 1) return 0; - var x = this[0]; - if ((x & 1) == 0) return 0; - var y = x & 3; // y == 1/x mod 2^2 - y = (y * (2 - (x & 0xf) * y)) & 0xf; // y == 1/x mod 2^4 - y = (y * (2 - (x & 0xff) * y)) & 0xff; // y == 1/x mod 2^8 - y = (y * (2 - (((x & 0xffff) * y) & 0xffff))) & 0xffff; // y == 1/x mod 2^16 - // last step - calculate inverse mod DV directly; - // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints - y = (y * (2 - ((x * y) % this.DV))) % this.DV; // y == 1/x mod 2^dbits - // we really want the negative inverse, and -DV < y < DV - return y > 0 ? this.DV - y : -y; - } - - // Montgomery reduction - function Montgomery(m) { - this.m = m; - this.mp = m.invDigit(); - this.mpl = this.mp & 0x7fff; - this.mph = this.mp >> 15; - this.um = (1 << (m.DB - 15)) - 1; - this.mt2 = 2 * m.t; - } - - // xR mod m - function montConvert(x) { - var r = nbi(); - x.abs().dlShiftTo(this.m.t, r); - r.divRemTo(this.m, null, r); - if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r, r); - return r; - } - - // x/R mod m - function montRevert(x) { - var r = nbi(); - x.copyTo(r); - this.reduce(r); - return r; - } - - // x = x/R mod m (HAC 14.32) - function montReduce(x) { - while ( - x.t <= this.mt2 // pad x so am has enough room later - ) - x[x.t++] = 0; - for (var i = 0; i < this.m.t; ++i) { - // faster way of calculating u0 = x[i]*mp mod DV - var j = x[i] & 0x7fff; - var u0 = - (j * this.mpl + - (((j * this.mph + (x[i] >> 15) * this.mpl) & this.um) << 15)) & - x.DM; - // use am to combine the multiply-shift-add into one call - j = i + this.m.t; - x[j] += this.m.am(0, u0, x, i, 0, this.m.t); - // propagate carry - while (x[j] >= x.DV) { - x[j] -= x.DV; - x[++j]++; - } - } - x.clamp(); - x.drShiftTo(this.m.t, x); - if (x.compareTo(this.m) >= 0) x.subTo(this.m, x); - } - - // r = "x^2/R mod m"; x != r - function montSqrTo(x, r) { - x.squareTo(r); - this.reduce(r); - } - - // r = "xy/R mod m"; x,y != r - function montMulTo(x, y, r) { - x.multiplyTo(y, r); - this.reduce(r); - } - - Montgomery.prototype.convert = montConvert; - Montgomery.prototype.revert = montRevert; - Montgomery.prototype.reduce = montReduce; - Montgomery.prototype.mulTo = montMulTo; - Montgomery.prototype.sqrTo = montSqrTo; - - // (protected) true iff this is even - function bnpIsEven() { - return (this.t > 0 ? this[0] & 1 : this.s) == 0; - } - - // (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79) - function bnpExp(e, z) { - if (e > 0xffffffff || e < 1) return BigInteger.ONE; - var r = nbi(), - r2 = nbi(), - g = z.convert(this), - i = nbits(e) - 1; - g.copyTo(r); - while (--i >= 0) { - z.sqrTo(r, r2); - if ((e & (1 << i)) > 0) z.mulTo(r2, g, r); - else { - var t = r; - r = r2; - r2 = t; - } - } - return z.revert(r); - } - - // (public) this^e % m, 0 <= e < 2^32 - function bnModPowInt(e, m) { - var z; - if (e < 256 || m.isEven()) z = new Classic(m); - else z = new Montgomery(m); - return this.exp(e, z); - } - - // protected - BigInteger.prototype.copyTo = bnpCopyTo; - BigInteger.prototype.fromInt = bnpFromInt; - BigInteger.prototype.fromString = bnpFromString; - BigInteger.prototype.clamp = bnpClamp; - BigInteger.prototype.dlShiftTo = bnpDLShiftTo; - BigInteger.prototype.drShiftTo = bnpDRShiftTo; - BigInteger.prototype.lShiftTo = bnpLShiftTo; - BigInteger.prototype.rShiftTo = bnpRShiftTo; - BigInteger.prototype.subTo = bnpSubTo; - BigInteger.prototype.multiplyTo = bnpMultiplyTo; - BigInteger.prototype.squareTo = bnpSquareTo; - BigInteger.prototype.divRemTo = bnpDivRemTo; - BigInteger.prototype.invDigit = bnpInvDigit; - BigInteger.prototype.isEven = bnpIsEven; - BigInteger.prototype.exp = bnpExp; - - // public - BigInteger.prototype.toString = bnToString; - BigInteger.prototype.negate = bnNegate; - BigInteger.prototype.abs = bnAbs; - BigInteger.prototype.compareTo = bnCompareTo; - BigInteger.prototype.bitLength = bnBitLength; - BigInteger.prototype.mod = bnMod; - BigInteger.prototype.modPowInt = bnModPowInt; - - // "constants" - BigInteger.ZERO = nbv(0); - BigInteger.ONE = nbv(1); - BigInteger.valueOf = nbv; - - // Copyright (c) 2005-2009 Tom Wu - // All Rights Reserved. - // See "LICENSE" for details. - - // Extended JavaScript BN functions, required for RSA private ops. - - // Version 1.1: new BigInteger("0", 10) returns "proper" zero - // Version 1.2: square() API, isProbablePrime fix - - // (public) - function bnClone() { - var r = nbi(); - this.copyTo(r); - return r; - } - - // (public) return value as integer - function bnIntValue() { - if (this.s < 0) { - if (this.t == 1) return this[0] - this.DV; - else if (this.t == 0) return -1; - } else if (this.t == 1) return this[0]; - else if (this.t == 0) return 0; - // assumes 16 < DB < 32 - return ((this[1] & ((1 << (32 - this.DB)) - 1)) << this.DB) | this[0]; - } - - // (public) return value as byte - function bnByteValue() { - return this.t == 0 ? this.s : (this[0] << 24) >> 24; - } - - // (public) return value as short (assumes DB>=16) - function bnShortValue() { - return this.t == 0 ? this.s : (this[0] << 16) >> 16; - } - - // (protected) return x s.t. r^x < DV - function bnpChunkSize(r) { - return Math.floor((Math.LN2 * this.DB) / Math.log(r)); - } - - // (public) 0 if this == 0, 1 if this > 0 - function bnSigNum() { - if (this.s < 0) return -1; - else if (this.t <= 0 || (this.t == 1 && this[0] <= 0)) return 0; - else return 1; - } - - // (protected) convert to radix string - function bnpToRadix(b) { - if (b == null) b = 10; - if (this.signum() == 0 || b < 2 || b > 36) return '0'; - var cs = this.chunkSize(b); - var a = Math.pow(b, cs); - var d = nbv(a), - y = nbi(), - z = nbi(), - r = ''; - this.divRemTo(d, y, z); - while (y.signum() > 0) { - r = (a + z.intValue()).toString(b).substr(1) + r; - y.divRemTo(d, y, z); - } - return z.intValue().toString(b) + r; - } - - // (protected) convert from radix string - function bnpFromRadix(s, b) { - this.fromInt(0); - if (b == null) b = 10; - var cs = this.chunkSize(b); - var d = Math.pow(b, cs), - mi = false, - j = 0, - w = 0; - for (var i = 0; i < s.length; ++i) { - var x = intAt(s, i); - if (x < 0) { - if (s.charAt(i) == '-' && this.signum() == 0) mi = true; - continue; - } - w = b * w + x; - if (++j >= cs) { - this.dMultiply(d); - this.dAddOffset(w, 0); - j = 0; - w = 0; - } - } - if (j > 0) { - this.dMultiply(Math.pow(b, j)); - this.dAddOffset(w, 0); - } - if (mi) BigInteger.ZERO.subTo(this, this); - } - - // (protected) alternate constructor - function bnpFromNumber(a, b, c) { - if ('number' == typeof b) { - // new BigInteger(int,int,RNG) - if (a < 2) this.fromInt(1); - else { - this.fromNumber(a, c); - if (!this.testBit(a - 1)) - // force MSB set - this.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, this); - if (this.isEven()) this.dAddOffset(1, 0); // force odd - while (!this.isProbablePrime(b)) { - this.dAddOffset(2, 0); - if (this.bitLength() > a) - this.subTo(BigInteger.ONE.shiftLeft(a - 1), this); - } - } - } else { - // new BigInteger(int,RNG) - var x = new Array(), - t = a & 7; - x.length = (a >> 3) + 1; - b.nextBytes(x); - if (t > 0) x[0] &= (1 << t) - 1; - else x[0] = 0; - this.fromString(x, 256); - } - } - - // (public) convert to bigendian byte array - function bnToByteArray() { - var i = this.t, - r = new Array(); - r[0] = this.s; - var p = this.DB - ((i * this.DB) % 8), - d, - k = 0; - if (i-- > 0) { - if (p < this.DB && (d = this[i] >> p) != (this.s & this.DM) >> p) - r[k++] = d | (this.s << (this.DB - p)); - while (i >= 0) { - if (p < 8) { - d = (this[i] & ((1 << p) - 1)) << (8 - p); - d |= this[--i] >> (p += this.DB - 8); - } else { - d = (this[i] >> (p -= 8)) & 0xff; - if (p <= 0) { - p += this.DB; - --i; - } - } - if ((d & 0x80) != 0) d |= -256; - if (k == 0 && (this.s & 0x80) != (d & 0x80)) ++k; - if (k > 0 || d != this.s) r[k++] = d; - } - } - return r; - } - - function bnEquals(a) { - return this.compareTo(a) == 0; - } - function bnMin(a) { - return this.compareTo(a) < 0 ? this : a; - } - function bnMax(a) { - return this.compareTo(a) > 0 ? this : a; - } - - // (protected) r = this op a (bitwise) - function bnpBitwiseTo(a, op, r) { - var i, - f, - m = Math.min(a.t, this.t); - for (i = 0; i < m; ++i) r[i] = op(this[i], a[i]); - if (a.t < this.t) { - f = a.s & this.DM; - for (i = m; i < this.t; ++i) r[i] = op(this[i], f); - r.t = this.t; - } else { - f = this.s & this.DM; - for (i = m; i < a.t; ++i) r[i] = op(f, a[i]); - r.t = a.t; - } - r.s = op(this.s, a.s); - r.clamp(); - } - - // (public) this & a - function op_and(x, y) { - return x & y; - } - function bnAnd(a) { - var r = nbi(); - this.bitwiseTo(a, op_and, r); - return r; - } - - // (public) this | a - function op_or(x, y) { - return x | y; - } - function bnOr(a) { - var r = nbi(); - this.bitwiseTo(a, op_or, r); - return r; - } - - // (public) this ^ a - function op_xor(x, y) { - return x ^ y; - } - function bnXor(a) { - var r = nbi(); - this.bitwiseTo(a, op_xor, r); - return r; - } - - // (public) this & ~a - function op_andnot(x, y) { - return x & ~y; - } - function bnAndNot(a) { - var r = nbi(); - this.bitwiseTo(a, op_andnot, r); - return r; - } - - // (public) ~this - function bnNot() { - var r = nbi(); - for (var i = 0; i < this.t; ++i) r[i] = this.DM & ~this[i]; - r.t = this.t; - r.s = ~this.s; - return r; - } - - // (public) this << n - function bnShiftLeft(n) { - var r = nbi(); - if (n < 0) this.rShiftTo(-n, r); - else this.lShiftTo(n, r); - return r; - } - - // (public) this >> n - function bnShiftRight(n) { - var r = nbi(); - if (n < 0) this.lShiftTo(-n, r); - else this.rShiftTo(n, r); - return r; - } - - // return index of lowest 1-bit in x, x < 2^31 - function lbit(x) { - if (x == 0) return -1; - var r = 0; - if ((x & 0xffff) == 0) { - x >>= 16; - r += 16; - } - if ((x & 0xff) == 0) { - x >>= 8; - r += 8; - } - if ((x & 0xf) == 0) { - x >>= 4; - r += 4; - } - if ((x & 3) == 0) { - x >>= 2; - r += 2; - } - if ((x & 1) == 0) ++r; - return r; - } - - // (public) returns index of lowest 1-bit (or -1 if none) - function bnGetLowestSetBit() { - for (var i = 0; i < this.t; ++i) - if (this[i] != 0) return i * this.DB + lbit(this[i]); - if (this.s < 0) return this.t * this.DB; - return -1; - } - - // return number of 1 bits in x - function cbit(x) { - var r = 0; - while (x != 0) { - x &= x - 1; - ++r; - } - return r; - } - - // (public) return number of set bits - function bnBitCount() { - var r = 0, - x = this.s & this.DM; - for (var i = 0; i < this.t; ++i) r += cbit(this[i] ^ x); - return r; - } - - // (public) true iff nth bit is set - function bnTestBit(n) { - var j = Math.floor(n / this.DB); - if (j >= this.t) return this.s != 0; - return (this[j] & (1 << n % this.DB)) != 0; - } - - // (protected) this op (1<>= this.DB; - } - if (a.t < this.t) { - c += a.s; - while (i < this.t) { - c += this[i]; - r[i++] = c & this.DM; - c >>= this.DB; - } - c += this.s; - } else { - c += this.s; - while (i < a.t) { - c += a[i]; - r[i++] = c & this.DM; - c >>= this.DB; - } - c += a.s; - } - r.s = c < 0 ? -1 : 0; - if (c > 0) r[i++] = c; - else if (c < -1) r[i++] = this.DV + c; - r.t = i; - r.clamp(); - } - - // (public) this + a - function bnAdd(a) { - var r = nbi(); - this.addTo(a, r); - return r; - } - - // (public) this - a - function bnSubtract(a) { - var r = nbi(); - this.subTo(a, r); - return r; - } - - // (public) this * a - function bnMultiply(a) { - var r = nbi(); - this.multiplyTo(a, r); - return r; - } - - // (public) this^2 - function bnSquare() { - var r = nbi(); - this.squareTo(r); - return r; - } - - // (public) this / a - function bnDivide(a) { - var r = nbi(); - this.divRemTo(a, r, null); - return r; - } - - // (public) this % a - function bnRemainder(a) { - var r = nbi(); - this.divRemTo(a, null, r); - return r; - } - - // (public) [this/a,this%a] - function bnDivideAndRemainder(a) { - var q = nbi(), - r = nbi(); - this.divRemTo(a, q, r); - return new Array(q, r); - } - - // (protected) this *= n, this >= 0, 1 < n < DV - function bnpDMultiply(n) { - this[this.t] = this.am(0, n - 1, this, 0, 0, this.t); - ++this.t; - this.clamp(); - } - - // (protected) this += n << w words, this >= 0 - function bnpDAddOffset(n, w) { - if (n == 0) return; - while (this.t <= w) this[this.t++] = 0; - this[w] += n; - while (this[w] >= this.DV) { - this[w] -= this.DV; - if (++w >= this.t) this[this.t++] = 0; - ++this[w]; - } - } - - // A "null" reducer - function NullExp() { } - function nNop(x) { - return x; - } - function nMulTo(x, y, r) { - x.multiplyTo(y, r); - } - function nSqrTo(x, r) { - x.squareTo(r); - } - - NullExp.prototype.convert = nNop; - NullExp.prototype.revert = nNop; - NullExp.prototype.mulTo = nMulTo; - NullExp.prototype.sqrTo = nSqrTo; - - // (public) this^e - function bnPow(e) { - return this.exp(e, new NullExp()); - } - - // (protected) r = lower n words of "this * a", a.t <= n - // "this" should be the larger one if appropriate. - function bnpMultiplyLowerTo(a, n, r) { - var i = Math.min(this.t + a.t, n); - r.s = 0; // assumes a,this >= 0 - r.t = i; - while (i > 0) r[--i] = 0; - var j; - for (j = r.t - this.t; i < j; ++i) - r[i + this.t] = this.am(0, a[i], r, i, 0, this.t); - for (j = Math.min(a.t, n); i < j; ++i) this.am(0, a[i], r, i, 0, n - i); - r.clamp(); - } - - // (protected) r = "this * a" without lower n words, n > 0 - // "this" should be the larger one if appropriate. - function bnpMultiplyUpperTo(a, n, r) { - --n; - var i = (r.t = this.t + a.t - n); - r.s = 0; // assumes a,this >= 0 - while (--i >= 0) r[i] = 0; - for (i = Math.max(n - this.t, 0); i < a.t; ++i) - r[this.t + i - n] = this.am(n - i, a[i], r, 0, 0, this.t + i - n); - r.clamp(); - r.drShiftTo(1, r); - } - - // Barrett modular reduction - function Barrett(m) { - // setup Barrett - this.r2 = nbi(); - this.q3 = nbi(); - BigInteger.ONE.dlShiftTo(2 * m.t, this.r2); - this.mu = this.r2.divide(m); - this.m = m; - } - - function barrettConvert(x) { - if (x.s < 0 || x.t > 2 * this.m.t) return x.mod(this.m); - else if (x.compareTo(this.m) < 0) return x; - else { - var r = nbi(); - x.copyTo(r); - this.reduce(r); - return r; - } - } - - function barrettRevert(x) { - return x; - } - - // x = x mod m (HAC 14.42) - function barrettReduce(x) { - x.drShiftTo(this.m.t - 1, this.r2); - if (x.t > this.m.t + 1) { - x.t = this.m.t + 1; - x.clamp(); - } - this.mu.multiplyUpperTo(this.r2, this.m.t + 1, this.q3); - this.m.multiplyLowerTo(this.q3, this.m.t + 1, this.r2); - while (x.compareTo(this.r2) < 0) x.dAddOffset(1, this.m.t + 1); - x.subTo(this.r2, x); - while (x.compareTo(this.m) >= 0) x.subTo(this.m, x); - } - - // r = x^2 mod m; x != r - function barrettSqrTo(x, r) { - x.squareTo(r); - this.reduce(r); - } - - // r = x*y mod m; x,y != r - function barrettMulTo(x, y, r) { - x.multiplyTo(y, r); - this.reduce(r); - } - - Barrett.prototype.convert = barrettConvert; - Barrett.prototype.revert = barrettRevert; - Barrett.prototype.reduce = barrettReduce; - Barrett.prototype.mulTo = barrettMulTo; - Barrett.prototype.sqrTo = barrettSqrTo; - - // (public) this^e % m (HAC 14.85) - function bnModPow(e, m) { - var i = e.bitLength(), - k, - r = nbv(1), - z; - if (i <= 0) return r; - else if (i < 18) k = 1; - else if (i < 48) k = 3; - else if (i < 144) k = 4; - else if (i < 768) k = 5; - else k = 6; - if (i < 8) z = new Classic(m); - else if (m.isEven()) z = new Barrett(m); - else z = new Montgomery(m); - - // precomputation - var g = new Array(), - n = 3, - k1 = k - 1, - km = (1 << k) - 1; - g[1] = z.convert(this); - if (k > 1) { - var g2 = nbi(); - z.sqrTo(g[1], g2); - while (n <= km) { - g[n] = nbi(); - z.mulTo(g2, g[n - 2], g[n]); - n += 2; - } - } - - var j = e.t - 1, - w, - is1 = true, - r2 = nbi(), - t; - i = nbits(e[j]) - 1; - while (j >= 0) { - if (i >= k1) w = (e[j] >> (i - k1)) & km; - else { - w = (e[j] & ((1 << (i + 1)) - 1)) << (k1 - i); - if (j > 0) w |= e[j - 1] >> (this.DB + i - k1); - } - - n = k; - while ((w & 1) == 0) { - w >>= 1; - --n; - } - if ((i -= n) < 0) { - i += this.DB; - --j; - } - if (is1) { - // ret == 1, don't bother squaring or multiplying it - g[w].copyTo(r); - is1 = false; - } else { - while (n > 1) { - z.sqrTo(r, r2); - z.sqrTo(r2, r); - n -= 2; - } - if (n > 0) z.sqrTo(r, r2); - else { - t = r; - r = r2; - r2 = t; - } - z.mulTo(r2, g[w], r); - } - - while (j >= 0 && (e[j] & (1 << i)) == 0) { - z.sqrTo(r, r2); - t = r; - r = r2; - r2 = t; - if (--i < 0) { - i = this.DB - 1; - --j; - } - } - } - return z.revert(r); - } - - // (public) gcd(this,a) (HAC 14.54) - function bnGCD(a) { - var x = this.s < 0 ? this.negate() : this.clone(); - var y = a.s < 0 ? a.negate() : a.clone(); - if (x.compareTo(y) < 0) { - var t = x; - x = y; - y = t; - } - var i = x.getLowestSetBit(), - g = y.getLowestSetBit(); - if (g < 0) return x; - if (i < g) g = i; - if (g > 0) { - x.rShiftTo(g, x); - y.rShiftTo(g, y); - } - while (x.signum() > 0) { - if ((i = x.getLowestSetBit()) > 0) x.rShiftTo(i, x); - if ((i = y.getLowestSetBit()) > 0) y.rShiftTo(i, y); - if (x.compareTo(y) >= 0) { - x.subTo(y, x); - x.rShiftTo(1, x); - } else { - y.subTo(x, y); - y.rShiftTo(1, y); - } - } - if (g > 0) y.lShiftTo(g, y); - return y; - } - - // (protected) this % n, n < 2^26 - function bnpModInt(n) { - if (n <= 0) return 0; - var d = this.DV % n, - r = this.s < 0 ? n - 1 : 0; - if (this.t > 0) - if (d == 0) r = this[0] % n; - else for (var i = this.t - 1; i >= 0; --i) r = (d * r + this[i]) % n; - return r; - } - - // (public) 1/this % m (HAC 14.61) - function bnModInverse(m) { - var ac = m.isEven(); - if ((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO; - var u = m.clone(), - v = this.clone(); - var a = nbv(1), - b = nbv(0), - c = nbv(0), - d = nbv(1); - while (u.signum() != 0) { - while (u.isEven()) { - u.rShiftTo(1, u); - if (ac) { - if (!a.isEven() || !b.isEven()) { - a.addTo(this, a); - b.subTo(m, b); - } - a.rShiftTo(1, a); - } else if (!b.isEven()) b.subTo(m, b); - b.rShiftTo(1, b); - } - while (v.isEven()) { - v.rShiftTo(1, v); - if (ac) { - if (!c.isEven() || !d.isEven()) { - c.addTo(this, c); - d.subTo(m, d); - } - c.rShiftTo(1, c); - } else if (!d.isEven()) d.subTo(m, d); - d.rShiftTo(1, d); - } - if (u.compareTo(v) >= 0) { - u.subTo(v, u); - if (ac) a.subTo(c, a); - b.subTo(d, b); - } else { - v.subTo(u, v); - if (ac) c.subTo(a, c); - d.subTo(b, d); - } - } - if (v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO; - if (d.compareTo(m) >= 0) return d.subtract(m); - if (d.signum() < 0) d.addTo(m, d); - else return d; - if (d.signum() < 0) return d.add(m); - else return d; - } - - var lowprimes = [ - 2, - 3, - 5, - 7, - 11, - 13, - 17, - 19, - 23, - 29, - 31, - 37, - 41, - 43, - 47, - 53, - 59, - 61, - 67, - 71, - 73, - 79, - 83, - 89, - 97, - 101, - 103, - 107, - 109, - 113, - 127, - 131, - 137, - 139, - 149, - 151, - 157, - 163, - 167, - 173, - 179, - 181, - 191, - 193, - 197, - 199, - 211, - 223, - 227, - 229, - 233, - 239, - 241, - 251, - 257, - 263, - 269, - 271, - 277, - 281, - 283, - 293, - 307, - 311, - 313, - 317, - 331, - 337, - 347, - 349, - 353, - 359, - 367, - 373, - 379, - 383, - 389, - 397, - 401, - 409, - 419, - 421, - 431, - 433, - 439, - 443, - 449, - 457, - 461, - 463, - 467, - 479, - 487, - 491, - 499, - 503, - 509, - 521, - 523, - 541, - 547, - 557, - 563, - 569, - 571, - 577, - 587, - 593, - 599, - 601, - 607, - 613, - 617, - 619, - 631, - 641, - 643, - 647, - 653, - 659, - 661, - 673, - 677, - 683, - 691, - 701, - 709, - 719, - 727, - 733, - 739, - 743, - 751, - 757, - 761, - 769, - 773, - 787, - 797, - 809, - 811, - 821, - 823, - 827, - 829, - 839, - 853, - 857, - 859, - 863, - 877, - 881, - 883, - 887, - 907, - 911, - 919, - 929, - 937, - 941, - 947, - 953, - 967, - 971, - 977, - 983, - 991, - 997, - ]; - var lplim = (1 << 26) / lowprimes[lowprimes.length - 1]; - - // (public) test primality with certainty >= 1-.5^t - function bnIsProbablePrime(t) { - var i, - x = this.abs(); - if (x.t == 1 && x[0] <= lowprimes[lowprimes.length - 1]) { - for (i = 0; i < lowprimes.length; ++i) - if (x[0] == lowprimes[i]) return true; - return false; - } - if (x.isEven()) return false; - i = 1; - while (i < lowprimes.length) { - var m = lowprimes[i], - j = i + 1; - while (j < lowprimes.length && m < lplim) m *= lowprimes[j++]; - m = x.modInt(m); - while (i < j) if (m % lowprimes[i++] == 0) return false; - } - return x.millerRabin(t); - } - - // (protected) true if probably prime (HAC 4.24, Miller-Rabin) - function bnpMillerRabin(t) { - var n1 = this.subtract(BigInteger.ONE); - var k = n1.getLowestSetBit(); - if (k <= 0) return false; - var r = n1.shiftRight(k); - t = (t + 1) >> 1; - if (t > lowprimes.length) t = lowprimes.length; - var a = nbi(); - for (var i = 0; i < t; ++i) { - //Pick bases at random, instead of starting at 2 - a.fromInt(lowprimes[Math.floor(Math.random() * lowprimes.length)]); - var y = a.modPow(r, this); - if (y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { - var j = 1; - while (j++ < k && y.compareTo(n1) != 0) { - y = y.modPowInt(2, this); - if (y.compareTo(BigInteger.ONE) == 0) return false; - } - if (y.compareTo(n1) != 0) return false; - } - } - return true; - } - - // protected - BigInteger.prototype.chunkSize = bnpChunkSize; - BigInteger.prototype.toRadix = bnpToRadix; - BigInteger.prototype.fromRadix = bnpFromRadix; - BigInteger.prototype.fromNumber = bnpFromNumber; - BigInteger.prototype.bitwiseTo = bnpBitwiseTo; - BigInteger.prototype.changeBit = bnpChangeBit; - BigInteger.prototype.addTo = bnpAddTo; - BigInteger.prototype.dMultiply = bnpDMultiply; - BigInteger.prototype.dAddOffset = bnpDAddOffset; - BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo; - BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo; - BigInteger.prototype.modInt = bnpModInt; - BigInteger.prototype.millerRabin = bnpMillerRabin; - - // public - BigInteger.prototype.clone = bnClone; - BigInteger.prototype.intValue = bnIntValue; - BigInteger.prototype.byteValue = bnByteValue; - BigInteger.prototype.shortValue = bnShortValue; - BigInteger.prototype.signum = bnSigNum; - BigInteger.prototype.toByteArray = bnToByteArray; - BigInteger.prototype.equals = bnEquals; - BigInteger.prototype.min = bnMin; - BigInteger.prototype.max = bnMax; - BigInteger.prototype.and = bnAnd; - BigInteger.prototype.or = bnOr; - BigInteger.prototype.xor = bnXor; - BigInteger.prototype.andNot = bnAndNot; - BigInteger.prototype.not = bnNot; - BigInteger.prototype.shiftLeft = bnShiftLeft; - BigInteger.prototype.shiftRight = bnShiftRight; - BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit; - BigInteger.prototype.bitCount = bnBitCount; - BigInteger.prototype.testBit = bnTestBit; - BigInteger.prototype.setBit = bnSetBit; - BigInteger.prototype.clearBit = bnClearBit; - BigInteger.prototype.flipBit = bnFlipBit; - BigInteger.prototype.add = bnAdd; - BigInteger.prototype.subtract = bnSubtract; - BigInteger.prototype.multiply = bnMultiply; - BigInteger.prototype.divide = bnDivide; - BigInteger.prototype.remainder = bnRemainder; - BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder; - BigInteger.prototype.modPow = bnModPow; - BigInteger.prototype.modInverse = bnModInverse; - BigInteger.prototype.pow = bnPow; - BigInteger.prototype.gcd = bnGCD; - BigInteger.prototype.isProbablePrime = bnIsProbablePrime; - - // JSBN-specific extension - BigInteger.prototype.square = bnSquare; - - // Expose the Barrett function - BigInteger.prototype.Barrett = Barrett; - - // BigInteger interfaces not implemented in jsbn: - - // BigInteger(int signum, byte[] magnitude) - // double doubleValue() - // float floatValue() - // int hashCode() - // long longValue() - // static BigInteger valueOf(long val) - - // Imported from bitcoinjs-lib - - /** - * Turns a byte array into a big integer. - * - * This function will interpret a byte array as a big integer in big - * endian notation and ignore leading zeros. - */ - - BigInteger.fromByteArrayUnsigned = function (ba) { - - if (!ba.length) { - return new BigInteger.valueOf(0); - } else if (ba[0] & 0x80) { - // Prepend a zero so the BigInteger class doesn't mistake this - // for a negative integer. - return new BigInteger([0].concat(ba)); - } else { - return new BigInteger(ba); - } - }; - - /** - * Parse a signed big integer byte representation. - * - * For details on the format please see BigInteger.toByteArraySigned. - */ - - BigInteger.fromByteArraySigned = function (ba) { - // Check for negative value - if (ba[0] & 0x80) { - // Remove sign bit - ba[0] &= 0x7f; - - return BigInteger.fromByteArrayUnsigned(ba).negate(); - } else { - return BigInteger.fromByteArrayUnsigned(ba); - } - }; - - /** - * Returns a byte array representation of the big integer. - * - * This returns the absolute of the contained value in big endian - * form. A value of zero results in an empty array. - */ - - BigInteger.prototype.toByteArrayUnsigned = function () { - var ba = this.abs().toByteArray(); - - // Empty array, nothing to do - if (!ba.length) { - return ba; - } - - // remove leading 0 - if (ba[0] === 0) { - ba = ba.slice(1); - } - - // all values must be positive - for (var i = 0; i < ba.length; ++i) { - ba[i] = (ba[i] < 0) ? ba[i] + 256 : ba[i]; - } - - return ba; - }; - - /* - * Converts big integer to signed byte representation. - * - * The format for this value uses the most significant bit as a sign - * bit. If the most significant bit is already occupied by the - * absolute value, an extra byte is prepended and the sign bit is set - * there. - * - * Examples: - * - * 0 => 0x00 - * 1 => 0x01 - * -1 => 0x81 - * 127 => 0x7f - * -127 => 0xff - * 128 => 0x0080 - * -128 => 0x8080 - * 255 => 0x00ff - * -255 => 0x80ff - * 16300 => 0x3fac - * -16300 => 0xbfac - * 62300 => 0x00f35c - * -62300 => 0x80f35c - */ - - BigInteger.prototype.toByteArraySigned = function () { - var val = this.toByteArrayUnsigned(); - var neg = this.s < 0; - - // if the first bit is set, we always unshift - // either unshift 0x80 or 0x00 - if (val[0] & 0x80) { - val.unshift((neg) ? 0x80 : 0x00); - } - // if the first bit isn't set, set it if negative - else if (neg) { - val[0] |= 0x80; - } - - return val; - }; - - // Random number generator - requires a PRNG backend, e.g. prng4.js - - // For best results, put code like - // - // in your main HTML document. - - var rng_state; - var rng_pool; - var rng_pptr; - - // Mix in a 32-bit integer into the pool - function rng_seed_int(x) { - rng_pool[rng_pptr++] ^= x & 255; - rng_pool[rng_pptr++] ^= (x >> 8) & 255; - rng_pool[rng_pptr++] ^= (x >> 16) & 255; - rng_pool[rng_pptr++] ^= (x >> 24) & 255; - if (rng_pptr >= rng_psize) rng_pptr -= rng_psize; - } - - // Mix in the current time (w/milliseconds) into the pool - function rng_seed_time() { - rng_seed_int(new Date().getTime()); - } - - // Initialize the pool with junk if needed. - if (rng_pool == null) { - rng_pool = new Array(); - rng_pptr = 0; - var t; - if (typeof window !== 'undefined' && window.crypto) { - if (window.crypto.getRandomValues) { - // Use webcrypto if available - var ua = new Uint8Array(32); - window.crypto.getRandomValues(ua); - for (t = 0; t < 32; ++t) rng_pool[rng_pptr++] = ua[t]; - } else if ( - navigator.appName == 'Netscape' && - navigator.appVersion < '5' - ) { - // Extract entropy (256 bits) from NS4 RNG if available - var z = window.crypto.random(32); - for (t = 0; t < z.length; ++t) - rng_pool[rng_pptr++] = z.charCodeAt(t) & 255; - } - } - while (rng_pptr < rng_psize) { - // extract some randomness from Math.random() - t = Math.floor(65536 * Math.random()); - rng_pool[rng_pptr++] = t >>> 8; - rng_pool[rng_pptr++] = t & 255; - } - rng_pptr = 0; - rng_seed_time(); - //rng_seed_int(window.screenX); - //rng_seed_int(window.screenY); - } - - function rng_get_byte() { - if (rng_state == null) { - rng_seed_time(); - rng_state = prng_newstate(); - rng_state.init(rng_pool); - for (rng_pptr = 0; rng_pptr < rng_pool.length; ++rng_pptr) - rng_pool[rng_pptr] = 0; - rng_pptr = 0; - //rng_pool = null; - } - // TODO: allow reseeding after first request - return rng_state.next(); - } - - function rng_get_bytes(ba) { - var i; - for (i = 0; i < ba.length; ++i) ba[i] = rng_get_byte(); - } - - function SecureRandom() { } - - SecureRandom.prototype.nextBytes = rng_get_bytes; - - // prng4.js - uses Arcfour as a PRNG - - function Arcfour() { - this.i = 0; - this.j = 0; - this.S = new Array(); - } - - // Initialize arcfour context from key, an array of ints, each from [0..255] - function ARC4init(key) { - var i, j, t; - for (i = 0; i < 256; ++i) this.S[i] = i; - j = 0; - for (i = 0; i < 256; ++i) { - j = (j + this.S[i] + key[i % key.length]) & 255; - t = this.S[i]; - this.S[i] = this.S[j]; - this.S[j] = t; - } - this.i = 0; - this.j = 0; - } - - function ARC4next() { - var t; - this.i = (this.i + 1) & 255; - this.j = (this.j + this.S[this.i]) & 255; - t = this.S[this.i]; - this.S[this.i] = this.S[this.j]; - this.S[this.j] = t; - return this.S[(t + this.S[this.i]) & 255]; - } - - Arcfour.prototype.init = ARC4init; - Arcfour.prototype.next = ARC4next; - - // Plug in your RNG constructor here - function prng_newstate() { - return new Arcfour(); - } - - // Pool size must be a multiple of 4 and greater than 32. - // An array of bytes the size of the pool will be passed to init() - var rng_psize = 256; - - - - - /*! - * Basic Javascript Elliptic Curve implementation - * Ported loosely from BouncyCastle's Java EC code - * Only Fp curves implemented for now - * - * Copyright Tom Wu, bitaddress.org BSD License. - * http://www-cs-students.stanford.edu/~tjw/jsbn/LICENSE - */ - - // Constructor function of Global EllipticCurve object - var ec = function () { }; - - - // ---------------- - // ECFieldElementFp constructor - // q instanceof BigInteger - // x instanceof BigInteger - ec.FieldElementFp = function (q, x) { - this.x = x; - // TODO if(x.compareTo(q) >= 0) error - this.q = q; - }; - - ec.FieldElementFp.prototype.equals = function (other) { - if (other == this) return true; - return (this.q.equals(other.q) && this.x.equals(other.x)); - }; - - ec.FieldElementFp.prototype.toBigInteger = function () { - return this.x; - }; - - ec.FieldElementFp.prototype.negate = function () { - return new ec.FieldElementFp(this.q, this.x.negate().mod(this.q)); - }; - - ec.FieldElementFp.prototype.add = function (b) { - return new ec.FieldElementFp(this.q, this.x.add(b.toBigInteger()).mod(this.q)); - }; - - ec.FieldElementFp.prototype.subtract = function (b) { - return new ec.FieldElementFp(this.q, this.x.subtract(b.toBigInteger()).mod(this.q)); - }; - - ec.FieldElementFp.prototype.multiply = function (b) { - return new ec.FieldElementFp(this.q, this.x.multiply(b.toBigInteger()).mod(this.q)); - }; - - ec.FieldElementFp.prototype.square = function () { - return new ec.FieldElementFp(this.q, this.x.square().mod(this.q)); - }; - - ec.FieldElementFp.prototype.divide = function (b) { - return new ec.FieldElementFp(this.q, this.x.multiply(b.toBigInteger().modInverse(this.q)).mod(this.q)); - }; - - ec.FieldElementFp.prototype.getByteLength = function () { - return Math.floor((this.toBigInteger().bitLength() + 7) / 8); - }; - - // D.1.4 91 + // Copyright (c) 2005 Tom Wu + // All Rights Reserved. + // See "LICENSE" for details. + + // Basic JavaScript BN library - subset useful for RSA encryption. + + // Bits per digit + var dbits; + + // JavaScript engine analysis + var canary = 0xdeadbeefcafe; + var j_lm = (canary & 0xffffff) == 0xefcafe; + + // (public) Constructor + function BigInteger(a, b, c) { + if (a != null) + if ('number' == typeof a) this.fromNumber(a, b, c); + else if (b == null && 'string' != typeof a) this.fromString(a, 256); + else this.fromString(a, b); + } + + // return new, unset BigInteger + function nbi() { + return new BigInteger(null); + } + + // am: Compute w_j += (x*this_i), propagate carries, + // c is initial carry, returns final carry. + // c < 3*dvalue, x < 2*dvalue, this_i < dvalue + // We need to select the fastest one that works in this environment. + + // am1: use a single mult and divide to get the high bits, + // max digit bits should be 26 because + // max internal value = 2*dvalue^2-2*dvalue (< 2^53) + function am1(i, x, w, j, c, n) { + while (--n >= 0) { + var v = x * this[i++] + w[j] + c; + c = Math.floor(v / 0x4000000); + w[j++] = v & 0x3ffffff; + } + return c; + } + // am2 avoids a big mult-and-extract completely. + // Max digit bits should be <= 30 because we do bitwise ops + // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) + function am2(i, x, w, j, c, n) { + var xl = x & 0x7fff, + xh = x >> 15; + while (--n >= 0) { + var l = this[i] & 0x7fff; + var h = this[i++] >> 15; + var m = xh * l + h * xl; + l = xl * l + ((m & 0x7fff) << 15) + w[j] + (c & 0x3fffffff); + c = (l >>> 30) + (m >>> 15) + xh * h + (c >>> 30); + w[j++] = l & 0x3fffffff; + } + return c; + } + // Alternately, set max digit bits to 28 since some + // browsers slow down when dealing with 32-bit numbers. + function am3(i, x, w, j, c, n) { + var xl = x & 0x3fff, + xh = x >> 14; + while (--n >= 0) { + var l = this[i] & 0x3fff; + var h = this[i++] >> 14; + var m = xh * l + h * xl; + l = xl * l + ((m & 0x3fff) << 14) + w[j] + c; + c = (l >> 28) + (m >> 14) + xh * h; + w[j++] = l & 0xfffffff; + } + return c; + } + var inBrowser = typeof navigator !== 'undefined'; + if (inBrowser && j_lm && navigator.appName == 'Microsoft Internet Explorer') { + BigInteger.prototype.am = am2; + dbits = 30; + } else if (inBrowser && j_lm && navigator.appName != 'Netscape') { + BigInteger.prototype.am = am1; + dbits = 26; + } else { + // Mozilla/Netscape seems to prefer am3 + BigInteger.prototype.am = am3; + dbits = 28; + } + + BigInteger.prototype.DB = dbits; + BigInteger.prototype.DM = (1 << dbits) - 1; + BigInteger.prototype.DV = 1 << dbits; + + var BI_FP = 52; + BigInteger.prototype.FV = Math.pow(2, BI_FP); + BigInteger.prototype.F1 = BI_FP - dbits; + BigInteger.prototype.F2 = 2 * dbits - BI_FP; + + // Digit conversions + var BI_RM = '0123456789abcdefghijklmnopqrstuvwxyz'; + var BI_RC = new Array(); + var rr, vv; + rr = '0'.charCodeAt(0); + for (vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv; + rr = 'a'.charCodeAt(0); + for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; + rr = 'A'.charCodeAt(0); + for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; + + function int2char(n) { + return BI_RM.charAt(n); + } + function intAt(s, i) { + var c = BI_RC[s.charCodeAt(i)]; + return c == null ? -1 : c; + } + + // (protected) copy this to r + function bnpCopyTo(r) { + for (var i = this.t - 1; i >= 0; --i) r[i] = this[i]; + r.t = this.t; + r.s = this.s; + } + + // (protected) set from integer value x, -DV <= x < DV + function bnpFromInt(x) { + this.t = 1; + this.s = x < 0 ? -1 : 0; + if (x > 0) this[0] = x; + else if (x < -1) this[0] = x + this.DV; + else this.t = 0; + } + + // return bigint initialized to value + function nbv(i) { + var r = nbi(); + r.fromInt(i); + return r; + } + + // (protected) set from string and radix + function bnpFromString(s, b) { + // Auto-detect string notations + if (!b && s.length >= 2 && s[0] === '0') { + var isDetected = true; + switch (s[1]) { + case 'x': // Hexadecimal notation + b = 16; + break; + case 'b': // Binary notation + b = 2; + break; + case 'o': // Octal notation + b = 8; + break; + default: + isDetected = false; + } + + // Remove the notation string if any has been detected + if (isDetected) { + s = s.substr(2); + } + } + + var k; + if (b == 16) k = 4; + else if (b == 8) k = 3; + else if (b == 256) k = 8; + // byte array + else if (b == 2) k = 1; + else if (b == 32) k = 5; + else if (b == 4) k = 2; + else { + this.fromRadix(s, b); + return; + } + this.t = 0; + this.s = 0; + var i = s.length, + mi = false, + sh = 0; + while (--i >= 0) { + var x = k == 8 ? s[i] & 0xff : intAt(s, i); + if (x < 0) { + if (s.charAt(i) == '-') mi = true; + continue; + } + mi = false; + if (sh == 0) this[this.t++] = x; + else if (sh + k > this.DB) { + this[this.t - 1] |= (x & ((1 << (this.DB - sh)) - 1)) << sh; + this[this.t++] = x >> (this.DB - sh); + } else this[this.t - 1] |= x << sh; + sh += k; + if (sh >= this.DB) sh -= this.DB; + } + if (k == 8 && (s[0] & 0x80) != 0) { + this.s = -1; + if (sh > 0) this[this.t - 1] |= ((1 << (this.DB - sh)) - 1) << sh; + } + this.clamp(); + if (mi) BigInteger.ZERO.subTo(this, this); + } + + // (protected) clamp off excess high words + function bnpClamp() { + var c = this.s & this.DM; + while (this.t > 0 && this[this.t - 1] == c) --this.t; + } + + // (public) return string representation in given radix + function bnToString(b) { + if (this.s < 0) return '-' + this.negate().toString(b); + var k; + if (b == 16) k = 4; + else if (b == 8) k = 3; + else if (b == 2) k = 1; + else if (b == 32) k = 5; + else if (b == 4) k = 2; + else return this.toRadix(b); + var km = (1 << k) - 1, + d, + m = false, + r = '', + i = this.t; + var p = this.DB - ((i * this.DB) % k); + if (i-- > 0) { + if (p < this.DB && (d = this[i] >> p) > 0) { + m = true; + r = int2char(d); + } + while (i >= 0) { + if (p < k) { + d = (this[i] & ((1 << p) - 1)) << (k - p); + d |= this[--i] >> (p += this.DB - k); + } else { + d = (this[i] >> (p -= k)) & km; + if (p <= 0) { + p += this.DB; + --i; + } + } + if (d > 0) m = true; + if (m) r += int2char(d); + } + } + return m ? r : '0'; + } + + // (public) -this + function bnNegate() { + var r = nbi(); + BigInteger.ZERO.subTo(this, r); + return r; + } + + // (public) |this| + function bnAbs() { + return this.s < 0 ? this.negate() : this; + } + + // (public) return + if this > a, - if this < a, 0 if equal + function bnCompareTo(a) { + var r = this.s - a.s; + if (r != 0) return r; + var i = this.t; + r = i - a.t; + if (r != 0) return this.s < 0 ? -r : r; + while (--i >= 0) if ((r = this[i] - a[i]) != 0) return r; + return 0; + } + + // returns bit length of the integer x + function nbits(x) { + var r = 1, + t; + if ((t = x >>> 16) != 0) { + x = t; + r += 16; + } + if ((t = x >> 8) != 0) { + x = t; + r += 8; + } + if ((t = x >> 4) != 0) { + x = t; + r += 4; + } + if ((t = x >> 2) != 0) { + x = t; + r += 2; + } + if ((t = x >> 1) != 0) { + x = t; + r += 1; + } + return r; + } + + // (public) return the number of bits in "this" + function bnBitLength() { + if (this.t <= 0) return 0; + return ( + this.DB * (this.t - 1) + nbits(this[this.t - 1] ^ (this.s & this.DM)) + ); + } + + // (protected) r = this << n*DB + function bnpDLShiftTo(n, r) { + var i; + for (i = this.t - 1; i >= 0; --i) r[i + n] = this[i]; + for (i = n - 1; i >= 0; --i) r[i] = 0; + r.t = this.t + n; + r.s = this.s; + } + + // (protected) r = this >> n*DB + function bnpDRShiftTo(n, r) { + for (var i = n; i < this.t; ++i) r[i - n] = this[i]; + r.t = Math.max(this.t - n, 0); + r.s = this.s; + } + + // (protected) r = this << n + function bnpLShiftTo(n, r) { + var bs = n % this.DB; + var cbs = this.DB - bs; + var bm = (1 << cbs) - 1; + var ds = Math.floor(n / this.DB), + c = (this.s << bs) & this.DM, + i; + for (i = this.t - 1; i >= 0; --i) { + r[i + ds + 1] = (this[i] >> cbs) | c; + c = (this[i] & bm) << bs; + } + for (i = ds - 1; i >= 0; --i) r[i] = 0; + r[ds] = c; + r.t = this.t + ds + 1; + r.s = this.s; + r.clamp(); + } + + // (protected) r = this >> n + function bnpRShiftTo(n, r) { + r.s = this.s; + var ds = Math.floor(n / this.DB); + if (ds >= this.t) { + r.t = 0; + return; + } + var bs = n % this.DB; + var cbs = this.DB - bs; + var bm = (1 << bs) - 1; + r[0] = this[ds] >> bs; + for (var i = ds + 1; i < this.t; ++i) { + r[i - ds - 1] |= (this[i] & bm) << cbs; + r[i - ds] = this[i] >> bs; + } + if (bs > 0) r[this.t - ds - 1] |= (this.s & bm) << cbs; + r.t = this.t - ds; + r.clamp(); + } + + // (protected) r = this - a + function bnpSubTo(a, r) { + var i = 0, + c = 0, + m = Math.min(a.t, this.t); + while (i < m) { + c += this[i] - a[i]; + r[i++] = c & this.DM; + c >>= this.DB; + } + if (a.t < this.t) { + c -= a.s; + while (i < this.t) { + c += this[i]; + r[i++] = c & this.DM; + c >>= this.DB; + } + c += this.s; + } else { + c += this.s; + while (i < a.t) { + c -= a[i]; + r[i++] = c & this.DM; + c >>= this.DB; + } + c -= a.s; + } + r.s = c < 0 ? -1 : 0; + if (c < -1) r[i++] = this.DV + c; + else if (c > 0) r[i++] = c; + r.t = i; + r.clamp(); + } + + // (protected) r = this * a, r != this,a (HAC 14.12) + // "this" should be the larger one if appropriate. + function bnpMultiplyTo(a, r) { + var x = this.abs(), + y = a.abs(); + var i = x.t; + r.t = i + y.t; + while (--i >= 0) r[i] = 0; + for (i = 0; i < y.t; ++i) r[i + x.t] = x.am(0, y[i], r, i, 0, x.t); + r.s = 0; + r.clamp(); + if (this.s != a.s) BigInteger.ZERO.subTo(r, r); + } + + // (protected) r = this^2, r != this (HAC 14.16) + function bnpSquareTo(r) { + var x = this.abs(); + var i = (r.t = 2 * x.t); + while (--i >= 0) r[i] = 0; + for (i = 0; i < x.t - 1; ++i) { + var c = x.am(i, x[i], r, 2 * i, 0, 1); + if ( + (r[i + x.t] += x.am(i + 1, 2 * x[i], r, 2 * i + 1, c, x.t - i - 1)) >= + x.DV + ) { + r[i + x.t] -= x.DV; + r[i + x.t + 1] = 1; + } + } + if (r.t > 0) r[r.t - 1] += x.am(i, x[i], r, 2 * i, 0, 1); + r.s = 0; + r.clamp(); + } + + // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) + // r != q, this != m. q or r may be null. + function bnpDivRemTo(m, q, r) { + var pm = m.abs(); + if (pm.t <= 0) return; + var pt = this.abs(); + if (pt.t < pm.t) { + if (q != null) q.fromInt(0); + if (r != null) this.copyTo(r); + return; + } + if (r == null) r = nbi(); + var y = nbi(), + ts = this.s, + ms = m.s; + var nsh = this.DB - nbits(pm[pm.t - 1]); // normalize modulus + if (nsh > 0) { + pm.lShiftTo(nsh, y); + pt.lShiftTo(nsh, r); + } else { + pm.copyTo(y); + pt.copyTo(r); + } + var ys = y.t; + var y0 = y[ys - 1]; + if (y0 == 0) return; + var yt = y0 * (1 << this.F1) + (ys > 1 ? y[ys - 2] >> this.F2 : 0); + var d1 = this.FV / yt, + d2 = (1 << this.F1) / yt, + e = 1 << this.F2; + var i = r.t, + j = i - ys, + t = q == null ? nbi() : q; + y.dlShiftTo(j, t); + if (r.compareTo(t) >= 0) { + r[r.t++] = 1; + r.subTo(t, r); + } + BigInteger.ONE.dlShiftTo(ys, t); + t.subTo(y, y); // "negative" y so we can replace sub with am later + while (y.t < ys) y[y.t++] = 0; + while (--j >= 0) { + // Estimate quotient digit + var qd = + r[--i] == y0 ? this.DM : Math.floor(r[i] * d1 + (r[i - 1] + e) * d2); + if ((r[i] += y.am(0, qd, r, j, 0, ys)) < qd) { + // Try it out + y.dlShiftTo(j, t); + r.subTo(t, r); + while (r[i] < --qd) r.subTo(t, r); + } + } + if (q != null) { + r.drShiftTo(ys, q); + if (ts != ms) BigInteger.ZERO.subTo(q, q); + } + r.t = ys; + r.clamp(); + if (nsh > 0) r.rShiftTo(nsh, r); // Denormalize remainder + if (ts < 0) BigInteger.ZERO.subTo(r, r); + } + + // (public) this mod a + function bnMod(a) { + var r = nbi(); + this.abs().divRemTo(a, null, r); + if (this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r, r); + return r; + } + + // Modular reduction using "classic" algorithm + function Classic(m) { + this.m = m; + } + function cConvert(x) { + if (x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m); + else return x; + } + function cRevert(x) { + return x; + } + function cReduce(x) { + x.divRemTo(this.m, null, x); + } + function cMulTo(x, y, r) { + x.multiplyTo(y, r); + this.reduce(r); + } + function cSqrTo(x, r) { + x.squareTo(r); + this.reduce(r); + } + + Classic.prototype.convert = cConvert; + Classic.prototype.revert = cRevert; + Classic.prototype.reduce = cReduce; + Classic.prototype.mulTo = cMulTo; + Classic.prototype.sqrTo = cSqrTo; + + // (protected) return "-1/this % 2^DB"; useful for Mont. reduction + // justification: + // xy == 1 (mod m) + // xy = 1+km + // xy(2-xy) = (1+km)(1-km) + // x[y(2-xy)] = 1-k^2m^2 + // x[y(2-xy)] == 1 (mod m^2) + // if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 + // should reduce x and y(2-xy) by m^2 at each step to keep size bounded. + // JS multiply "overflows" differently from C/C++, so care is needed here. + function bnpInvDigit() { + if (this.t < 1) return 0; + var x = this[0]; + if ((x & 1) == 0) return 0; + var y = x & 3; // y == 1/x mod 2^2 + y = (y * (2 - (x & 0xf) * y)) & 0xf; // y == 1/x mod 2^4 + y = (y * (2 - (x & 0xff) * y)) & 0xff; // y == 1/x mod 2^8 + y = (y * (2 - (((x & 0xffff) * y) & 0xffff))) & 0xffff; // y == 1/x mod 2^16 + // last step - calculate inverse mod DV directly; + // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints + y = (y * (2 - ((x * y) % this.DV))) % this.DV; // y == 1/x mod 2^dbits + // we really want the negative inverse, and -DV < y < DV + return y > 0 ? this.DV - y : -y; + } + + // Montgomery reduction + function Montgomery(m) { + this.m = m; + this.mp = m.invDigit(); + this.mpl = this.mp & 0x7fff; + this.mph = this.mp >> 15; + this.um = (1 << (m.DB - 15)) - 1; + this.mt2 = 2 * m.t; + } + + // xR mod m + function montConvert(x) { + var r = nbi(); + x.abs().dlShiftTo(this.m.t, r); + r.divRemTo(this.m, null, r); + if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r, r); + return r; + } + + // x/R mod m + function montRevert(x) { + var r = nbi(); + x.copyTo(r); + this.reduce(r); + return r; + } + + // x = x/R mod m (HAC 14.32) + function montReduce(x) { + while ( + x.t <= this.mt2 // pad x so am has enough room later + ) + x[x.t++] = 0; + for (var i = 0; i < this.m.t; ++i) { + // faster way of calculating u0 = x[i]*mp mod DV + var j = x[i] & 0x7fff; + var u0 = + (j * this.mpl + + (((j * this.mph + (x[i] >> 15) * this.mpl) & this.um) << 15)) & + x.DM; + // use am to combine the multiply-shift-add into one call + j = i + this.m.t; + x[j] += this.m.am(0, u0, x, i, 0, this.m.t); + // propagate carry + while (x[j] >= x.DV) { + x[j] -= x.DV; + x[++j]++; + } + } + x.clamp(); + x.drShiftTo(this.m.t, x); + if (x.compareTo(this.m) >= 0) x.subTo(this.m, x); + } + + // r = "x^2/R mod m"; x != r + function montSqrTo(x, r) { + x.squareTo(r); + this.reduce(r); + } + + // r = "xy/R mod m"; x,y != r + function montMulTo(x, y, r) { + x.multiplyTo(y, r); + this.reduce(r); + } + + Montgomery.prototype.convert = montConvert; + Montgomery.prototype.revert = montRevert; + Montgomery.prototype.reduce = montReduce; + Montgomery.prototype.mulTo = montMulTo; + Montgomery.prototype.sqrTo = montSqrTo; + + // (protected) true iff this is even + function bnpIsEven() { + return (this.t > 0 ? this[0] & 1 : this.s) == 0; + } + + // (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79) + function bnpExp(e, z) { + if (e > 0xffffffff || e < 1) return BigInteger.ONE; + var r = nbi(), + r2 = nbi(), + g = z.convert(this), + i = nbits(e) - 1; + g.copyTo(r); + while (--i >= 0) { + z.sqrTo(r, r2); + if ((e & (1 << i)) > 0) z.mulTo(r2, g, r); + else { + var t = r; + r = r2; + r2 = t; + } + } + return z.revert(r); + } + + // (public) this^e % m, 0 <= e < 2^32 + function bnModPowInt(e, m) { + var z; + if (e < 256 || m.isEven()) z = new Classic(m); + else z = new Montgomery(m); + return this.exp(e, z); + } + + // protected + BigInteger.prototype.copyTo = bnpCopyTo; + BigInteger.prototype.fromInt = bnpFromInt; + BigInteger.prototype.fromString = bnpFromString; + BigInteger.prototype.clamp = bnpClamp; + BigInteger.prototype.dlShiftTo = bnpDLShiftTo; + BigInteger.prototype.drShiftTo = bnpDRShiftTo; + BigInteger.prototype.lShiftTo = bnpLShiftTo; + BigInteger.prototype.rShiftTo = bnpRShiftTo; + BigInteger.prototype.subTo = bnpSubTo; + BigInteger.prototype.multiplyTo = bnpMultiplyTo; + BigInteger.prototype.squareTo = bnpSquareTo; + BigInteger.prototype.divRemTo = bnpDivRemTo; + BigInteger.prototype.invDigit = bnpInvDigit; + BigInteger.prototype.isEven = bnpIsEven; + BigInteger.prototype.exp = bnpExp; + + // public + BigInteger.prototype.toString = bnToString; + BigInteger.prototype.negate = bnNegate; + BigInteger.prototype.abs = bnAbs; + BigInteger.prototype.compareTo = bnCompareTo; + BigInteger.prototype.bitLength = bnBitLength; + BigInteger.prototype.mod = bnMod; + BigInteger.prototype.modPowInt = bnModPowInt; + + // "constants" + BigInteger.ZERO = nbv(0); + BigInteger.ONE = nbv(1); + BigInteger.valueOf = nbv; + + // Copyright (c) 2005-2009 Tom Wu + // All Rights Reserved. + // See "LICENSE" for details. + + // Extended JavaScript BN functions, required for RSA private ops. + + // Version 1.1: new BigInteger("0", 10) returns "proper" zero + // Version 1.2: square() API, isProbablePrime fix + + // (public) + function bnClone() { + var r = nbi(); + this.copyTo(r); + return r; + } + + // (public) return value as integer + function bnIntValue() { + if (this.s < 0) { + if (this.t == 1) return this[0] - this.DV; + else if (this.t == 0) return -1; + } else if (this.t == 1) return this[0]; + else if (this.t == 0) return 0; + // assumes 16 < DB < 32 + return ((this[1] & ((1 << (32 - this.DB)) - 1)) << this.DB) | this[0]; + } + + // (public) return value as byte + function bnByteValue() { + return this.t == 0 ? this.s : (this[0] << 24) >> 24; + } + + // (public) return value as short (assumes DB>=16) + function bnShortValue() { + return this.t == 0 ? this.s : (this[0] << 16) >> 16; + } + + // (protected) return x s.t. r^x < DV + function bnpChunkSize(r) { + return Math.floor((Math.LN2 * this.DB) / Math.log(r)); + } + + // (public) 0 if this == 0, 1 if this > 0 + function bnSigNum() { + if (this.s < 0) return -1; + else if (this.t <= 0 || (this.t == 1 && this[0] <= 0)) return 0; + else return 1; + } + + // (protected) convert to radix string + function bnpToRadix(b) { + if (b == null) b = 10; + if (this.signum() == 0 || b < 2 || b > 36) return '0'; + var cs = this.chunkSize(b); + var a = Math.pow(b, cs); + var d = nbv(a), + y = nbi(), + z = nbi(), + r = ''; + this.divRemTo(d, y, z); + while (y.signum() > 0) { + r = (a + z.intValue()).toString(b).substr(1) + r; + y.divRemTo(d, y, z); + } + return z.intValue().toString(b) + r; + } + + // (protected) convert from radix string + function bnpFromRadix(s, b) { + this.fromInt(0); + if (b == null) b = 10; + var cs = this.chunkSize(b); + var d = Math.pow(b, cs), + mi = false, + j = 0, + w = 0; + for (var i = 0; i < s.length; ++i) { + var x = intAt(s, i); + if (x < 0) { + if (s.charAt(i) == '-' && this.signum() == 0) mi = true; + continue; + } + w = b * w + x; + if (++j >= cs) { + this.dMultiply(d); + this.dAddOffset(w, 0); + j = 0; + w = 0; + } + } + if (j > 0) { + this.dMultiply(Math.pow(b, j)); + this.dAddOffset(w, 0); + } + if (mi) BigInteger.ZERO.subTo(this, this); + } + + // (protected) alternate constructor + function bnpFromNumber(a, b, c) { + if ('number' == typeof b) { + // new BigInteger(int,int,RNG) + if (a < 2) this.fromInt(1); + else { + this.fromNumber(a, c); + if (!this.testBit(a - 1)) + // force MSB set + this.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, this); + if (this.isEven()) this.dAddOffset(1, 0); // force odd + while (!this.isProbablePrime(b)) { + this.dAddOffset(2, 0); + if (this.bitLength() > a) + this.subTo(BigInteger.ONE.shiftLeft(a - 1), this); + } + } + } else { + // new BigInteger(int,RNG) + var x = new Array(), + t = a & 7; + x.length = (a >> 3) + 1; + b.nextBytes(x); + if (t > 0) x[0] &= (1 << t) - 1; + else x[0] = 0; + this.fromString(x, 256); + } + } + + // (public) convert to bigendian byte array + function bnToByteArray() { + var i = this.t, + r = new Array(); + r[0] = this.s; + var p = this.DB - ((i * this.DB) % 8), + d, + k = 0; + if (i-- > 0) { + if (p < this.DB && (d = this[i] >> p) != (this.s & this.DM) >> p) + r[k++] = d | (this.s << (this.DB - p)); + while (i >= 0) { + if (p < 8) { + d = (this[i] & ((1 << p) - 1)) << (8 - p); + d |= this[--i] >> (p += this.DB - 8); + } else { + d = (this[i] >> (p -= 8)) & 0xff; + if (p <= 0) { + p += this.DB; + --i; + } + } + if ((d & 0x80) != 0) d |= -256; + if (k == 0 && (this.s & 0x80) != (d & 0x80)) ++k; + if (k > 0 || d != this.s) r[k++] = d; + } + } + return r; + } + + function bnEquals(a) { + return this.compareTo(a) == 0; + } + function bnMin(a) { + return this.compareTo(a) < 0 ? this : a; + } + function bnMax(a) { + return this.compareTo(a) > 0 ? this : a; + } + + // (protected) r = this op a (bitwise) + function bnpBitwiseTo(a, op, r) { + var i, + f, + m = Math.min(a.t, this.t); + for (i = 0; i < m; ++i) r[i] = op(this[i], a[i]); + if (a.t < this.t) { + f = a.s & this.DM; + for (i = m; i < this.t; ++i) r[i] = op(this[i], f); + r.t = this.t; + } else { + f = this.s & this.DM; + for (i = m; i < a.t; ++i) r[i] = op(f, a[i]); + r.t = a.t; + } + r.s = op(this.s, a.s); + r.clamp(); + } + + // (public) this & a + function op_and(x, y) { + return x & y; + } + function bnAnd(a) { + var r = nbi(); + this.bitwiseTo(a, op_and, r); + return r; + } + + // (public) this | a + function op_or(x, y) { + return x | y; + } + function bnOr(a) { + var r = nbi(); + this.bitwiseTo(a, op_or, r); + return r; + } + + // (public) this ^ a + function op_xor(x, y) { + return x ^ y; + } + function bnXor(a) { + var r = nbi(); + this.bitwiseTo(a, op_xor, r); + return r; + } + + // (public) this & ~a + function op_andnot(x, y) { + return x & ~y; + } + function bnAndNot(a) { + var r = nbi(); + this.bitwiseTo(a, op_andnot, r); + return r; + } + + // (public) ~this + function bnNot() { + var r = nbi(); + for (var i = 0; i < this.t; ++i) r[i] = this.DM & ~this[i]; + r.t = this.t; + r.s = ~this.s; + return r; + } + + // (public) this << n + function bnShiftLeft(n) { + var r = nbi(); + if (n < 0) this.rShiftTo(-n, r); + else this.lShiftTo(n, r); + return r; + } + + // (public) this >> n + function bnShiftRight(n) { + var r = nbi(); + if (n < 0) this.lShiftTo(-n, r); + else this.rShiftTo(n, r); + return r; + } + + // return index of lowest 1-bit in x, x < 2^31 + function lbit(x) { + if (x == 0) return -1; + var r = 0; + if ((x & 0xffff) == 0) { + x >>= 16; + r += 16; + } + if ((x & 0xff) == 0) { + x >>= 8; + r += 8; + } + if ((x & 0xf) == 0) { + x >>= 4; + r += 4; + } + if ((x & 3) == 0) { + x >>= 2; + r += 2; + } + if ((x & 1) == 0) ++r; + return r; + } + + // (public) returns index of lowest 1-bit (or -1 if none) + function bnGetLowestSetBit() { + for (var i = 0; i < this.t; ++i) + if (this[i] != 0) return i * this.DB + lbit(this[i]); + if (this.s < 0) return this.t * this.DB; + return -1; + } + + // return number of 1 bits in x + function cbit(x) { + var r = 0; + while (x != 0) { + x &= x - 1; + ++r; + } + return r; + } + + // (public) return number of set bits + function bnBitCount() { + var r = 0, + x = this.s & this.DM; + for (var i = 0; i < this.t; ++i) r += cbit(this[i] ^ x); + return r; + } + + // (public) true iff nth bit is set + function bnTestBit(n) { + var j = Math.floor(n / this.DB); + if (j >= this.t) return this.s != 0; + return (this[j] & (1 << n % this.DB)) != 0; + } + + // (protected) this op (1<>= this.DB; + } + if (a.t < this.t) { + c += a.s; + while (i < this.t) { + c += this[i]; + r[i++] = c & this.DM; + c >>= this.DB; + } + c += this.s; + } else { + c += this.s; + while (i < a.t) { + c += a[i]; + r[i++] = c & this.DM; + c >>= this.DB; + } + c += a.s; + } + r.s = c < 0 ? -1 : 0; + if (c > 0) r[i++] = c; + else if (c < -1) r[i++] = this.DV + c; + r.t = i; + r.clamp(); + } + + // (public) this + a + function bnAdd(a) { + var r = nbi(); + this.addTo(a, r); + return r; + } + + // (public) this - a + function bnSubtract(a) { + var r = nbi(); + this.subTo(a, r); + return r; + } + + // (public) this * a + function bnMultiply(a) { + var r = nbi(); + this.multiplyTo(a, r); + return r; + } + + // (public) this^2 + function bnSquare() { + var r = nbi(); + this.squareTo(r); + return r; + } + + // (public) this / a + function bnDivide(a) { + var r = nbi(); + this.divRemTo(a, r, null); + return r; + } + + // (public) this % a + function bnRemainder(a) { + var r = nbi(); + this.divRemTo(a, null, r); + return r; + } + + // (public) [this/a,this%a] + function bnDivideAndRemainder(a) { + var q = nbi(), + r = nbi(); + this.divRemTo(a, q, r); + return new Array(q, r); + } + + // (protected) this *= n, this >= 0, 1 < n < DV + function bnpDMultiply(n) { + this[this.t] = this.am(0, n - 1, this, 0, 0, this.t); + ++this.t; + this.clamp(); + } + + // (protected) this += n << w words, this >= 0 + function bnpDAddOffset(n, w) { + if (n == 0) return; + while (this.t <= w) this[this.t++] = 0; + this[w] += n; + while (this[w] >= this.DV) { + this[w] -= this.DV; + if (++w >= this.t) this[this.t++] = 0; + ++this[w]; + } + } + + // A "null" reducer + function NullExp() { } + function nNop(x) { + return x; + } + function nMulTo(x, y, r) { + x.multiplyTo(y, r); + } + function nSqrTo(x, r) { + x.squareTo(r); + } + + NullExp.prototype.convert = nNop; + NullExp.prototype.revert = nNop; + NullExp.prototype.mulTo = nMulTo; + NullExp.prototype.sqrTo = nSqrTo; + + // (public) this^e + function bnPow(e) { + return this.exp(e, new NullExp()); + } + + // (protected) r = lower n words of "this * a", a.t <= n + // "this" should be the larger one if appropriate. + function bnpMultiplyLowerTo(a, n, r) { + var i = Math.min(this.t + a.t, n); + r.s = 0; // assumes a,this >= 0 + r.t = i; + while (i > 0) r[--i] = 0; + var j; + for (j = r.t - this.t; i < j; ++i) + r[i + this.t] = this.am(0, a[i], r, i, 0, this.t); + for (j = Math.min(a.t, n); i < j; ++i) this.am(0, a[i], r, i, 0, n - i); + r.clamp(); + } + + // (protected) r = "this * a" without lower n words, n > 0 + // "this" should be the larger one if appropriate. + function bnpMultiplyUpperTo(a, n, r) { + --n; + var i = (r.t = this.t + a.t - n); + r.s = 0; // assumes a,this >= 0 + while (--i >= 0) r[i] = 0; + for (i = Math.max(n - this.t, 0); i < a.t; ++i) + r[this.t + i - n] = this.am(n - i, a[i], r, 0, 0, this.t + i - n); + r.clamp(); + r.drShiftTo(1, r); + } + + // Barrett modular reduction + function Barrett(m) { + // setup Barrett + this.r2 = nbi(); + this.q3 = nbi(); + BigInteger.ONE.dlShiftTo(2 * m.t, this.r2); + this.mu = this.r2.divide(m); + this.m = m; + } + + function barrettConvert(x) { + if (x.s < 0 || x.t > 2 * this.m.t) return x.mod(this.m); + else if (x.compareTo(this.m) < 0) return x; + else { + var r = nbi(); + x.copyTo(r); + this.reduce(r); + return r; + } + } + + function barrettRevert(x) { + return x; + } + + // x = x mod m (HAC 14.42) + function barrettReduce(x) { + x.drShiftTo(this.m.t - 1, this.r2); + if (x.t > this.m.t + 1) { + x.t = this.m.t + 1; + x.clamp(); + } + this.mu.multiplyUpperTo(this.r2, this.m.t + 1, this.q3); + this.m.multiplyLowerTo(this.q3, this.m.t + 1, this.r2); + while (x.compareTo(this.r2) < 0) x.dAddOffset(1, this.m.t + 1); + x.subTo(this.r2, x); + while (x.compareTo(this.m) >= 0) x.subTo(this.m, x); + } + + // r = x^2 mod m; x != r + function barrettSqrTo(x, r) { + x.squareTo(r); + this.reduce(r); + } + + // r = x*y mod m; x,y != r + function barrettMulTo(x, y, r) { + x.multiplyTo(y, r); + this.reduce(r); + } + + Barrett.prototype.convert = barrettConvert; + Barrett.prototype.revert = barrettRevert; + Barrett.prototype.reduce = barrettReduce; + Barrett.prototype.mulTo = barrettMulTo; + Barrett.prototype.sqrTo = barrettSqrTo; + + // (public) this^e % m (HAC 14.85) + function bnModPow(e, m) { + var i = e.bitLength(), + k, + r = nbv(1), + z; + if (i <= 0) return r; + else if (i < 18) k = 1; + else if (i < 48) k = 3; + else if (i < 144) k = 4; + else if (i < 768) k = 5; + else k = 6; + if (i < 8) z = new Classic(m); + else if (m.isEven()) z = new Barrett(m); + else z = new Montgomery(m); + + // precomputation + var g = new Array(), + n = 3, + k1 = k - 1, + km = (1 << k) - 1; + g[1] = z.convert(this); + if (k > 1) { + var g2 = nbi(); + z.sqrTo(g[1], g2); + while (n <= km) { + g[n] = nbi(); + z.mulTo(g2, g[n - 2], g[n]); + n += 2; + } + } + + var j = e.t - 1, + w, + is1 = true, + r2 = nbi(), + t; + i = nbits(e[j]) - 1; + while (j >= 0) { + if (i >= k1) w = (e[j] >> (i - k1)) & km; + else { + w = (e[j] & ((1 << (i + 1)) - 1)) << (k1 - i); + if (j > 0) w |= e[j - 1] >> (this.DB + i - k1); + } + + n = k; + while ((w & 1) == 0) { + w >>= 1; + --n; + } + if ((i -= n) < 0) { + i += this.DB; + --j; + } + if (is1) { + // ret == 1, don't bother squaring or multiplying it + g[w].copyTo(r); + is1 = false; + } else { + while (n > 1) { + z.sqrTo(r, r2); + z.sqrTo(r2, r); + n -= 2; + } + if (n > 0) z.sqrTo(r, r2); + else { + t = r; + r = r2; + r2 = t; + } + z.mulTo(r2, g[w], r); + } + + while (j >= 0 && (e[j] & (1 << i)) == 0) { + z.sqrTo(r, r2); + t = r; + r = r2; + r2 = t; + if (--i < 0) { + i = this.DB - 1; + --j; + } + } + } + return z.revert(r); + } + + // (public) gcd(this,a) (HAC 14.54) + function bnGCD(a) { + var x = this.s < 0 ? this.negate() : this.clone(); + var y = a.s < 0 ? a.negate() : a.clone(); + if (x.compareTo(y) < 0) { + var t = x; + x = y; + y = t; + } + var i = x.getLowestSetBit(), + g = y.getLowestSetBit(); + if (g < 0) return x; + if (i < g) g = i; + if (g > 0) { + x.rShiftTo(g, x); + y.rShiftTo(g, y); + } + while (x.signum() > 0) { + if ((i = x.getLowestSetBit()) > 0) x.rShiftTo(i, x); + if ((i = y.getLowestSetBit()) > 0) y.rShiftTo(i, y); + if (x.compareTo(y) >= 0) { + x.subTo(y, x); + x.rShiftTo(1, x); + } else { + y.subTo(x, y); + y.rShiftTo(1, y); + } + } + if (g > 0) y.lShiftTo(g, y); + return y; + } + + // (protected) this % n, n < 2^26 + function bnpModInt(n) { + if (n <= 0) return 0; + var d = this.DV % n, + r = this.s < 0 ? n - 1 : 0; + if (this.t > 0) + if (d == 0) r = this[0] % n; + else for (var i = this.t - 1; i >= 0; --i) r = (d * r + this[i]) % n; + return r; + } + + // (public) 1/this % m (HAC 14.61) + function bnModInverse(m) { + var ac = m.isEven(); + if ((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO; + var u = m.clone(), + v = this.clone(); + var a = nbv(1), + b = nbv(0), + c = nbv(0), + d = nbv(1); + while (u.signum() != 0) { + while (u.isEven()) { + u.rShiftTo(1, u); + if (ac) { + if (!a.isEven() || !b.isEven()) { + a.addTo(this, a); + b.subTo(m, b); + } + a.rShiftTo(1, a); + } else if (!b.isEven()) b.subTo(m, b); + b.rShiftTo(1, b); + } + while (v.isEven()) { + v.rShiftTo(1, v); + if (ac) { + if (!c.isEven() || !d.isEven()) { + c.addTo(this, c); + d.subTo(m, d); + } + c.rShiftTo(1, c); + } else if (!d.isEven()) d.subTo(m, d); + d.rShiftTo(1, d); + } + if (u.compareTo(v) >= 0) { + u.subTo(v, u); + if (ac) a.subTo(c, a); + b.subTo(d, b); + } else { + v.subTo(u, v); + if (ac) c.subTo(a, c); + d.subTo(b, d); + } + } + if (v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO; + if (d.compareTo(m) >= 0) return d.subtract(m); + if (d.signum() < 0) d.addTo(m, d); + else return d; + if (d.signum() < 0) return d.add(m); + else return d; + } + + var lowprimes = [ + 2, + 3, + 5, + 7, + 11, + 13, + 17, + 19, + 23, + 29, + 31, + 37, + 41, + 43, + 47, + 53, + 59, + 61, + 67, + 71, + 73, + 79, + 83, + 89, + 97, + 101, + 103, + 107, + 109, + 113, + 127, + 131, + 137, + 139, + 149, + 151, + 157, + 163, + 167, + 173, + 179, + 181, + 191, + 193, + 197, + 199, + 211, + 223, + 227, + 229, + 233, + 239, + 241, + 251, + 257, + 263, + 269, + 271, + 277, + 281, + 283, + 293, + 307, + 311, + 313, + 317, + 331, + 337, + 347, + 349, + 353, + 359, + 367, + 373, + 379, + 383, + 389, + 397, + 401, + 409, + 419, + 421, + 431, + 433, + 439, + 443, + 449, + 457, + 461, + 463, + 467, + 479, + 487, + 491, + 499, + 503, + 509, + 521, + 523, + 541, + 547, + 557, + 563, + 569, + 571, + 577, + 587, + 593, + 599, + 601, + 607, + 613, + 617, + 619, + 631, + 641, + 643, + 647, + 653, + 659, + 661, + 673, + 677, + 683, + 691, + 701, + 709, + 719, + 727, + 733, + 739, + 743, + 751, + 757, + 761, + 769, + 773, + 787, + 797, + 809, + 811, + 821, + 823, + 827, + 829, + 839, + 853, + 857, + 859, + 863, + 877, + 881, + 883, + 887, + 907, + 911, + 919, + 929, + 937, + 941, + 947, + 953, + 967, + 971, + 977, + 983, + 991, + 997, + ]; + var lplim = (1 << 26) / lowprimes[lowprimes.length - 1]; + + // (public) test primality with certainty >= 1-.5^t + function bnIsProbablePrime(t) { + var i, + x = this.abs(); + if (x.t == 1 && x[0] <= lowprimes[lowprimes.length - 1]) { + for (i = 0; i < lowprimes.length; ++i) + if (x[0] == lowprimes[i]) return true; + return false; + } + if (x.isEven()) return false; + i = 1; + while (i < lowprimes.length) { + var m = lowprimes[i], + j = i + 1; + while (j < lowprimes.length && m < lplim) m *= lowprimes[j++]; + m = x.modInt(m); + while (i < j) if (m % lowprimes[i++] == 0) return false; + } + return x.millerRabin(t); + } + + // (protected) true if probably prime (HAC 4.24, Miller-Rabin) + function bnpMillerRabin(t) { + var n1 = this.subtract(BigInteger.ONE); + var k = n1.getLowestSetBit(); + if (k <= 0) return false; + var r = n1.shiftRight(k); + t = (t + 1) >> 1; + if (t > lowprimes.length) t = lowprimes.length; + var a = nbi(); + for (var i = 0; i < t; ++i) { + //Pick bases at random, instead of starting at 2 + a.fromInt(lowprimes[Math.floor(Math.random() * lowprimes.length)]); + var y = a.modPow(r, this); + if (y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { + var j = 1; + while (j++ < k && y.compareTo(n1) != 0) { + y = y.modPowInt(2, this); + if (y.compareTo(BigInteger.ONE) == 0) return false; + } + if (y.compareTo(n1) != 0) return false; + } + } + return true; + } + + // protected + BigInteger.prototype.chunkSize = bnpChunkSize; + BigInteger.prototype.toRadix = bnpToRadix; + BigInteger.prototype.fromRadix = bnpFromRadix; + BigInteger.prototype.fromNumber = bnpFromNumber; + BigInteger.prototype.bitwiseTo = bnpBitwiseTo; + BigInteger.prototype.changeBit = bnpChangeBit; + BigInteger.prototype.addTo = bnpAddTo; + BigInteger.prototype.dMultiply = bnpDMultiply; + BigInteger.prototype.dAddOffset = bnpDAddOffset; + BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo; + BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo; + BigInteger.prototype.modInt = bnpModInt; + BigInteger.prototype.millerRabin = bnpMillerRabin; + + // public + BigInteger.prototype.clone = bnClone; + BigInteger.prototype.intValue = bnIntValue; + BigInteger.prototype.byteValue = bnByteValue; + BigInteger.prototype.shortValue = bnShortValue; + BigInteger.prototype.signum = bnSigNum; + BigInteger.prototype.toByteArray = bnToByteArray; + BigInteger.prototype.equals = bnEquals; + BigInteger.prototype.min = bnMin; + BigInteger.prototype.max = bnMax; + BigInteger.prototype.and = bnAnd; + BigInteger.prototype.or = bnOr; + BigInteger.prototype.xor = bnXor; + BigInteger.prototype.andNot = bnAndNot; + BigInteger.prototype.not = bnNot; + BigInteger.prototype.shiftLeft = bnShiftLeft; + BigInteger.prototype.shiftRight = bnShiftRight; + BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit; + BigInteger.prototype.bitCount = bnBitCount; + BigInteger.prototype.testBit = bnTestBit; + BigInteger.prototype.setBit = bnSetBit; + BigInteger.prototype.clearBit = bnClearBit; + BigInteger.prototype.flipBit = bnFlipBit; + BigInteger.prototype.add = bnAdd; + BigInteger.prototype.subtract = bnSubtract; + BigInteger.prototype.multiply = bnMultiply; + BigInteger.prototype.divide = bnDivide; + BigInteger.prototype.remainder = bnRemainder; + BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder; + BigInteger.prototype.modPow = bnModPow; + BigInteger.prototype.modInverse = bnModInverse; + BigInteger.prototype.pow = bnPow; + BigInteger.prototype.gcd = bnGCD; + BigInteger.prototype.isProbablePrime = bnIsProbablePrime; + + // JSBN-specific extension + BigInteger.prototype.square = bnSquare; + + // Expose the Barrett function + BigInteger.prototype.Barrett = Barrett; + + // BigInteger interfaces not implemented in jsbn: + + // BigInteger(int signum, byte[] magnitude) + // double doubleValue() + // float floatValue() + // int hashCode() + // long longValue() + // static BigInteger valueOf(long val) + + // Imported from bitcoinjs-lib + + /** + * Turns a byte array into a big integer. + * + * This function will interpret a byte array as a big integer in big + * endian notation and ignore leading zeros. + */ + + BigInteger.fromByteArrayUnsigned = function (ba) { + + if (!ba.length) { + return new BigInteger.valueOf(0); + } else if (ba[0] & 0x80) { + // Prepend a zero so the BigInteger class doesn't mistake this + // for a negative integer. + return new BigInteger([0].concat(ba)); + } else { + return new BigInteger(ba); + } + }; + + /** + * Parse a signed big integer byte representation. + * + * For details on the format please see BigInteger.toByteArraySigned. + */ + + BigInteger.fromByteArraySigned = function (ba) { + // Check for negative value + if (ba[0] & 0x80) { + // Remove sign bit + ba[0] &= 0x7f; + + return BigInteger.fromByteArrayUnsigned(ba).negate(); + } else { + return BigInteger.fromByteArrayUnsigned(ba); + } + }; + + /** + * Returns a byte array representation of the big integer. + * + * This returns the absolute of the contained value in big endian + * form. A value of zero results in an empty array. + */ + + BigInteger.prototype.toByteArrayUnsigned = function () { + var ba = this.abs().toByteArray(); + + // Empty array, nothing to do + if (!ba.length) { + return ba; + } + + // remove leading 0 + if (ba[0] === 0) { + ba = ba.slice(1); + } + + // all values must be positive + for (var i = 0; i < ba.length; ++i) { + ba[i] = (ba[i] < 0) ? ba[i] + 256 : ba[i]; + } + + return ba; + }; + + /* + * Converts big integer to signed byte representation. + * + * The format for this value uses the most significant bit as a sign + * bit. If the most significant bit is already occupied by the + * absolute value, an extra byte is prepended and the sign bit is set + * there. + * + * Examples: + * + * 0 => 0x00 + * 1 => 0x01 + * -1 => 0x81 + * 127 => 0x7f + * -127 => 0xff + * 128 => 0x0080 + * -128 => 0x8080 + * 255 => 0x00ff + * -255 => 0x80ff + * 16300 => 0x3fac + * -16300 => 0xbfac + * 62300 => 0x00f35c + * -62300 => 0x80f35c + */ + + BigInteger.prototype.toByteArraySigned = function () { + var val = this.toByteArrayUnsigned(); + var neg = this.s < 0; + + // if the first bit is set, we always unshift + // either unshift 0x80 or 0x00 + if (val[0] & 0x80) { + val.unshift((neg) ? 0x80 : 0x00); + } + // if the first bit isn't set, set it if negative + else if (neg) { + val[0] |= 0x80; + } + + return val; + }; + + // Random number generator - requires a PRNG backend, e.g. prng4.js + + // For best results, put code like + // + // in your main HTML document. + + var rng_state; + var rng_pool; + var rng_pptr; + + // Mix in a 32-bit integer into the pool + function rng_seed_int(x) { + rng_pool[rng_pptr++] ^= x & 255; + rng_pool[rng_pptr++] ^= (x >> 8) & 255; + rng_pool[rng_pptr++] ^= (x >> 16) & 255; + rng_pool[rng_pptr++] ^= (x >> 24) & 255; + if (rng_pptr >= rng_psize) rng_pptr -= rng_psize; + } + + // Mix in the current time (w/milliseconds) into the pool + function rng_seed_time() { + rng_seed_int(new Date().getTime()); + } + + // Initialize the pool with junk if needed. + if (rng_pool == null) { + rng_pool = new Array(); + rng_pptr = 0; + var t; + if (typeof window !== 'undefined' && window.crypto) { + if (window.crypto.getRandomValues) { + // Use webcrypto if available + var ua = new Uint8Array(32); + window.crypto.getRandomValues(ua); + for (t = 0; t < 32; ++t) rng_pool[rng_pptr++] = ua[t]; + } else if ( + navigator.appName == 'Netscape' && + navigator.appVersion < '5' + ) { + // Extract entropy (256 bits) from NS4 RNG if available + var z = window.crypto.random(32); + for (t = 0; t < z.length; ++t) + rng_pool[rng_pptr++] = z.charCodeAt(t) & 255; + } + } + while (rng_pptr < rng_psize) { + // extract some randomness from Math.random() + t = Math.floor(65536 * Math.random()); + rng_pool[rng_pptr++] = t >>> 8; + rng_pool[rng_pptr++] = t & 255; + } + rng_pptr = 0; + rng_seed_time(); + } + + function rng_get_byte() { + if (rng_state == null) { + rng_seed_time(); + rng_state = prng_newstate(); + rng_state.init(rng_pool); + for (rng_pptr = 0; rng_pptr < rng_pool.length; ++rng_pptr) + rng_pool[rng_pptr] = 0; + rng_pptr = 0; + } + // TODO: allow reseeding after first request + return rng_state.next(); + } + + function rng_get_bytes(ba) { + var i; + for (i = 0; i < ba.length; ++i) ba[i] = rng_get_byte(); + } + + function SecureRandom() { } + + SecureRandom.prototype.nextBytes = rng_get_bytes; + + // prng4.js - uses Arcfour as a PRNG + function Arcfour() { + this.i = 0; + this.j = 0; + this.S = new Array(); + } + + // Initialize arcfour context from key, an array of ints, each from [0..255] + function ARC4init(key) { + var i, j, t; + for (i = 0; i < 256; ++i) this.S[i] = i; + j = 0; + for (i = 0; i < 256; ++i) { + j = (j + this.S[i] + key[i % key.length]) & 255; + t = this.S[i]; + this.S[i] = this.S[j]; + this.S[j] = t; + } + this.i = 0; + this.j = 0; + } + + function ARC4next() { + var t; + this.i = (this.i + 1) & 255; + this.j = (this.j + this.S[this.i]) & 255; + t = this.S[this.i]; + this.S[this.i] = this.S[this.j]; + this.S[this.j] = t; + return this.S[(t + this.S[this.i]) & 255]; + } + + Arcfour.prototype.init = ARC4init; + Arcfour.prototype.next = ARC4next; + + // Plug in your RNG constructor here + function prng_newstate() { + return new Arcfour(); + } + + // Pool size must be a multiple of 4 and greater than 32. + // An array of bytes the size of the pool will be passed to init() + var rng_psize = 256; + + /*! + * Basic Javascript Elliptic Curve implementation + * Ported loosely from BouncyCastle's Java EC code + * Only Fp curves implemented for now + * + * Copyright Tom Wu, bitaddress.org BSD License. + * http://www-cs-students.stanford.edu/~tjw/jsbn/LICENSE + */ + + // Constructor function of Global EllipticCurve object + var ec = function () { }; + + // ---------------- + // ECFieldElementFp constructor + // q instanceof BigInteger + // x instanceof BigInteger + ec.FieldElementFp = function (q, x) { + this.x = x; + // TODO if(x.compareTo(q) >= 0) error + this.q = q; + }; + + ec.FieldElementFp.prototype.equals = function (other) { + if (other == this) return true; + return (this.q.equals(other.q) && this.x.equals(other.x)); + }; + + ec.FieldElementFp.prototype.toBigInteger = function () { + return this.x; + }; + + ec.FieldElementFp.prototype.negate = function () { + return new ec.FieldElementFp(this.q, this.x.negate().mod(this.q)); + }; + + ec.FieldElementFp.prototype.add = function (b) { + return new ec.FieldElementFp(this.q, this.x.add(b.toBigInteger()).mod(this.q)); + }; + + ec.FieldElementFp.prototype.subtract = function (b) { + return new ec.FieldElementFp(this.q, this.x.subtract(b.toBigInteger()).mod(this.q)); + }; + + ec.FieldElementFp.prototype.multiply = function (b) { + return new ec.FieldElementFp(this.q, this.x.multiply(b.toBigInteger()).mod(this.q)); + }; + + ec.FieldElementFp.prototype.square = function () { + return new ec.FieldElementFp(this.q, this.x.square().mod(this.q)); + }; + + ec.FieldElementFp.prototype.divide = function (b) { + return new ec.FieldElementFp(this.q, this.x.multiply(b.toBigInteger().modInverse(this.q)).mod(this.q)); + }; + + ec.FieldElementFp.prototype.getByteLength = function () { + return Math.floor((this.toBigInteger().bitLength() + 7) / 8); + }; + + // D.1.4 91 /** * return a sqrt root - the routine verifies that the calculation * returns the right value - if none exists it returns null. @@ -2005,530 +1995,526 @@ * Copyright (c) 2000 - 2011 The Legion Of The Bouncy Castle (http://www.bouncycastle.org) * Ported to JavaScript by bitaddress.org */ - ec.FieldElementFp.prototype.sqrt = function () { - if (!this.q.testBit(0)) throw new Error("even value of q"); + ec.FieldElementFp.prototype.sqrt = function () { + if (!this.q.testBit(0)) throw new Error("even value of q"); - // p mod 4 == 3 - if (this.q.testBit(1)) { - // z = g^(u+1) + p, p = 4u + 3 - var z = new ec.FieldElementFp(this.q, this.x.modPow(this.q.shiftRight(2).add(BigInteger.ONE), this.q)); - return z.square().equals(this) ? z : null; - } + // p mod 4 == 3 + if (this.q.testBit(1)) { + // z = g^(u+1) + p, p = 4u + 3 + var z = new ec.FieldElementFp(this.q, this.x.modPow(this.q.shiftRight(2).add(BigInteger.ONE), this.q)); + return z.square().equals(this) ? z : null; + } - // p mod 4 == 1 - var qMinusOne = this.q.subtract(BigInteger.ONE); - var legendreExponent = qMinusOne.shiftRight(1); - if (!(this.x.modPow(legendreExponent, this.q).equals(BigInteger.ONE))) return null; - var u = qMinusOne.shiftRight(2); - var k = u.shiftLeft(1).add(BigInteger.ONE); - var Q = this.x; - var fourQ = Q.shiftLeft(2).mod(this.q); - var U, V; + // p mod 4 == 1 + var qMinusOne = this.q.subtract(BigInteger.ONE); + var legendreExponent = qMinusOne.shiftRight(1); + if (!(this.x.modPow(legendreExponent, this.q).equals(BigInteger.ONE))) return null; + var u = qMinusOne.shiftRight(2); + var k = u.shiftLeft(1).add(BigInteger.ONE); + var Q = this.x; + var fourQ = Q.shiftLeft(2).mod(this.q); + var U, V; - do { - var rand = new SecureRandom(); - var P; - do { - P = new BigInteger(this.q.bitLength(), rand); - } - while (P.compareTo(this.q) >= 0 || !(P.multiply(P).subtract(fourQ).modPow(legendreExponent, this.q).equals(qMinusOne))); + do { + var rand = new SecureRandom(); + var P; + do { + P = new BigInteger(this.q.bitLength(), rand); + } + while (P.compareTo(this.q) >= 0 || !(P.multiply(P).subtract(fourQ).modPow(legendreExponent, this.q).equals(qMinusOne))); - var result = ec.FieldElementFp.fastLucasSequence(this.q, P, Q, k); + var result = ec.FieldElementFp.fastLucasSequence(this.q, P, Q, k); - U = result[0]; - V = result[1]; - if (V.multiply(V).mod(this.q).equals(fourQ)) { - // Integer division by 2, mod q - if (V.testBit(0)) { - V = V.add(this.q); - } - V = V.shiftRight(1); - return new ec.FieldElementFp(this.q, V); - } - } - while (U.equals(BigInteger.ONE) || U.equals(qMinusOne)); + U = result[0]; + V = result[1]; + if (V.multiply(V).mod(this.q).equals(fourQ)) { + // Integer division by 2, mod q + if (V.testBit(0)) { + V = V.add(this.q); + } + V = V.shiftRight(1); + return new ec.FieldElementFp(this.q, V); + } + } + while (U.equals(BigInteger.ONE) || U.equals(qMinusOne)); - return null; - }; + return null; + }; /* * Copyright (c) 2000 - 2011 The Legion Of The Bouncy Castle (http://www.bouncycastle.org) * Ported to JavaScript by bitaddress.org */ - ec.FieldElementFp.fastLucasSequence = function (p, P, Q, k) { - // TODO Research and apply "common-multiplicand multiplication here" + ec.FieldElementFp.fastLucasSequence = function (p, P, Q, k) { + // TODO Research and apply "common-multiplicand multiplication here" - var n = k.bitLength(); - var s = k.getLowestSetBit(); - var Uh = BigInteger.ONE; - var Vl = BigInteger.TWO; - var Vh = P; - var Ql = BigInteger.ONE; - var Qh = BigInteger.ONE; + var n = k.bitLength(); + var s = k.getLowestSetBit(); + var Uh = BigInteger.ONE; + var Vl = BigInteger.TWO; + var Vh = P; + var Ql = BigInteger.ONE; + var Qh = BigInteger.ONE; - for (var j = n - 1; j >= s + 1; --j) { - Ql = Ql.multiply(Qh).mod(p); - if (k.testBit(j)) { - Qh = Ql.multiply(Q).mod(p); - Uh = Uh.multiply(Vh).mod(p); - Vl = Vh.multiply(Vl).subtract(P.multiply(Ql)).mod(p); - Vh = Vh.multiply(Vh).subtract(Qh.shiftLeft(1)).mod(p); - } - else { - Qh = Ql; - Uh = Uh.multiply(Vl).subtract(Ql).mod(p); - Vh = Vh.multiply(Vl).subtract(P.multiply(Ql)).mod(p); - Vl = Vl.multiply(Vl).subtract(Ql.shiftLeft(1)).mod(p); - } - } + for (var j = n - 1; j >= s + 1; --j) { + Ql = Ql.multiply(Qh).mod(p); + if (k.testBit(j)) { + Qh = Ql.multiply(Q).mod(p); + Uh = Uh.multiply(Vh).mod(p); + Vl = Vh.multiply(Vl).subtract(P.multiply(Ql)).mod(p); + Vh = Vh.multiply(Vh).subtract(Qh.shiftLeft(1)).mod(p); + } + else { + Qh = Ql; + Uh = Uh.multiply(Vl).subtract(Ql).mod(p); + Vh = Vh.multiply(Vl).subtract(P.multiply(Ql)).mod(p); + Vl = Vl.multiply(Vl).subtract(Ql.shiftLeft(1)).mod(p); + } + } - Ql = Ql.multiply(Qh).mod(p); - Qh = Ql.multiply(Q).mod(p); - Uh = Uh.multiply(Vl).subtract(Ql).mod(p); - Vl = Vh.multiply(Vl).subtract(P.multiply(Ql)).mod(p); - Ql = Ql.multiply(Qh).mod(p); + Ql = Ql.multiply(Qh).mod(p); + Qh = Ql.multiply(Q).mod(p); + Uh = Uh.multiply(Vl).subtract(Ql).mod(p); + Vl = Vh.multiply(Vl).subtract(P.multiply(Ql)).mod(p); + Ql = Ql.multiply(Qh).mod(p); - for (var j = 1; j <= s; ++j) { - Uh = Uh.multiply(Vl).mod(p); - Vl = Vl.multiply(Vl).subtract(Ql.shiftLeft(1)).mod(p); - Ql = Ql.multiply(Ql).mod(p); - } + for (var j = 1; j <= s; ++j) { + Uh = Uh.multiply(Vl).mod(p); + Vl = Vl.multiply(Vl).subtract(Ql.shiftLeft(1)).mod(p); + Ql = Ql.multiply(Ql).mod(p); + } - return [Uh, Vl]; - }; + return [Uh, Vl]; + }; - // ---------------- - // ECPointFp constructor - ec.PointFp = function (curve, x, y, z, compressed) { - this.curve = curve; - this.x = x; - this.y = y; - // Projective coordinates: either zinv == null or z * zinv == 1 - // z and zinv are just BigIntegers, not fieldElements - if (z == null) { - this.z = BigInteger.ONE; - } - else { - this.z = z; - } - this.zinv = null; - // compression flag - this.compressed = !!compressed; - }; + // ---------------- + // ECPointFp constructor + ec.PointFp = function (curve, x, y, z, compressed) { + this.curve = curve; + this.x = x; + this.y = y; + // Projective coordinates: either zinv == null or z * zinv == 1 + // z and zinv are just BigIntegers, not fieldElements + if (z == null) { + this.z = BigInteger.ONE; + } + else { + this.z = z; + } + this.zinv = null; + // compression flag + this.compressed = !!compressed; + }; - ec.PointFp.prototype.getX = function () { - if (this.zinv == null) { - this.zinv = this.z.modInverse(this.curve.q); - } - var r = this.x.toBigInteger().multiply(this.zinv); - this.curve.reduce(r); - return this.curve.fromBigInteger(r); - }; + ec.PointFp.prototype.getX = function () { + if (this.zinv == null) { + this.zinv = this.z.modInverse(this.curve.q); + } + var r = this.x.toBigInteger().multiply(this.zinv); + this.curve.reduce(r); + return this.curve.fromBigInteger(r); + }; - ec.PointFp.prototype.getY = function () { - if (this.zinv == null) { - this.zinv = this.z.modInverse(this.curve.q); - } - var r = this.y.toBigInteger().multiply(this.zinv); - this.curve.reduce(r); - return this.curve.fromBigInteger(r); - }; + ec.PointFp.prototype.getY = function () { + if (this.zinv == null) { + this.zinv = this.z.modInverse(this.curve.q); + } + var r = this.y.toBigInteger().multiply(this.zinv); + this.curve.reduce(r); + return this.curve.fromBigInteger(r); + }; - ec.PointFp.prototype.equals = function (other) { - if (other == this) return true; - if (this.isInfinity()) return other.isInfinity(); - if (other.isInfinity()) return this.isInfinity(); - var u, v; - // u = Y2 * Z1 - Y1 * Z2 - u = other.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(other.z)).mod(this.curve.q); - if (!u.equals(BigInteger.ZERO)) return false; - // v = X2 * Z1 - X1 * Z2 - v = other.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(other.z)).mod(this.curve.q); - return v.equals(BigInteger.ZERO); - }; + ec.PointFp.prototype.equals = function (other) { + if (other == this) return true; + if (this.isInfinity()) return other.isInfinity(); + if (other.isInfinity()) return this.isInfinity(); + var u, v; + // u = Y2 * Z1 - Y1 * Z2 + u = other.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(other.z)).mod(this.curve.q); + if (!u.equals(BigInteger.ZERO)) return false; + // v = X2 * Z1 - X1 * Z2 + v = other.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(other.z)).mod(this.curve.q); + return v.equals(BigInteger.ZERO); + }; - ec.PointFp.prototype.isInfinity = function () { - if ((this.x == null) && (this.y == null)) return true; - return this.z.equals(BigInteger.ZERO) && !this.y.toBigInteger().equals(BigInteger.ZERO); - }; + ec.PointFp.prototype.isInfinity = function () { + if ((this.x == null) && (this.y == null)) return true; + return this.z.equals(BigInteger.ZERO) && !this.y.toBigInteger().equals(BigInteger.ZERO); + }; - ec.PointFp.prototype.negate = function () { - return new ec.PointFp(this.curve, this.x, this.y.negate(), this.z); - }; + ec.PointFp.prototype.negate = function () { + return new ec.PointFp(this.curve, this.x, this.y.negate(), this.z); + }; - ec.PointFp.prototype.add = function (b) { - if (this.isInfinity()) return b; - if (b.isInfinity()) return this; + ec.PointFp.prototype.add = function (b) { + if (this.isInfinity()) return b; + if (b.isInfinity()) return this; - // u = Y2 * Z1 - Y1 * Z2 - var u = b.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(b.z)).mod(this.curve.q); - // v = X2 * Z1 - X1 * Z2 - var v = b.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(b.z)).mod(this.curve.q); + // u = Y2 * Z1 - Y1 * Z2 + var u = b.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(b.z)).mod(this.curve.q); + // v = X2 * Z1 - X1 * Z2 + var v = b.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(b.z)).mod(this.curve.q); - if (BigInteger.ZERO.equals(v)) { - if (BigInteger.ZERO.equals(u)) { - return this.twice(); // this == b, so double - } - return this.curve.getInfinity(); // this = -b, so infinity - } + if (BigInteger.ZERO.equals(v)) { + if (BigInteger.ZERO.equals(u)) { + return this.twice(); // this == b, so double + } + return this.curve.getInfinity(); // this = -b, so infinity + } - var THREE = new BigInteger("3"); - var x1 = this.x.toBigInteger(); - var y1 = this.y.toBigInteger(); - var x2 = b.x.toBigInteger(); - var y2 = b.y.toBigInteger(); + var THREE = new BigInteger("3"); + var x1 = this.x.toBigInteger(); + var y1 = this.y.toBigInteger(); + var x2 = b.x.toBigInteger(); + var y2 = b.y.toBigInteger(); - var v2 = v.square(); - var v3 = v2.multiply(v); - var x1v2 = x1.multiply(v2); - var zu2 = u.square().multiply(this.z); + var v2 = v.square(); + var v3 = v2.multiply(v); + var x1v2 = x1.multiply(v2); + var zu2 = u.square().multiply(this.z); - // x3 = v * (z2 * (z1 * u^2 - 2 * x1 * v^2) - v^3) - var x3 = zu2.subtract(x1v2.shiftLeft(1)).multiply(b.z).subtract(v3).multiply(v).mod(this.curve.q); - // y3 = z2 * (3 * x1 * u * v^2 - y1 * v^3 - z1 * u^3) + u * v^3 - var y3 = x1v2.multiply(THREE).multiply(u).subtract(y1.multiply(v3)).subtract(zu2.multiply(u)).multiply(b.z).add(u.multiply(v3)).mod(this.curve.q); - // z3 = v^3 * z1 * z2 - var z3 = v3.multiply(this.z).multiply(b.z).mod(this.curve.q); + // x3 = v * (z2 * (z1 * u^2 - 2 * x1 * v^2) - v^3) + var x3 = zu2.subtract(x1v2.shiftLeft(1)).multiply(b.z).subtract(v3).multiply(v).mod(this.curve.q); + // y3 = z2 * (3 * x1 * u * v^2 - y1 * v^3 - z1 * u^3) + u * v^3 + var y3 = x1v2.multiply(THREE).multiply(u).subtract(y1.multiply(v3)).subtract(zu2.multiply(u)).multiply(b.z).add(u.multiply(v3)).mod(this.curve.q); + // z3 = v^3 * z1 * z2 + var z3 = v3.multiply(this.z).multiply(b.z).mod(this.curve.q); - return new ec.PointFp(this.curve, this.curve.fromBigInteger(x3), this.curve.fromBigInteger(y3), z3); - }; + return new ec.PointFp(this.curve, this.curve.fromBigInteger(x3), this.curve.fromBigInteger(y3), z3); + }; - ec.PointFp.prototype.twice = function () { - if (this.isInfinity()) return this; - if (this.y.toBigInteger().signum() == 0) return this.curve.getInfinity(); + ec.PointFp.prototype.twice = function () { + if (this.isInfinity()) return this; + if (this.y.toBigInteger().signum() == 0) return this.curve.getInfinity(); - // TODO: optimized handling of constants - var THREE = new BigInteger("3"); - var x1 = this.x.toBigInteger(); - var y1 = this.y.toBigInteger(); + // TODO: optimized handling of constants + var THREE = new BigInteger("3"); + var x1 = this.x.toBigInteger(); + var y1 = this.y.toBigInteger(); - var y1z1 = y1.multiply(this.z); - var y1sqz1 = y1z1.multiply(y1).mod(this.curve.q); - var a = this.curve.a.toBigInteger(); + var y1z1 = y1.multiply(this.z); + var y1sqz1 = y1z1.multiply(y1).mod(this.curve.q); + var a = this.curve.a.toBigInteger(); - // w = 3 * x1^2 + a * z1^2 - var w = x1.square().multiply(THREE); - if (!BigInteger.ZERO.equals(a)) { - w = w.add(this.z.square().multiply(a)); - } - w = w.mod(this.curve.q); - //this.curve.reduce(w); - // x3 = 2 * y1 * z1 * (w^2 - 8 * x1 * y1^2 * z1) - var x3 = w.square().subtract(x1.shiftLeft(3).multiply(y1sqz1)).shiftLeft(1).multiply(y1z1).mod(this.curve.q); - // y3 = 4 * y1^2 * z1 * (3 * w * x1 - 2 * y1^2 * z1) - w^3 - var y3 = w.multiply(THREE).multiply(x1).subtract(y1sqz1.shiftLeft(1)).shiftLeft(2).multiply(y1sqz1).subtract(w.square().multiply(w)).mod(this.curve.q); - // z3 = 8 * (y1 * z1)^3 - var z3 = y1z1.square().multiply(y1z1).shiftLeft(3).mod(this.curve.q); + // w = 3 * x1^2 + a * z1^2 + var w = x1.square().multiply(THREE); + if (!BigInteger.ZERO.equals(a)) { + w = w.add(this.z.square().multiply(a)); + } + w = w.mod(this.curve.q); + //this.curve.reduce(w); + // x3 = 2 * y1 * z1 * (w^2 - 8 * x1 * y1^2 * z1) + var x3 = w.square().subtract(x1.shiftLeft(3).multiply(y1sqz1)).shiftLeft(1).multiply(y1z1).mod(this.curve.q); + // y3 = 4 * y1^2 * z1 * (3 * w * x1 - 2 * y1^2 * z1) - w^3 + var y3 = w.multiply(THREE).multiply(x1).subtract(y1sqz1.shiftLeft(1)).shiftLeft(2).multiply(y1sqz1).subtract(w.square().multiply(w)).mod(this.curve.q); + // z3 = 8 * (y1 * z1)^3 + var z3 = y1z1.square().multiply(y1z1).shiftLeft(3).mod(this.curve.q); - return new ec.PointFp(this.curve, this.curve.fromBigInteger(x3), this.curve.fromBigInteger(y3), z3); - }; + return new ec.PointFp(this.curve, this.curve.fromBigInteger(x3), this.curve.fromBigInteger(y3), z3); + }; - // Simple NAF (Non-Adjacent Form) multiplication algorithm - // TODO: modularize the multiplication algorithm - ec.PointFp.prototype.multiply = function (k) { - if (this.isInfinity()) return this; - if (k.signum() == 0) return this.curve.getInfinity(); + // Simple NAF (Non-Adjacent Form) multiplication algorithm + // TODO: modularize the multiplication algorithm + ec.PointFp.prototype.multiply = function (k) { + if (this.isInfinity()) return this; + if (k.signum() == 0) return this.curve.getInfinity(); - var e = k; - var h = e.multiply(new BigInteger("3")); + var e = k; + var h = e.multiply(new BigInteger("3")); - var neg = this.negate(); - var R = this; + var neg = this.negate(); + var R = this; - var i; - for (i = h.bitLength() - 2; i > 0; --i) { - R = R.twice(); + var i; + for (i = h.bitLength() - 2; i > 0; --i) { + R = R.twice(); - var hBit = h.testBit(i); - var eBit = e.testBit(i); + var hBit = h.testBit(i); + var eBit = e.testBit(i); - if (hBit != eBit) { - R = R.add(hBit ? this : neg); - } - } + if (hBit != eBit) { + R = R.add(hBit ? this : neg); + } + } - return R; - }; + return R; + }; - // Compute this*j + x*k (simultaneous multiplication) - ec.PointFp.prototype.multiplyTwo = function (j, x, k) { - var i; - if (j.bitLength() > k.bitLength()) - i = j.bitLength() - 1; - else - i = k.bitLength() - 1; + // Compute this*j + x*k (simultaneous multiplication) + ec.PointFp.prototype.multiplyTwo = function (j, x, k) { + var i; + if (j.bitLength() > k.bitLength()) + i = j.bitLength() - 1; + else + i = k.bitLength() - 1; - var R = this.curve.getInfinity(); - var both = this.add(x); - while (i >= 0) { - R = R.twice(); - if (j.testBit(i)) { - if (k.testBit(i)) { - R = R.add(both); - } - else { - R = R.add(this); - } - } - else { - if (k.testBit(i)) { - R = R.add(x); - } - } - --i; - } + var R = this.curve.getInfinity(); + var both = this.add(x); + while (i >= 0) { + R = R.twice(); + if (j.testBit(i)) { + if (k.testBit(i)) { + R = R.add(both); + } + else { + R = R.add(this); + } + } + else { + if (k.testBit(i)) { + R = R.add(x); + } + } + --i; + } - return R; - }; + return R; + }; - // patched by bitaddress.org and Casascius for use with Bitcoin.ECKey - // patched by coretechs to support compressed public keys - ec.PointFp.prototype.getEncoded = function (compressed) { - var x = this.getX().toBigInteger(); - var y = this.getY().toBigInteger(); - var len = 32; // integerToBytes will zero pad if integer is less than 32 bytes. 32 bytes length is required by the Bitcoin protocol. - var enc = ec.integerToBytes(x, len); + // patched by bitaddress.org and Casascius for use with Bitcoin.ECKey + // patched by coretechs to support compressed public keys + ec.PointFp.prototype.getEncoded = function (compressed) { + var x = this.getX().toBigInteger(); + var y = this.getY().toBigInteger(); + var len = 32; // integerToBytes will zero pad if integer is less than 32 bytes. 32 bytes length is required by the Bitcoin protocol. + var enc = ec.integerToBytes(x, len); - // when compressed prepend byte depending if y point is even or odd - if (compressed) { - if (y.isEven()) { - enc.unshift(0x02); - } - else { - enc.unshift(0x03); - } - } - else { - enc.unshift(0x04); - enc = enc.concat(ec.integerToBytes(y, len)); // uncompressed public key appends the bytes of the y point - } - return enc; - }; + // when compressed prepend byte depending if y point is even or odd + if (compressed) { + if (y.isEven()) { + enc.unshift(0x02); + } + else { + enc.unshift(0x03); + } + } + else { + enc.unshift(0x04); + enc = enc.concat(ec.integerToBytes(y, len)); // uncompressed public key appends the bytes of the y point + } + return enc; + }; - ec.PointFp.decodeFrom = function (curve, enc) { - var type = enc[0]; - var dataLen = enc.length - 1; + ec.PointFp.decodeFrom = function (curve, enc) { + var type = enc[0]; + var dataLen = enc.length - 1; - // Extract x and y as byte arrays - var xBa = enc.slice(1, 1 + dataLen / 2); - var yBa = enc.slice(1 + dataLen / 2, 1 + dataLen); + // Extract x and y as byte arrays + var xBa = enc.slice(1, 1 + dataLen / 2); + var yBa = enc.slice(1 + dataLen / 2, 1 + dataLen); - // Prepend zero byte to prevent interpretation as negative integer - xBa.unshift(0); - yBa.unshift(0); + // Prepend zero byte to prevent interpretation as negative integer + xBa.unshift(0); + yBa.unshift(0); - // Convert to BigIntegers - var x = new BigInteger(xBa); - var y = new BigInteger(yBa); + // Convert to BigIntegers + var x = new BigInteger(xBa); + var y = new BigInteger(yBa); - // Return point - return new ec.PointFp(curve, curve.fromBigInteger(x), curve.fromBigInteger(y)); - }; + // Return point + return new ec.PointFp(curve, curve.fromBigInteger(x), curve.fromBigInteger(y)); + }; - ec.PointFp.prototype.add2D = function (b) { - if (this.isInfinity()) return b; - if (b.isInfinity()) return this; + ec.PointFp.prototype.add2D = function (b) { + if (this.isInfinity()) return b; + if (b.isInfinity()) return this; - if (this.x.equals(b.x)) { - if (this.y.equals(b.y)) { - // this = b, i.e. this must be doubled - return this.twice(); - } - // this = -b, i.e. the result is the point at infinity - return this.curve.getInfinity(); - } + if (this.x.equals(b.x)) { + if (this.y.equals(b.y)) { + // this = b, i.e. this must be doubled + return this.twice(); + } + // this = -b, i.e. the result is the point at infinity + return this.curve.getInfinity(); + } - var x_x = b.x.subtract(this.x); - var y_y = b.y.subtract(this.y); - var gamma = y_y.divide(x_x); + var x_x = b.x.subtract(this.x); + var y_y = b.y.subtract(this.y); + var gamma = y_y.divide(x_x); - var x3 = gamma.square().subtract(this.x).subtract(b.x); - var y3 = gamma.multiply(this.x.subtract(x3)).subtract(this.y); + var x3 = gamma.square().subtract(this.x).subtract(b.x); + var y3 = gamma.multiply(this.x.subtract(x3)).subtract(this.y); - return new ec.PointFp(this.curve, x3, y3); - }; + return new ec.PointFp(this.curve, x3, y3); + }; - ec.PointFp.prototype.twice2D = function () { - if (this.isInfinity()) return this; - if (this.y.toBigInteger().signum() == 0) { - // if y1 == 0, then (x1, y1) == (x1, -y1) - // and hence this = -this and thus 2(x1, y1) == infinity - return this.curve.getInfinity(); - } + ec.PointFp.prototype.twice2D = function () { + if (this.isInfinity()) return this; + if (this.y.toBigInteger().signum() == 0) { + // if y1 == 0, then (x1, y1) == (x1, -y1) + // and hence this = -this and thus 2(x1, y1) == infinity + return this.curve.getInfinity(); + } - var TWO = this.curve.fromBigInteger(BigInteger.valueOf(2)); - var THREE = this.curve.fromBigInteger(BigInteger.valueOf(3)); - var gamma = this.x.square().multiply(THREE).add(this.curve.a).divide(this.y.multiply(TWO)); + var TWO = this.curve.fromBigInteger(BigInteger.valueOf(2)); + var THREE = this.curve.fromBigInteger(BigInteger.valueOf(3)); + var gamma = this.x.square().multiply(THREE).add(this.curve.a).divide(this.y.multiply(TWO)); - var x3 = gamma.square().subtract(this.x.multiply(TWO)); - var y3 = gamma.multiply(this.x.subtract(x3)).subtract(this.y); + var x3 = gamma.square().subtract(this.x.multiply(TWO)); + var y3 = gamma.multiply(this.x.subtract(x3)).subtract(this.y); - return new ec.PointFp(this.curve, x3, y3); - }; + return new ec.PointFp(this.curve, x3, y3); + }; - ec.PointFp.prototype.multiply2D = function (k) { - if (this.isInfinity()) return this; - if (k.signum() == 0) return this.curve.getInfinity(); + ec.PointFp.prototype.multiply2D = function (k) { + if (this.isInfinity()) return this; + if (k.signum() == 0) return this.curve.getInfinity(); - var e = k; - var h = e.multiply(new BigInteger("3")); + var e = k; + var h = e.multiply(new BigInteger("3")); - var neg = this.negate(); - var R = this; + var neg = this.negate(); + var R = this; - var i; - for (i = h.bitLength() - 2; i > 0; --i) { - R = R.twice(); + var i; + for (i = h.bitLength() - 2; i > 0; --i) { + R = R.twice(); - var hBit = h.testBit(i); - var eBit = e.testBit(i); + var hBit = h.testBit(i); + var eBit = e.testBit(i); - if (hBit != eBit) { - R = R.add2D(hBit ? this : neg); - } - } + if (hBit != eBit) { + R = R.add2D(hBit ? this : neg); + } + } - return R; - }; + return R; + }; + ec.PointFp.prototype.isOnCurve = function () { + var x = this.getX().toBigInteger(); + var y = this.getY().toBigInteger(); + var a = this.curve.getA().toBigInteger(); + var b = this.curve.getB().toBigInteger(); + var n = this.curve.getQ(); + var lhs = y.multiply(y).mod(n); + var rhs = x.multiply(x).multiply(x).add(a.multiply(x)).add(b).mod(n); + return lhs.equals(rhs); + }; - ec.PointFp.prototype.isOnCurve = function () { - var x = this.getX().toBigInteger(); - var y = this.getY().toBigInteger(); - var a = this.curve.getA().toBigInteger(); - var b = this.curve.getB().toBigInteger(); - var n = this.curve.getQ(); - var lhs = y.multiply(y).mod(n); - var rhs = x.multiply(x).multiply(x).add(a.multiply(x)).add(b).mod(n); - return lhs.equals(rhs); - }; - - ec.PointFp.prototype.toString = function () { - return '(' + this.getX().toBigInteger().toString() + ',' + this.getY().toBigInteger().toString() + ')'; - }; + ec.PointFp.prototype.toString = function () { + return '(' + this.getX().toBigInteger().toString() + ',' + this.getY().toBigInteger().toString() + ')'; + }; /** * Validate an elliptic curve point. * * See SEC 1, section 3.2.2.1: Elliptic Curve Public Key Validation Primitive */ - ec.PointFp.prototype.validate = function () { - var n = this.curve.getQ(); + ec.PointFp.prototype.validate = function () { + var n = this.curve.getQ(); - // Check Q != O - if (this.isInfinity()) { - throw new Error("Point is at infinity."); - } + // Check Q != O + if (this.isInfinity()) { + throw new Error("Point is at infinity."); + } - // Check coordinate bounds - var x = this.getX().toBigInteger(); - var y = this.getY().toBigInteger(); - if (x.compareTo(BigInteger.ONE) < 0 || x.compareTo(n.subtract(BigInteger.ONE)) > 0) { - throw new Error('x coordinate out of bounds'); - } - if (y.compareTo(BigInteger.ONE) < 0 || y.compareTo(n.subtract(BigInteger.ONE)) > 0) { - throw new Error('y coordinate out of bounds'); - } + // Check coordinate bounds + var x = this.getX().toBigInteger(); + var y = this.getY().toBigInteger(); + if (x.compareTo(BigInteger.ONE) < 0 || x.compareTo(n.subtract(BigInteger.ONE)) > 0) { + throw new Error('x coordinate out of bounds'); + } + if (y.compareTo(BigInteger.ONE) < 0 || y.compareTo(n.subtract(BigInteger.ONE)) > 0) { + throw new Error('y coordinate out of bounds'); + } - // Check y^2 = x^3 + ax + b (mod n) - if (!this.isOnCurve()) { - throw new Error("Point is not on the curve."); - } + // Check y^2 = x^3 + ax + b (mod n) + if (!this.isOnCurve()) { + throw new Error("Point is not on the curve."); + } - // Check nQ = 0 (Q is a scalar multiple of G) - if (this.multiply(n).isInfinity()) { - // TODO: This check doesn't work - fix. - throw new Error("Point is not a scalar multiple of G."); - } + // Check nQ = 0 (Q is a scalar multiple of G) + if (this.multiply(n).isInfinity()) { + // TODO: This check doesn't work - fix. + throw new Error("Point is not a scalar multiple of G."); + } - return true; - }; + return true; + }; + // ---------------- + // ECCurveFp constructor + ec.CurveFp = function (q, a, b) { + this.q = q; + this.a = this.fromBigInteger(a); + this.b = this.fromBigInteger(b); + this.infinity = new ec.PointFp(this, null, null); + this.reducer = new Barrett(this.q); + } + ec.CurveFp.prototype.getQ = function () { + return this.q; + }; + ec.CurveFp.prototype.getA = function () { + return this.a; + }; - // ---------------- - // ECCurveFp constructor - ec.CurveFp = function (q, a, b) { - this.q = q; - this.a = this.fromBigInteger(a); - this.b = this.fromBigInteger(b); - this.infinity = new ec.PointFp(this, null, null); - this.reducer = new Barrett(this.q); - } + ec.CurveFp.prototype.getB = function () { + return this.b; + }; - ec.CurveFp.prototype.getQ = function () { - return this.q; - }; + ec.CurveFp.prototype.equals = function (other) { + if (other == this) return true; + return (this.q.equals(other.q) && this.a.equals(other.a) && this.b.equals(other.b)); + }; - ec.CurveFp.prototype.getA = function () { - return this.a; - }; + ec.CurveFp.prototype.getInfinity = function () { + return this.infinity; + }; - ec.CurveFp.prototype.getB = function () { - return this.b; - }; + ec.CurveFp.prototype.fromBigInteger = function (x) { + return new ec.FieldElementFp(this.q, x); + }; - ec.CurveFp.prototype.equals = function (other) { - if (other == this) return true; - return (this.q.equals(other.q) && this.a.equals(other.a) && this.b.equals(other.b)); - }; + ec.CurveFp.prototype.reduce = function (x) { + this.reducer.reduce(x); + }; - ec.CurveFp.prototype.getInfinity = function () { - return this.infinity; - }; + // for now, work with hex strings because they're easier in JS + // compressed support added by bitaddress.org + ec.CurveFp.prototype.decodePointHex = function (s) { + var firstByte = parseInt(s.substr(0, 2), 16); + switch (firstByte) { // first byte + case 0: + return this.infinity; + case 2: // compressed + case 3: // compressed + var yTilde = firstByte & 1; + var xHex = s.substr(2, s.length - 2); + var X1 = new BigInteger(xHex, 16); + return this.decompressPoint(yTilde, X1); + case 4: // uncompressed + case 6: // hybrid + case 7: // hybrid + var len = (s.length - 2) / 2; + var xHex = s.substr(2, len); + var yHex = s.substr(len + 2, len); - ec.CurveFp.prototype.fromBigInteger = function (x) { - return new ec.FieldElementFp(this.q, x); - }; + return new ec.PointFp(this, + this.fromBigInteger(new BigInteger(xHex, 16)), + this.fromBigInteger(new BigInteger(yHex, 16))); - ec.CurveFp.prototype.reduce = function (x) { - this.reducer.reduce(x); - }; + default: // unsupported + return null; + } + }; - // for now, work with hex strings because they're easier in JS - // compressed support added by bitaddress.org - ec.CurveFp.prototype.decodePointHex = function (s) { - var firstByte = parseInt(s.substr(0, 2), 16); - switch (firstByte) { // first byte - case 0: - return this.infinity; - case 2: // compressed - case 3: // compressed - var yTilde = firstByte & 1; - var xHex = s.substr(2, s.length - 2); - var X1 = new BigInteger(xHex, 16); - return this.decompressPoint(yTilde, X1); - case 4: // uncompressed - case 6: // hybrid - case 7: // hybrid - var len = (s.length - 2) / 2; - var xHex = s.substr(2, len); - var yHex = s.substr(len + 2, len); - - return new ec.PointFp(this, - this.fromBigInteger(new BigInteger(xHex, 16)), - this.fromBigInteger(new BigInteger(yHex, 16))); - - default: // unsupported - return null; - } - }; - - ec.CurveFp.prototype.encodePointHex = function (p) { - if (p.isInfinity()) return "00"; - var xHex = p.getX().toBigInteger().toString(16); - var yHex = p.getY().toBigInteger().toString(16); - var oLen = this.getQ().toString(16).length; - if ((oLen % 2) != 0) oLen++; - while (xHex.length < oLen) { - xHex = "0" + xHex; - } - while (yHex.length < oLen) { - yHex = "0" + yHex; - } - return "04" + xHex + yHex; - }; + ec.CurveFp.prototype.encodePointHex = function (p) { + if (p.isInfinity()) return "00"; + var xHex = p.getX().toBigInteger().toString(16); + var yHex = p.getY().toBigInteger().toString(16); + var oLen = this.getQ().toString(16).length; + if ((oLen % 2) != 0) oLen++; + while (xHex.length < oLen) { + xHex = "0" + xHex; + } + while (yHex.length < oLen) { + yHex = "0" + yHex; + } + return "04" + xHex + yHex; + }; /* * Copyright (c) 2000 - 2011 The Legion Of The Bouncy Castle (http://www.bouncycastle.org) @@ -2537,84 +2523,84 @@ * Number yTilde * BigInteger X1 */ - ec.CurveFp.prototype.decompressPoint = function (yTilde, X1) { - var x = this.fromBigInteger(X1); - var alpha = x.multiply(x.square().add(this.getA())).add(this.getB()); - var beta = alpha.sqrt(); - // if we can't find a sqrt we haven't got a point on the curve - run! - if (beta == null) throw new Error("Invalid point compression"); - var betaValue = beta.toBigInteger(); - var bit0 = betaValue.testBit(0) ? 1 : 0; - if (bit0 != yTilde) { - // Use the other root - beta = this.fromBigInteger(this.getQ().subtract(betaValue)); - } - return new ec.PointFp(this, x, beta, null, true); - }; + ec.CurveFp.prototype.decompressPoint = function (yTilde, X1) { + var x = this.fromBigInteger(X1); + var alpha = x.multiply(x.square().add(this.getA())).add(this.getB()); + var beta = alpha.sqrt(); + // if we can't find a sqrt we haven't got a point on the curve - run! + if (beta == null) throw new Error("Invalid point compression"); + var betaValue = beta.toBigInteger(); + var bit0 = betaValue.testBit(0) ? 1 : 0; + if (bit0 != yTilde) { + // Use the other root + beta = this.fromBigInteger(this.getQ().subtract(betaValue)); + } + return new ec.PointFp(this, x, beta, null, true); + }; - ec.fromHex = function (s) { return new BigInteger(s, 16); }; + ec.fromHex = function (s) { return new BigInteger(s, 16); }; - ec.integerToBytes = function (i, len) { - var bytes = i.toByteArrayUnsigned(); - if (len < bytes.length) { - bytes = bytes.slice(bytes.length - len); - } else while (len > bytes.length) { - bytes.unshift(0); - } - return bytes; - }; + ec.integerToBytes = function (i, len) { + var bytes = i.toByteArrayUnsigned(); + if (len < bytes.length) { + bytes = bytes.slice(bytes.length - len); + } else while (len > bytes.length) { + bytes.unshift(0); + } + return bytes; + }; - // Named EC curves - // ---------------- - // X9ECParameters constructor - ec.X9Parameters = function (curve, g, n, h) { - this.curve = curve; - this.g = g; - this.n = n; - this.h = h; - } - ec.X9Parameters.prototype.getCurve = function () { return this.curve; }; - ec.X9Parameters.prototype.getG = function () { return this.g; }; - ec.X9Parameters.prototype.getN = function () { return this.n; }; - ec.X9Parameters.prototype.getH = function () { return this.h; }; + // Named EC curves + // ---------------- + // X9ECParameters constructor + ec.X9Parameters = function (curve, g, n, h) { + this.curve = curve; + this.g = g; + this.n = n; + this.h = h; + } + ec.X9Parameters.prototype.getCurve = function () { return this.curve; }; + ec.X9Parameters.prototype.getG = function () { return this.g; }; + ec.X9Parameters.prototype.getN = function () { return this.n; }; + ec.X9Parameters.prototype.getH = function () { return this.h; }; - // secp256k1 is the Curve used by Bitcoin - ec.secNamedCurves = { - // used by Bitcoin - "secp256k1": function () { - // p = 2^256 - 2^32 - 2^9 - 2^8 - 2^7 - 2^6 - 2^4 - 1 - var p = ec.fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F"); - var a = BigInteger.ZERO; - var b = ec.fromHex("7"); - var n = ec.fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141"); - var h = BigInteger.ONE; - var curve = new ec.CurveFp(p, a, b); - var G = curve.decodePointHex("04" - + "79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798" - + "483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8"); - return new ec.X9Parameters(curve, G, n, h); - } - }; + // secp256k1 is the Curve used by Bitcoin + ec.secNamedCurves = { + // used by Bitcoin + "secp256k1": function () { + // p = 2^256 - 2^32 - 2^9 - 2^8 - 2^7 - 2^6 - 2^4 - 1 + var p = ec.fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F"); + var a = BigInteger.ZERO; + var b = ec.fromHex("7"); + var n = ec.fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141"); + var h = BigInteger.ONE; + var curve = new ec.CurveFp(p, a, b); + var G = curve.decodePointHex("04" + + "79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798" + + "483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8"); + return new ec.X9Parameters(curve, G, n, h); + } + }; - // secp256k1 called by Bitcoin's ECKEY - ec.getSECCurveByName = function (name) { - if (ec.secNamedCurves[name] == undefined) return null; - return ec.secNamedCurves[name](); - } + // secp256k1 called by Bitcoin's ECKEY + ec.getSECCurveByName = function (name) { + if (ec.secNamedCurves[name] == undefined) return null; + return ec.secNamedCurves[name](); + } - if (typeof exports !== 'undefined') { - exports = module.exports = { - default: ec, - EllipticCurve: ec, - BigInteger: BigInteger - }; - } else { - this.ecbn = { - EllipticCurve: ec, - BigInteger: BigInteger - }; - } + if (typeof exports !== 'undefined') { + exports = module.exports = { + default: ec, + EllipticCurve: ec, + BigInteger: BigInteger + }; + } else { + this.ecbn = { + EllipticCurve: ec, + BigInteger: BigInteger + }; + } -}).call(this); \ No newline at end of file +}).call(this); diff --git a/crypto/api/bitcoin/jsbn.js b/crypto/api/bitcoin/jsbn.js index 0e306853..e3c323bd 100644 --- a/crypto/api/bitcoin/jsbn.js +++ b/crypto/api/bitcoin/jsbn.js @@ -1,1940 +1,1937 @@ (function () { - // Copyright (c) 2005 Tom Wu - // All Rights Reserved. - // See "LICENSE" for details. - - // Basic JavaScript BN library - subset useful for RSA encryption. - - // Bits per digit - var dbits; - - // JavaScript engine analysis - var canary = 0xdeadbeefcafe; - var j_lm = (canary & 0xffffff) == 0xefcafe; - - // (public) Constructor - function BigInteger(a, b, c) { - if (a != null) - if ('number' == typeof a) this.fromNumber(a, b, c); - else if (b == null && 'string' != typeof a) this.fromString(a, 256); - else this.fromString(a, b); - } - - // return new, unset BigInteger - function nbi() { - return new BigInteger(null); - } - - // am: Compute w_j += (x*this_i), propagate carries, - // c is initial carry, returns final carry. - // c < 3*dvalue, x < 2*dvalue, this_i < dvalue - // We need to select the fastest one that works in this environment. - - // am1: use a single mult and divide to get the high bits, - // max digit bits should be 26 because - // max internal value = 2*dvalue^2-2*dvalue (< 2^53) - function am1(i, x, w, j, c, n) { - while (--n >= 0) { - var v = x * this[i++] + w[j] + c; - c = Math.floor(v / 0x4000000); - w[j++] = v & 0x3ffffff; - } - return c; - } - // am2 avoids a big mult-and-extract completely. - // Max digit bits should be <= 30 because we do bitwise ops - // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) - function am2(i, x, w, j, c, n) { - var xl = x & 0x7fff, - xh = x >> 15; - while (--n >= 0) { - var l = this[i] & 0x7fff; - var h = this[i++] >> 15; - var m = xh * l + h * xl; - l = xl * l + ((m & 0x7fff) << 15) + w[j] + (c & 0x3fffffff); - c = (l >>> 30) + (m >>> 15) + xh * h + (c >>> 30); - w[j++] = l & 0x3fffffff; - } - return c; - } - // Alternately, set max digit bits to 28 since some - // browsers slow down when dealing with 32-bit numbers. - function am3(i, x, w, j, c, n) { - var xl = x & 0x3fff, - xh = x >> 14; - while (--n >= 0) { - var l = this[i] & 0x3fff; - var h = this[i++] >> 14; - var m = xh * l + h * xl; - l = xl * l + ((m & 0x3fff) << 14) + w[j] + c; - c = (l >> 28) + (m >> 14) + xh * h; - w[j++] = l & 0xfffffff; - } - return c; - } - var inBrowser = typeof navigator !== 'undefined'; - if (inBrowser && j_lm && navigator.appName == 'Microsoft Internet Explorer') { - BigInteger.prototype.am = am2; - dbits = 30; - } else if (inBrowser && j_lm && navigator.appName != 'Netscape') { - BigInteger.prototype.am = am1; - dbits = 26; - } else { - // Mozilla/Netscape seems to prefer am3 - BigInteger.prototype.am = am3; - dbits = 28; - } - - BigInteger.prototype.DB = dbits; - BigInteger.prototype.DM = (1 << dbits) - 1; - BigInteger.prototype.DV = 1 << dbits; - - var BI_FP = 52; - BigInteger.prototype.FV = Math.pow(2, BI_FP); - BigInteger.prototype.F1 = BI_FP - dbits; - BigInteger.prototype.F2 = 2 * dbits - BI_FP; - - // Digit conversions - var BI_RM = '0123456789abcdefghijklmnopqrstuvwxyz'; - var BI_RC = new Array(); - var rr, vv; - rr = '0'.charCodeAt(0); - for (vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv; - rr = 'a'.charCodeAt(0); - for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; - rr = 'A'.charCodeAt(0); - for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; - - function int2char(n) { - return BI_RM.charAt(n); - } - function intAt(s, i) { - var c = BI_RC[s.charCodeAt(i)]; - return c == null ? -1 : c; - } - - // (protected) copy this to r - function bnpCopyTo(r) { - for (var i = this.t - 1; i >= 0; --i) r[i] = this[i]; - r.t = this.t; - r.s = this.s; - } - - // (protected) set from integer value x, -DV <= x < DV - function bnpFromInt(x) { - this.t = 1; - this.s = x < 0 ? -1 : 0; - if (x > 0) this[0] = x; - else if (x < -1) this[0] = x + this.DV; - else this.t = 0; - } - - // return bigint initialized to value - function nbv(i) { - var r = nbi(); - r.fromInt(i); - return r; - } - - // (protected) set from string and radix - function bnpFromString(s, b) { - // Auto-detect string notations - if (!b && s.length >= 2 && s[0] === '0') { - var isDetected = true; - switch (s[1]) { - case 'x': // Hexadecimal notation - b = 16; - break; - case 'b': // Binary notation - b = 2; - break; - case 'o': // Octal notation - b = 8; - break; - default: - isDetected = false; - } - - // Remove the notation string if any has been detected - if (isDetected) { - s = s.substr(2); - } - } - - var k; - if (b == 16) k = 4; - else if (b == 8) k = 3; - else if (b == 256) k = 8; - // byte array - else if (b == 2) k = 1; - else if (b == 32) k = 5; - else if (b == 4) k = 2; - else { - this.fromRadix(s, b); - return; - } - this.t = 0; - this.s = 0; - var i = s.length, - mi = false, - sh = 0; - while (--i >= 0) { - var x = k == 8 ? s[i] & 0xff : intAt(s, i); - if (x < 0) { - if (s.charAt(i) == '-') mi = true; - continue; - } - mi = false; - if (sh == 0) this[this.t++] = x; - else if (sh + k > this.DB) { - this[this.t - 1] |= (x & ((1 << (this.DB - sh)) - 1)) << sh; - this[this.t++] = x >> (this.DB - sh); - } else this[this.t - 1] |= x << sh; - sh += k; - if (sh >= this.DB) sh -= this.DB; - } - if (k == 8 && (s[0] & 0x80) != 0) { - this.s = -1; - if (sh > 0) this[this.t - 1] |= ((1 << (this.DB - sh)) - 1) << sh; - } - this.clamp(); - if (mi) BigInteger.ZERO.subTo(this, this); - } - - // (protected) clamp off excess high words - function bnpClamp() { - var c = this.s & this.DM; - while (this.t > 0 && this[this.t - 1] == c) --this.t; - } - - // (public) return string representation in given radix - function bnToString(b) { - if (this.s < 0) return '-' + this.negate().toString(b); - var k; - if (b == 16) k = 4; - else if (b == 8) k = 3; - else if (b == 2) k = 1; - else if (b == 32) k = 5; - else if (b == 4) k = 2; - else return this.toRadix(b); - var km = (1 << k) - 1, - d, - m = false, - r = '', - i = this.t; - var p = this.DB - ((i * this.DB) % k); - if (i-- > 0) { - if (p < this.DB && (d = this[i] >> p) > 0) { - m = true; - r = int2char(d); - } - while (i >= 0) { - if (p < k) { - d = (this[i] & ((1 << p) - 1)) << (k - p); - d |= this[--i] >> (p += this.DB - k); - } else { - d = (this[i] >> (p -= k)) & km; - if (p <= 0) { - p += this.DB; - --i; - } - } - if (d > 0) m = true; - if (m) r += int2char(d); - } - } - return m ? r : '0'; - } - - // (public) -this - function bnNegate() { - var r = nbi(); - BigInteger.ZERO.subTo(this, r); - return r; - } - - // (public) |this| - function bnAbs() { - return this.s < 0 ? this.negate() : this; - } - - // (public) return + if this > a, - if this < a, 0 if equal - function bnCompareTo(a) { - var r = this.s - a.s; - if (r != 0) return r; - var i = this.t; - r = i - a.t; - if (r != 0) return this.s < 0 ? -r : r; - while (--i >= 0) if ((r = this[i] - a[i]) != 0) return r; - return 0; - } - - // returns bit length of the integer x - function nbits(x) { - var r = 1, - t; - if ((t = x >>> 16) != 0) { - x = t; - r += 16; - } - if ((t = x >> 8) != 0) { - x = t; - r += 8; - } - if ((t = x >> 4) != 0) { - x = t; - r += 4; - } - if ((t = x >> 2) != 0) { - x = t; - r += 2; - } - if ((t = x >> 1) != 0) { - x = t; - r += 1; - } - return r; - } - - // (public) return the number of bits in "this" - function bnBitLength() { - if (this.t <= 0) return 0; - return ( - this.DB * (this.t - 1) + nbits(this[this.t - 1] ^ (this.s & this.DM)) - ); - } - - // (protected) r = this << n*DB - function bnpDLShiftTo(n, r) { - var i; - for (i = this.t - 1; i >= 0; --i) r[i + n] = this[i]; - for (i = n - 1; i >= 0; --i) r[i] = 0; - r.t = this.t + n; - r.s = this.s; - } - - // (protected) r = this >> n*DB - function bnpDRShiftTo(n, r) { - for (var i = n; i < this.t; ++i) r[i - n] = this[i]; - r.t = Math.max(this.t - n, 0); - r.s = this.s; - } - - // (protected) r = this << n - function bnpLShiftTo(n, r) { - var bs = n % this.DB; - var cbs = this.DB - bs; - var bm = (1 << cbs) - 1; - var ds = Math.floor(n / this.DB), - c = (this.s << bs) & this.DM, - i; - for (i = this.t - 1; i >= 0; --i) { - r[i + ds + 1] = (this[i] >> cbs) | c; - c = (this[i] & bm) << bs; - } - for (i = ds - 1; i >= 0; --i) r[i] = 0; - r[ds] = c; - r.t = this.t + ds + 1; - r.s = this.s; - r.clamp(); - } - - // (protected) r = this >> n - function bnpRShiftTo(n, r) { - r.s = this.s; - var ds = Math.floor(n / this.DB); - if (ds >= this.t) { - r.t = 0; - return; - } - var bs = n % this.DB; - var cbs = this.DB - bs; - var bm = (1 << bs) - 1; - r[0] = this[ds] >> bs; - for (var i = ds + 1; i < this.t; ++i) { - r[i - ds - 1] |= (this[i] & bm) << cbs; - r[i - ds] = this[i] >> bs; - } - if (bs > 0) r[this.t - ds - 1] |= (this.s & bm) << cbs; - r.t = this.t - ds; - r.clamp(); - } - - // (protected) r = this - a - function bnpSubTo(a, r) { - var i = 0, - c = 0, - m = Math.min(a.t, this.t); - while (i < m) { - c += this[i] - a[i]; - r[i++] = c & this.DM; - c >>= this.DB; - } - if (a.t < this.t) { - c -= a.s; - while (i < this.t) { - c += this[i]; - r[i++] = c & this.DM; - c >>= this.DB; - } - c += this.s; - } else { - c += this.s; - while (i < a.t) { - c -= a[i]; - r[i++] = c & this.DM; - c >>= this.DB; - } - c -= a.s; - } - r.s = c < 0 ? -1 : 0; - if (c < -1) r[i++] = this.DV + c; - else if (c > 0) r[i++] = c; - r.t = i; - r.clamp(); - } - - // (protected) r = this * a, r != this,a (HAC 14.12) - // "this" should be the larger one if appropriate. - function bnpMultiplyTo(a, r) { - var x = this.abs(), - y = a.abs(); - var i = x.t; - r.t = i + y.t; - while (--i >= 0) r[i] = 0; - for (i = 0; i < y.t; ++i) r[i + x.t] = x.am(0, y[i], r, i, 0, x.t); - r.s = 0; - r.clamp(); - if (this.s != a.s) BigInteger.ZERO.subTo(r, r); - } - - // (protected) r = this^2, r != this (HAC 14.16) - function bnpSquareTo(r) { - var x = this.abs(); - var i = (r.t = 2 * x.t); - while (--i >= 0) r[i] = 0; - for (i = 0; i < x.t - 1; ++i) { - var c = x.am(i, x[i], r, 2 * i, 0, 1); - if ( - (r[i + x.t] += x.am(i + 1, 2 * x[i], r, 2 * i + 1, c, x.t - i - 1)) >= - x.DV - ) { - r[i + x.t] -= x.DV; - r[i + x.t + 1] = 1; - } - } - if (r.t > 0) r[r.t - 1] += x.am(i, x[i], r, 2 * i, 0, 1); - r.s = 0; - r.clamp(); - } - - // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) - // r != q, this != m. q or r may be null. - function bnpDivRemTo(m, q, r) { - var pm = m.abs(); - if (pm.t <= 0) return; - var pt = this.abs(); - if (pt.t < pm.t) { - if (q != null) q.fromInt(0); - if (r != null) this.copyTo(r); - return; - } - if (r == null) r = nbi(); - var y = nbi(), - ts = this.s, - ms = m.s; - var nsh = this.DB - nbits(pm[pm.t - 1]); // normalize modulus - if (nsh > 0) { - pm.lShiftTo(nsh, y); - pt.lShiftTo(nsh, r); - } else { - pm.copyTo(y); - pt.copyTo(r); - } - var ys = y.t; - var y0 = y[ys - 1]; - if (y0 == 0) return; - var yt = y0 * (1 << this.F1) + (ys > 1 ? y[ys - 2] >> this.F2 : 0); - var d1 = this.FV / yt, - d2 = (1 << this.F1) / yt, - e = 1 << this.F2; - var i = r.t, - j = i - ys, - t = q == null ? nbi() : q; - y.dlShiftTo(j, t); - if (r.compareTo(t) >= 0) { - r[r.t++] = 1; - r.subTo(t, r); - } - BigInteger.ONE.dlShiftTo(ys, t); - t.subTo(y, y); // "negative" y so we can replace sub with am later - while (y.t < ys) y[y.t++] = 0; - while (--j >= 0) { - // Estimate quotient digit - var qd = - r[--i] == y0 ? this.DM : Math.floor(r[i] * d1 + (r[i - 1] + e) * d2); - if ((r[i] += y.am(0, qd, r, j, 0, ys)) < qd) { - // Try it out - y.dlShiftTo(j, t); - r.subTo(t, r); - while (r[i] < --qd) r.subTo(t, r); - } - } - if (q != null) { - r.drShiftTo(ys, q); - if (ts != ms) BigInteger.ZERO.subTo(q, q); - } - r.t = ys; - r.clamp(); - if (nsh > 0) r.rShiftTo(nsh, r); // Denormalize remainder - if (ts < 0) BigInteger.ZERO.subTo(r, r); - } - - // (public) this mod a - function bnMod(a) { - var r = nbi(); - this.abs().divRemTo(a, null, r); - if (this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r, r); - return r; - } - - // Modular reduction using "classic" algorithm - function Classic(m) { - this.m = m; - } - function cConvert(x) { - if (x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m); - else return x; - } - function cRevert(x) { - return x; - } - function cReduce(x) { - x.divRemTo(this.m, null, x); - } - function cMulTo(x, y, r) { - x.multiplyTo(y, r); - this.reduce(r); - } - function cSqrTo(x, r) { - x.squareTo(r); - this.reduce(r); - } - - Classic.prototype.convert = cConvert; - Classic.prototype.revert = cRevert; - Classic.prototype.reduce = cReduce; - Classic.prototype.mulTo = cMulTo; - Classic.prototype.sqrTo = cSqrTo; - - // (protected) return "-1/this % 2^DB"; useful for Mont. reduction - // justification: - // xy == 1 (mod m) - // xy = 1+km - // xy(2-xy) = (1+km)(1-km) - // x[y(2-xy)] = 1-k^2m^2 - // x[y(2-xy)] == 1 (mod m^2) - // if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 - // should reduce x and y(2-xy) by m^2 at each step to keep size bounded. - // JS multiply "overflows" differently from C/C++, so care is needed here. - function bnpInvDigit() { - if (this.t < 1) return 0; - var x = this[0]; - if ((x & 1) == 0) return 0; - var y = x & 3; // y == 1/x mod 2^2 - y = (y * (2 - (x & 0xf) * y)) & 0xf; // y == 1/x mod 2^4 - y = (y * (2 - (x & 0xff) * y)) & 0xff; // y == 1/x mod 2^8 - y = (y * (2 - (((x & 0xffff) * y) & 0xffff))) & 0xffff; // y == 1/x mod 2^16 - // last step - calculate inverse mod DV directly; - // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints - y = (y * (2 - ((x * y) % this.DV))) % this.DV; // y == 1/x mod 2^dbits - // we really want the negative inverse, and -DV < y < DV - return y > 0 ? this.DV - y : -y; - } - - // Montgomery reduction - function Montgomery(m) { - this.m = m; - this.mp = m.invDigit(); - this.mpl = this.mp & 0x7fff; - this.mph = this.mp >> 15; - this.um = (1 << (m.DB - 15)) - 1; - this.mt2 = 2 * m.t; - } - - // xR mod m - function montConvert(x) { - var r = nbi(); - x.abs().dlShiftTo(this.m.t, r); - r.divRemTo(this.m, null, r); - if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r, r); - return r; - } - - // x/R mod m - function montRevert(x) { - var r = nbi(); - x.copyTo(r); - this.reduce(r); - return r; - } - - // x = x/R mod m (HAC 14.32) - function montReduce(x) { - while ( - x.t <= this.mt2 // pad x so am has enough room later - ) - x[x.t++] = 0; - for (var i = 0; i < this.m.t; ++i) { - // faster way of calculating u0 = x[i]*mp mod DV - var j = x[i] & 0x7fff; - var u0 = - (j * this.mpl + - (((j * this.mph + (x[i] >> 15) * this.mpl) & this.um) << 15)) & - x.DM; - // use am to combine the multiply-shift-add into one call - j = i + this.m.t; - x[j] += this.m.am(0, u0, x, i, 0, this.m.t); - // propagate carry - while (x[j] >= x.DV) { - x[j] -= x.DV; - x[++j]++; - } - } - x.clamp(); - x.drShiftTo(this.m.t, x); - if (x.compareTo(this.m) >= 0) x.subTo(this.m, x); - } - - // r = "x^2/R mod m"; x != r - function montSqrTo(x, r) { - x.squareTo(r); - this.reduce(r); - } - - // r = "xy/R mod m"; x,y != r - function montMulTo(x, y, r) { - x.multiplyTo(y, r); - this.reduce(r); - } - - Montgomery.prototype.convert = montConvert; - Montgomery.prototype.revert = montRevert; - Montgomery.prototype.reduce = montReduce; - Montgomery.prototype.mulTo = montMulTo; - Montgomery.prototype.sqrTo = montSqrTo; - - // (protected) true iff this is even - function bnpIsEven() { - return (this.t > 0 ? this[0] & 1 : this.s) == 0; - } - - // (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79) - function bnpExp(e, z) { - if (e > 0xffffffff || e < 1) return BigInteger.ONE; - var r = nbi(), - r2 = nbi(), - g = z.convert(this), - i = nbits(e) - 1; - g.copyTo(r); - while (--i >= 0) { - z.sqrTo(r, r2); - if ((e & (1 << i)) > 0) z.mulTo(r2, g, r); - else { - var t = r; - r = r2; - r2 = t; - } - } - return z.revert(r); - } - - // (public) this^e % m, 0 <= e < 2^32 - function bnModPowInt(e, m) { - var z; - if (e < 256 || m.isEven()) z = new Classic(m); - else z = new Montgomery(m); - return this.exp(e, z); - } - - // protected - BigInteger.prototype.copyTo = bnpCopyTo; - BigInteger.prototype.fromInt = bnpFromInt; - BigInteger.prototype.fromString = bnpFromString; - BigInteger.prototype.clamp = bnpClamp; - BigInteger.prototype.dlShiftTo = bnpDLShiftTo; - BigInteger.prototype.drShiftTo = bnpDRShiftTo; - BigInteger.prototype.lShiftTo = bnpLShiftTo; - BigInteger.prototype.rShiftTo = bnpRShiftTo; - BigInteger.prototype.subTo = bnpSubTo; - BigInteger.prototype.multiplyTo = bnpMultiplyTo; - BigInteger.prototype.squareTo = bnpSquareTo; - BigInteger.prototype.divRemTo = bnpDivRemTo; - BigInteger.prototype.invDigit = bnpInvDigit; - BigInteger.prototype.isEven = bnpIsEven; - BigInteger.prototype.exp = bnpExp; - - // public - BigInteger.prototype.toString = bnToString; - BigInteger.prototype.negate = bnNegate; - BigInteger.prototype.abs = bnAbs; - BigInteger.prototype.compareTo = bnCompareTo; - BigInteger.prototype.bitLength = bnBitLength; - BigInteger.prototype.mod = bnMod; - BigInteger.prototype.modPowInt = bnModPowInt; - - // "constants" - BigInteger.ZERO = nbv(0); - BigInteger.ONE = nbv(1); - BigInteger.valueOf = nbv; - - // Copyright (c) 2005-2009 Tom Wu - // All Rights Reserved. - // See "LICENSE" for details. - - // Extended JavaScript BN functions, required for RSA private ops. - - // Version 1.1: new BigInteger("0", 10) returns "proper" zero - // Version 1.2: square() API, isProbablePrime fix - - // (public) - function bnClone() { - var r = nbi(); - this.copyTo(r); - return r; - } - - // (public) return value as integer - function bnIntValue() { - if (this.s < 0) { - if (this.t == 1) return this[0] - this.DV; - else if (this.t == 0) return -1; - } else if (this.t == 1) return this[0]; - else if (this.t == 0) return 0; - // assumes 16 < DB < 32 - return ((this[1] & ((1 << (32 - this.DB)) - 1)) << this.DB) | this[0]; - } - - // (public) return value as byte - function bnByteValue() { - return this.t == 0 ? this.s : (this[0] << 24) >> 24; - } - - // (public) return value as short (assumes DB>=16) - function bnShortValue() { - return this.t == 0 ? this.s : (this[0] << 16) >> 16; - } - - // (protected) return x s.t. r^x < DV - function bnpChunkSize(r) { - return Math.floor((Math.LN2 * this.DB) / Math.log(r)); - } - - // (public) 0 if this == 0, 1 if this > 0 - function bnSigNum() { - if (this.s < 0) return -1; - else if (this.t <= 0 || (this.t == 1 && this[0] <= 0)) return 0; - else return 1; - } - - // (protected) convert to radix string - function bnpToRadix(b) { - if (b == null) b = 10; - if (this.signum() == 0 || b < 2 || b > 36) return '0'; - var cs = this.chunkSize(b); - var a = Math.pow(b, cs); - var d = nbv(a), - y = nbi(), - z = nbi(), - r = ''; - this.divRemTo(d, y, z); - while (y.signum() > 0) { - r = (a + z.intValue()).toString(b).substr(1) + r; - y.divRemTo(d, y, z); - } - return z.intValue().toString(b) + r; - } - - // (protected) convert from radix string - function bnpFromRadix(s, b) { - this.fromInt(0); - if (b == null) b = 10; - var cs = this.chunkSize(b); - var d = Math.pow(b, cs), - mi = false, - j = 0, - w = 0; - for (var i = 0; i < s.length; ++i) { - var x = intAt(s, i); - if (x < 0) { - if (s.charAt(i) == '-' && this.signum() == 0) mi = true; - continue; - } - w = b * w + x; - if (++j >= cs) { - this.dMultiply(d); - this.dAddOffset(w, 0); - j = 0; - w = 0; - } - } - if (j > 0) { - this.dMultiply(Math.pow(b, j)); - this.dAddOffset(w, 0); - } - if (mi) BigInteger.ZERO.subTo(this, this); - } - - // (protected) alternate constructor - function bnpFromNumber(a, b, c) { - if ('number' == typeof b) { - // new BigInteger(int,int,RNG) - if (a < 2) this.fromInt(1); - else { - this.fromNumber(a, c); - if (!this.testBit(a - 1)) - // force MSB set - this.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, this); - if (this.isEven()) this.dAddOffset(1, 0); // force odd - while (!this.isProbablePrime(b)) { - this.dAddOffset(2, 0); - if (this.bitLength() > a) - this.subTo(BigInteger.ONE.shiftLeft(a - 1), this); - } - } - } else { - // new BigInteger(int,RNG) - var x = new Array(), - t = a & 7; - x.length = (a >> 3) + 1; - b.nextBytes(x); - if (t > 0) x[0] &= (1 << t) - 1; - else x[0] = 0; - this.fromString(x, 256); - } - } - - // (public) convert to bigendian byte array - function bnToByteArray() { - var i = this.t, - r = new Array(); - r[0] = this.s; - var p = this.DB - ((i * this.DB) % 8), - d, - k = 0; - if (i-- > 0) { - if (p < this.DB && (d = this[i] >> p) != (this.s & this.DM) >> p) - r[k++] = d | (this.s << (this.DB - p)); - while (i >= 0) { - if (p < 8) { - d = (this[i] & ((1 << p) - 1)) << (8 - p); - d |= this[--i] >> (p += this.DB - 8); - } else { - d = (this[i] >> (p -= 8)) & 0xff; - if (p <= 0) { - p += this.DB; - --i; - } - } - if ((d & 0x80) != 0) d |= -256; - if (k == 0 && (this.s & 0x80) != (d & 0x80)) ++k; - if (k > 0 || d != this.s) r[k++] = d; - } - } - return r; - } - - function bnEquals(a) { - return this.compareTo(a) == 0; - } - function bnMin(a) { - return this.compareTo(a) < 0 ? this : a; - } - function bnMax(a) { - return this.compareTo(a) > 0 ? this : a; - } - - // (protected) r = this op a (bitwise) - function bnpBitwiseTo(a, op, r) { - var i, - f, - m = Math.min(a.t, this.t); - for (i = 0; i < m; ++i) r[i] = op(this[i], a[i]); - if (a.t < this.t) { - f = a.s & this.DM; - for (i = m; i < this.t; ++i) r[i] = op(this[i], f); - r.t = this.t; - } else { - f = this.s & this.DM; - for (i = m; i < a.t; ++i) r[i] = op(f, a[i]); - r.t = a.t; - } - r.s = op(this.s, a.s); - r.clamp(); - } - - // (public) this & a - function op_and(x, y) { - return x & y; - } - function bnAnd(a) { - var r = nbi(); - this.bitwiseTo(a, op_and, r); - return r; - } - - // (public) this | a - function op_or(x, y) { - return x | y; - } - function bnOr(a) { - var r = nbi(); - this.bitwiseTo(a, op_or, r); - return r; - } - - // (public) this ^ a - function op_xor(x, y) { - return x ^ y; - } - function bnXor(a) { - var r = nbi(); - this.bitwiseTo(a, op_xor, r); - return r; - } - - // (public) this & ~a - function op_andnot(x, y) { - return x & ~y; - } - function bnAndNot(a) { - var r = nbi(); - this.bitwiseTo(a, op_andnot, r); - return r; - } - - // (public) ~this - function bnNot() { - var r = nbi(); - for (var i = 0; i < this.t; ++i) r[i] = this.DM & ~this[i]; - r.t = this.t; - r.s = ~this.s; - return r; - } - - // (public) this << n - function bnShiftLeft(n) { - var r = nbi(); - if (n < 0) this.rShiftTo(-n, r); - else this.lShiftTo(n, r); - return r; - } - - // (public) this >> n - function bnShiftRight(n) { - var r = nbi(); - if (n < 0) this.lShiftTo(-n, r); - else this.rShiftTo(n, r); - return r; - } - - // return index of lowest 1-bit in x, x < 2^31 - function lbit(x) { - if (x == 0) return -1; - var r = 0; - if ((x & 0xffff) == 0) { - x >>= 16; - r += 16; - } - if ((x & 0xff) == 0) { - x >>= 8; - r += 8; - } - if ((x & 0xf) == 0) { - x >>= 4; - r += 4; - } - if ((x & 3) == 0) { - x >>= 2; - r += 2; - } - if ((x & 1) == 0) ++r; - return r; - } - - // (public) returns index of lowest 1-bit (or -1 if none) - function bnGetLowestSetBit() { - for (var i = 0; i < this.t; ++i) - if (this[i] != 0) return i * this.DB + lbit(this[i]); - if (this.s < 0) return this.t * this.DB; - return -1; - } - - // return number of 1 bits in x - function cbit(x) { - var r = 0; - while (x != 0) { - x &= x - 1; - ++r; - } - return r; - } - - // (public) return number of set bits - function bnBitCount() { - var r = 0, - x = this.s & this.DM; - for (var i = 0; i < this.t; ++i) r += cbit(this[i] ^ x); - return r; - } - - // (public) true iff nth bit is set - function bnTestBit(n) { - var j = Math.floor(n / this.DB); - if (j >= this.t) return this.s != 0; - return (this[j] & (1 << n % this.DB)) != 0; - } - - // (protected) this op (1<>= this.DB; - } - if (a.t < this.t) { - c += a.s; - while (i < this.t) { - c += this[i]; - r[i++] = c & this.DM; - c >>= this.DB; - } - c += this.s; - } else { - c += this.s; - while (i < a.t) { - c += a[i]; - r[i++] = c & this.DM; - c >>= this.DB; - } - c += a.s; - } - r.s = c < 0 ? -1 : 0; - if (c > 0) r[i++] = c; - else if (c < -1) r[i++] = this.DV + c; - r.t = i; - r.clamp(); - } - - // (public) this + a - function bnAdd(a) { - var r = nbi(); - this.addTo(a, r); - return r; - } - - // (public) this - a - function bnSubtract(a) { - var r = nbi(); - this.subTo(a, r); - return r; - } - - // (public) this * a - function bnMultiply(a) { - var r = nbi(); - this.multiplyTo(a, r); - return r; - } - - // (public) this^2 - function bnSquare() { - var r = nbi(); - this.squareTo(r); - return r; - } - - // (public) this / a - function bnDivide(a) { - var r = nbi(); - this.divRemTo(a, r, null); - return r; - } - - // (public) this % a - function bnRemainder(a) { - var r = nbi(); - this.divRemTo(a, null, r); - return r; - } - - // (public) [this/a,this%a] - function bnDivideAndRemainder(a) { - var q = nbi(), - r = nbi(); - this.divRemTo(a, q, r); - return new Array(q, r); - } - - // (protected) this *= n, this >= 0, 1 < n < DV - function bnpDMultiply(n) { - this[this.t] = this.am(0, n - 1, this, 0, 0, this.t); - ++this.t; - this.clamp(); - } - - // (protected) this += n << w words, this >= 0 - function bnpDAddOffset(n, w) { - if (n == 0) return; - while (this.t <= w) this[this.t++] = 0; - this[w] += n; - while (this[w] >= this.DV) { - this[w] -= this.DV; - if (++w >= this.t) this[this.t++] = 0; - ++this[w]; - } - } - - // A "null" reducer - function NullExp() { } - function nNop(x) { - return x; - } - function nMulTo(x, y, r) { - x.multiplyTo(y, r); - } - function nSqrTo(x, r) { - x.squareTo(r); - } - - NullExp.prototype.convert = nNop; - NullExp.prototype.revert = nNop; - NullExp.prototype.mulTo = nMulTo; - NullExp.prototype.sqrTo = nSqrTo; - - // (public) this^e - function bnPow(e) { - return this.exp(e, new NullExp()); - } - - // (protected) r = lower n words of "this * a", a.t <= n - // "this" should be the larger one if appropriate. - function bnpMultiplyLowerTo(a, n, r) { - var i = Math.min(this.t + a.t, n); - r.s = 0; // assumes a,this >= 0 - r.t = i; - while (i > 0) r[--i] = 0; - var j; - for (j = r.t - this.t; i < j; ++i) - r[i + this.t] = this.am(0, a[i], r, i, 0, this.t); - for (j = Math.min(a.t, n); i < j; ++i) this.am(0, a[i], r, i, 0, n - i); - r.clamp(); - } - - // (protected) r = "this * a" without lower n words, n > 0 - // "this" should be the larger one if appropriate. - function bnpMultiplyUpperTo(a, n, r) { - --n; - var i = (r.t = this.t + a.t - n); - r.s = 0; // assumes a,this >= 0 - while (--i >= 0) r[i] = 0; - for (i = Math.max(n - this.t, 0); i < a.t; ++i) - r[this.t + i - n] = this.am(n - i, a[i], r, 0, 0, this.t + i - n); - r.clamp(); - r.drShiftTo(1, r); - } - - // Barrett modular reduction - function Barrett(m) { - // setup Barrett - this.r2 = nbi(); - this.q3 = nbi(); - BigInteger.ONE.dlShiftTo(2 * m.t, this.r2); - this.mu = this.r2.divide(m); - this.m = m; - } - - function barrettConvert(x) { - if (x.s < 0 || x.t > 2 * this.m.t) return x.mod(this.m); - else if (x.compareTo(this.m) < 0) return x; - else { - var r = nbi(); - x.copyTo(r); - this.reduce(r); - return r; - } - } - - function barrettRevert(x) { - return x; - } - - // x = x mod m (HAC 14.42) - function barrettReduce(x) { - x.drShiftTo(this.m.t - 1, this.r2); - if (x.t > this.m.t + 1) { - x.t = this.m.t + 1; - x.clamp(); - } - this.mu.multiplyUpperTo(this.r2, this.m.t + 1, this.q3); - this.m.multiplyLowerTo(this.q3, this.m.t + 1, this.r2); - while (x.compareTo(this.r2) < 0) x.dAddOffset(1, this.m.t + 1); - x.subTo(this.r2, x); - while (x.compareTo(this.m) >= 0) x.subTo(this.m, x); - } - - // r = x^2 mod m; x != r - function barrettSqrTo(x, r) { - x.squareTo(r); - this.reduce(r); - } - - // r = x*y mod m; x,y != r - function barrettMulTo(x, y, r) { - x.multiplyTo(y, r); - this.reduce(r); - } - - Barrett.prototype.convert = barrettConvert; - Barrett.prototype.revert = barrettRevert; - Barrett.prototype.reduce = barrettReduce; - Barrett.prototype.mulTo = barrettMulTo; - Barrett.prototype.sqrTo = barrettSqrTo; - - // (public) this^e % m (HAC 14.85) - function bnModPow(e, m) { - var i = e.bitLength(), - k, - r = nbv(1), - z; - if (i <= 0) return r; - else if (i < 18) k = 1; - else if (i < 48) k = 3; - else if (i < 144) k = 4; - else if (i < 768) k = 5; - else k = 6; - if (i < 8) z = new Classic(m); - else if (m.isEven()) z = new Barrett(m); - else z = new Montgomery(m); - - // precomputation - var g = new Array(), - n = 3, - k1 = k - 1, - km = (1 << k) - 1; - g[1] = z.convert(this); - if (k > 1) { - var g2 = nbi(); - z.sqrTo(g[1], g2); - while (n <= km) { - g[n] = nbi(); - z.mulTo(g2, g[n - 2], g[n]); - n += 2; - } - } - - var j = e.t - 1, - w, - is1 = true, - r2 = nbi(), - t; - i = nbits(e[j]) - 1; - while (j >= 0) { - if (i >= k1) w = (e[j] >> (i - k1)) & km; - else { - w = (e[j] & ((1 << (i + 1)) - 1)) << (k1 - i); - if (j > 0) w |= e[j - 1] >> (this.DB + i - k1); - } - - n = k; - while ((w & 1) == 0) { - w >>= 1; - --n; - } - if ((i -= n) < 0) { - i += this.DB; - --j; - } - if (is1) { - // ret == 1, don't bother squaring or multiplying it - g[w].copyTo(r); - is1 = false; - } else { - while (n > 1) { - z.sqrTo(r, r2); - z.sqrTo(r2, r); - n -= 2; - } - if (n > 0) z.sqrTo(r, r2); - else { - t = r; - r = r2; - r2 = t; - } - z.mulTo(r2, g[w], r); - } - - while (j >= 0 && (e[j] & (1 << i)) == 0) { - z.sqrTo(r, r2); - t = r; - r = r2; - r2 = t; - if (--i < 0) { - i = this.DB - 1; - --j; - } - } - } - return z.revert(r); - } - - // (public) gcd(this,a) (HAC 14.54) - function bnGCD(a) { - var x = this.s < 0 ? this.negate() : this.clone(); - var y = a.s < 0 ? a.negate() : a.clone(); - if (x.compareTo(y) < 0) { - var t = x; - x = y; - y = t; - } - var i = x.getLowestSetBit(), - g = y.getLowestSetBit(); - if (g < 0) return x; - if (i < g) g = i; - if (g > 0) { - x.rShiftTo(g, x); - y.rShiftTo(g, y); - } - while (x.signum() > 0) { - if ((i = x.getLowestSetBit()) > 0) x.rShiftTo(i, x); - if ((i = y.getLowestSetBit()) > 0) y.rShiftTo(i, y); - if (x.compareTo(y) >= 0) { - x.subTo(y, x); - x.rShiftTo(1, x); - } else { - y.subTo(x, y); - y.rShiftTo(1, y); - } - } - if (g > 0) y.lShiftTo(g, y); - return y; - } - - // (protected) this % n, n < 2^26 - function bnpModInt(n) { - if (n <= 0) return 0; - var d = this.DV % n, - r = this.s < 0 ? n - 1 : 0; - if (this.t > 0) - if (d == 0) r = this[0] % n; - else for (var i = this.t - 1; i >= 0; --i) r = (d * r + this[i]) % n; - return r; - } - - // (public) 1/this % m (HAC 14.61) - function bnModInverse(m) { - var ac = m.isEven(); - if ((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO; - var u = m.clone(), - v = this.clone(); - var a = nbv(1), - b = nbv(0), - c = nbv(0), - d = nbv(1); - while (u.signum() != 0) { - while (u.isEven()) { - u.rShiftTo(1, u); - if (ac) { - if (!a.isEven() || !b.isEven()) { - a.addTo(this, a); - b.subTo(m, b); - } - a.rShiftTo(1, a); - } else if (!b.isEven()) b.subTo(m, b); - b.rShiftTo(1, b); - } - while (v.isEven()) { - v.rShiftTo(1, v); - if (ac) { - if (!c.isEven() || !d.isEven()) { - c.addTo(this, c); - d.subTo(m, d); - } - c.rShiftTo(1, c); - } else if (!d.isEven()) d.subTo(m, d); - d.rShiftTo(1, d); - } - if (u.compareTo(v) >= 0) { - u.subTo(v, u); - if (ac) a.subTo(c, a); - b.subTo(d, b); - } else { - v.subTo(u, v); - if (ac) c.subTo(a, c); - d.subTo(b, d); - } - } - if (v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO; - if (d.compareTo(m) >= 0) return d.subtract(m); - if (d.signum() < 0) d.addTo(m, d); - else return d; - if (d.signum() < 0) return d.add(m); - else return d; - } - - var lowprimes = [ - 2, - 3, - 5, - 7, - 11, - 13, - 17, - 19, - 23, - 29, - 31, - 37, - 41, - 43, - 47, - 53, - 59, - 61, - 67, - 71, - 73, - 79, - 83, - 89, - 97, - 101, - 103, - 107, - 109, - 113, - 127, - 131, - 137, - 139, - 149, - 151, - 157, - 163, - 167, - 173, - 179, - 181, - 191, - 193, - 197, - 199, - 211, - 223, - 227, - 229, - 233, - 239, - 241, - 251, - 257, - 263, - 269, - 271, - 277, - 281, - 283, - 293, - 307, - 311, - 313, - 317, - 331, - 337, - 347, - 349, - 353, - 359, - 367, - 373, - 379, - 383, - 389, - 397, - 401, - 409, - 419, - 421, - 431, - 433, - 439, - 443, - 449, - 457, - 461, - 463, - 467, - 479, - 487, - 491, - 499, - 503, - 509, - 521, - 523, - 541, - 547, - 557, - 563, - 569, - 571, - 577, - 587, - 593, - 599, - 601, - 607, - 613, - 617, - 619, - 631, - 641, - 643, - 647, - 653, - 659, - 661, - 673, - 677, - 683, - 691, - 701, - 709, - 719, - 727, - 733, - 739, - 743, - 751, - 757, - 761, - 769, - 773, - 787, - 797, - 809, - 811, - 821, - 823, - 827, - 829, - 839, - 853, - 857, - 859, - 863, - 877, - 881, - 883, - 887, - 907, - 911, - 919, - 929, - 937, - 941, - 947, - 953, - 967, - 971, - 977, - 983, - 991, - 997, - ]; - var lplim = (1 << 26) / lowprimes[lowprimes.length - 1]; - - // (public) test primality with certainty >= 1-.5^t - function bnIsProbablePrime(t) { - var i, - x = this.abs(); - if (x.t == 1 && x[0] <= lowprimes[lowprimes.length - 1]) { - for (i = 0; i < lowprimes.length; ++i) - if (x[0] == lowprimes[i]) return true; - return false; - } - if (x.isEven()) return false; - i = 1; - while (i < lowprimes.length) { - var m = lowprimes[i], - j = i + 1; - while (j < lowprimes.length && m < lplim) m *= lowprimes[j++]; - m = x.modInt(m); - while (i < j) if (m % lowprimes[i++] == 0) return false; - } - return x.millerRabin(t); - } - - // (protected) true if probably prime (HAC 4.24, Miller-Rabin) - function bnpMillerRabin(t) { - var n1 = this.subtract(BigInteger.ONE); - var k = n1.getLowestSetBit(); - if (k <= 0) return false; - var r = n1.shiftRight(k); - t = (t + 1) >> 1; - if (t > lowprimes.length) t = lowprimes.length; - var a = nbi(); - for (var i = 0; i < t; ++i) { - //Pick bases at random, instead of starting at 2 - a.fromInt(lowprimes[Math.floor(Math.random() * lowprimes.length)]); - var y = a.modPow(r, this); - if (y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { - var j = 1; - while (j++ < k && y.compareTo(n1) != 0) { - y = y.modPowInt(2, this); - if (y.compareTo(BigInteger.ONE) == 0) return false; - } - if (y.compareTo(n1) != 0) return false; - } - } - return true; - } - - // protected - BigInteger.prototype.chunkSize = bnpChunkSize; - BigInteger.prototype.toRadix = bnpToRadix; - BigInteger.prototype.fromRadix = bnpFromRadix; - BigInteger.prototype.fromNumber = bnpFromNumber; - BigInteger.prototype.bitwiseTo = bnpBitwiseTo; - BigInteger.prototype.changeBit = bnpChangeBit; - BigInteger.prototype.addTo = bnpAddTo; - BigInteger.prototype.dMultiply = bnpDMultiply; - BigInteger.prototype.dAddOffset = bnpDAddOffset; - BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo; - BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo; - BigInteger.prototype.modInt = bnpModInt; - BigInteger.prototype.millerRabin = bnpMillerRabin; - - // public - BigInteger.prototype.clone = bnClone; - BigInteger.prototype.intValue = bnIntValue; - BigInteger.prototype.byteValue = bnByteValue; - BigInteger.prototype.shortValue = bnShortValue; - BigInteger.prototype.signum = bnSigNum; - BigInteger.prototype.toByteArray = bnToByteArray; - BigInteger.prototype.equals = bnEquals; - BigInteger.prototype.min = bnMin; - BigInteger.prototype.max = bnMax; - BigInteger.prototype.and = bnAnd; - BigInteger.prototype.or = bnOr; - BigInteger.prototype.xor = bnXor; - BigInteger.prototype.andNot = bnAndNot; - BigInteger.prototype.not = bnNot; - BigInteger.prototype.shiftLeft = bnShiftLeft; - BigInteger.prototype.shiftRight = bnShiftRight; - BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit; - BigInteger.prototype.bitCount = bnBitCount; - BigInteger.prototype.testBit = bnTestBit; - BigInteger.prototype.setBit = bnSetBit; - BigInteger.prototype.clearBit = bnClearBit; - BigInteger.prototype.flipBit = bnFlipBit; - BigInteger.prototype.add = bnAdd; - BigInteger.prototype.subtract = bnSubtract; - BigInteger.prototype.multiply = bnMultiply; - BigInteger.prototype.divide = bnDivide; - BigInteger.prototype.remainder = bnRemainder; - BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder; - BigInteger.prototype.modPow = bnModPow; - BigInteger.prototype.modInverse = bnModInverse; - BigInteger.prototype.pow = bnPow; - BigInteger.prototype.gcd = bnGCD; - BigInteger.prototype.isProbablePrime = bnIsProbablePrime; - - // JSBN-specific extension - BigInteger.prototype.square = bnSquare; - - // Expose the Barrett function - BigInteger.prototype.Barrett = Barrett; - - // BigInteger interfaces not implemented in jsbn: - - // BigInteger(int signum, byte[] magnitude) - // double doubleValue() - // float floatValue() - // int hashCode() - // long longValue() - // static BigInteger valueOf(long val) - - // Imported from bitcoinjs-lib - - /** - * Turns a byte array into a big integer. - * - * This function will interpret a byte array as a big integer in big - * endian notation and ignore leading zeros. - */ - - BigInteger.fromByteArrayUnsigned = function (ba) { - - if (!ba.length) { - return new BigInteger.valueOf(0); - } else if (ba[0] & 0x80) { - // Prepend a zero so the BigInteger class doesn't mistake this - // for a negative integer. - return new BigInteger([0].concat(ba)); - } else { - return new BigInteger(ba); - } - }; - - /** - * Parse a signed big integer byte representation. - * - * For details on the format please see BigInteger.toByteArraySigned. - */ - - BigInteger.fromByteArraySigned = function (ba) { - // Check for negative value - if (ba[0] & 0x80) { - // Remove sign bit - ba[0] &= 0x7f; - - return BigInteger.fromByteArrayUnsigned(ba).negate(); - } else { - return BigInteger.fromByteArrayUnsigned(ba); - } - }; - - /** - * Returns a byte array representation of the big integer. - * - * This returns the absolute of the contained value in big endian - * form. A value of zero results in an empty array. - */ - - BigInteger.prototype.toByteArrayUnsigned = function () { - var ba = this.abs().toByteArray(); - - // Empty array, nothing to do - if (!ba.length) { - return ba; - } - - // remove leading 0 - if (ba[0] === 0) { - ba = ba.slice(1); - } - - // all values must be positive - for (var i = 0; i < ba.length; ++i) { - ba[i] = (ba[i] < 0) ? ba[i] + 256 : ba[i]; - } - - return ba; - }; - - /* - * Converts big integer to signed byte representation. - * - * The format for this value uses the most significant bit as a sign - * bit. If the most significant bit is already occupied by the - * absolute value, an extra byte is prepended and the sign bit is set - * there. - * - * Examples: - * - * 0 => 0x00 - * 1 => 0x01 - * -1 => 0x81 - * 127 => 0x7f - * -127 => 0xff - * 128 => 0x0080 - * -128 => 0x8080 - * 255 => 0x00ff - * -255 => 0x80ff - * 16300 => 0x3fac - * -16300 => 0xbfac - * 62300 => 0x00f35c - * -62300 => 0x80f35c - */ - - BigInteger.prototype.toByteArraySigned = function () { - var val = this.toByteArrayUnsigned(); - var neg = this.s < 0; - - // if the first bit is set, we always unshift - // either unshift 0x80 or 0x00 - if (val[0] & 0x80) { - val.unshift((neg) ? 0x80 : 0x00); - } - // if the first bit isn't set, set it if negative - else if (neg) { - val[0] |= 0x80; - } - - return val; - }; - - // Random number generator - requires a PRNG backend, e.g. prng4.js - - // For best results, put code like - // - // in your main HTML document. - - var rng_state; - var rng_pool; - var rng_pptr; - - // Mix in a 32-bit integer into the pool - function rng_seed_int(x) { - rng_pool[rng_pptr++] ^= x & 255; - rng_pool[rng_pptr++] ^= (x >> 8) & 255; - rng_pool[rng_pptr++] ^= (x >> 16) & 255; - rng_pool[rng_pptr++] ^= (x >> 24) & 255; - if (rng_pptr >= rng_psize) rng_pptr -= rng_psize; - } - - // Mix in the current time (w/milliseconds) into the pool - function rng_seed_time() { - rng_seed_int(new Date().getTime()); - } - - // Initialize the pool with junk if needed. - if (rng_pool == null) { - rng_pool = new Array(); - rng_pptr = 0; - var t; - if (typeof window !== 'undefined' && window.crypto) { - if (window.crypto.getRandomValues) { - // Use webcrypto if available - var ua = new Uint8Array(32); - window.crypto.getRandomValues(ua); - for (t = 0; t < 32; ++t) rng_pool[rng_pptr++] = ua[t]; - } else if ( - navigator.appName == 'Netscape' && - navigator.appVersion < '5' - ) { - // Extract entropy (256 bits) from NS4 RNG if available - var z = window.crypto.random(32); - for (t = 0; t < z.length; ++t) - rng_pool[rng_pptr++] = z.charCodeAt(t) & 255; - } - } - while (rng_pptr < rng_psize) { - // extract some randomness from Math.random() - t = Math.floor(65536 * Math.random()); - rng_pool[rng_pptr++] = t >>> 8; - rng_pool[rng_pptr++] = t & 255; - } - rng_pptr = 0; - rng_seed_time(); - //rng_seed_int(window.screenX); - //rng_seed_int(window.screenY); - } - - function rng_get_byte() { - if (rng_state == null) { - rng_seed_time(); - rng_state = prng_newstate(); - rng_state.init(rng_pool); - for (rng_pptr = 0; rng_pptr < rng_pool.length; ++rng_pptr) - rng_pool[rng_pptr] = 0; - rng_pptr = 0; - //rng_pool = null; - } - // TODO: allow reseeding after first request - return rng_state.next(); - } - - function rng_get_bytes(ba) { - var i; - for (i = 0; i < ba.length; ++i) ba[i] = rng_get_byte(); - } - - function SecureRandom() { } - - SecureRandom.prototype.nextBytes = rng_get_bytes; - - // prng4.js - uses Arcfour as a PRNG - - function Arcfour() { - this.i = 0; - this.j = 0; - this.S = new Array(); - } - - // Initialize arcfour context from key, an array of ints, each from [0..255] - function ARC4init(key) { - var i, j, t; - for (i = 0; i < 256; ++i) this.S[i] = i; - j = 0; - for (i = 0; i < 256; ++i) { - j = (j + this.S[i] + key[i % key.length]) & 255; - t = this.S[i]; - this.S[i] = this.S[j]; - this.S[j] = t; - } - this.i = 0; - this.j = 0; - } - - function ARC4next() { - var t; - this.i = (this.i + 1) & 255; - this.j = (this.j + this.S[this.i]) & 255; - t = this.S[this.i]; - this.S[this.i] = this.S[this.j]; - this.S[this.j] = t; - return this.S[(t + this.S[this.i]) & 255]; - } - - Arcfour.prototype.init = ARC4init; - Arcfour.prototype.next = ARC4next; - - // Plug in your RNG constructor here - function prng_newstate() { - return new Arcfour(); - } - - // Pool size must be a multiple of 4 and greater than 32. - // An array of bytes the size of the pool will be passed to init() - var rng_psize = 256; - - if (typeof exports !== 'undefined') { - exports = module.exports = { - default: BigInteger, - BigInteger: BigInteger, - SecureRandom: SecureRandom, - }; - } else { - this.jsbn = { - BigInteger: BigInteger, - SecureRandom: SecureRandom, - }; - } -}.call(this)); \ No newline at end of file + // Copyright (c) 2005 Tom Wu + // All Rights Reserved. + // See "LICENSE" for details. + + // Basic JavaScript BN library - subset useful for RSA encryption. + + // Bits per digit + var dbits; + + // JavaScript engine analysis + var canary = 0xdeadbeefcafe; + var j_lm = (canary & 0xffffff) == 0xefcafe; + + // (public) Constructor + function BigInteger(a, b, c) { + if (a != null) + if ('number' == typeof a) this.fromNumber(a, b, c); + else if (b == null && 'string' != typeof a) this.fromString(a, 256); + else this.fromString(a, b); + } + + // return new, unset BigInteger + function nbi() { + return new BigInteger(null); + } + + // am: Compute w_j += (x*this_i), propagate carries, + // c is initial carry, returns final carry. + // c < 3*dvalue, x < 2*dvalue, this_i < dvalue + // We need to select the fastest one that works in this environment. + + // am1: use a single mult and divide to get the high bits, + // max digit bits should be 26 because + // max internal value = 2*dvalue^2-2*dvalue (< 2^53) + function am1(i, x, w, j, c, n) { + while (--n >= 0) { + var v = x * this[i++] + w[j] + c; + c = Math.floor(v / 0x4000000); + w[j++] = v & 0x3ffffff; + } + return c; + } + // am2 avoids a big mult-and-extract completely. + // Max digit bits should be <= 30 because we do bitwise ops + // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) + function am2(i, x, w, j, c, n) { + var xl = x & 0x7fff, + xh = x >> 15; + while (--n >= 0) { + var l = this[i] & 0x7fff; + var h = this[i++] >> 15; + var m = xh * l + h * xl; + l = xl * l + ((m & 0x7fff) << 15) + w[j] + (c & 0x3fffffff); + c = (l >>> 30) + (m >>> 15) + xh * h + (c >>> 30); + w[j++] = l & 0x3fffffff; + } + return c; + } + // Alternately, set max digit bits to 28 since some + // browsers slow down when dealing with 32-bit numbers. + function am3(i, x, w, j, c, n) { + var xl = x & 0x3fff, + xh = x >> 14; + while (--n >= 0) { + var l = this[i] & 0x3fff; + var h = this[i++] >> 14; + var m = xh * l + h * xl; + l = xl * l + ((m & 0x3fff) << 14) + w[j] + c; + c = (l >> 28) + (m >> 14) + xh * h; + w[j++] = l & 0xfffffff; + } + return c; + } + var inBrowser = typeof navigator !== 'undefined'; + if (inBrowser && j_lm && navigator.appName == 'Microsoft Internet Explorer') { + BigInteger.prototype.am = am2; + dbits = 30; + } else if (inBrowser && j_lm && navigator.appName != 'Netscape') { + BigInteger.prototype.am = am1; + dbits = 26; + } else { + // Mozilla/Netscape seems to prefer am3 + BigInteger.prototype.am = am3; + dbits = 28; + } + + BigInteger.prototype.DB = dbits; + BigInteger.prototype.DM = (1 << dbits) - 1; + BigInteger.prototype.DV = 1 << dbits; + + var BI_FP = 52; + BigInteger.prototype.FV = Math.pow(2, BI_FP); + BigInteger.prototype.F1 = BI_FP - dbits; + BigInteger.prototype.F2 = 2 * dbits - BI_FP; + + // Digit conversions + var BI_RM = '0123456789abcdefghijklmnopqrstuvwxyz'; + var BI_RC = new Array(); + var rr, vv; + rr = '0'.charCodeAt(0); + for (vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv; + rr = 'a'.charCodeAt(0); + for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; + rr = 'A'.charCodeAt(0); + for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; + + function int2char(n) { + return BI_RM.charAt(n); + } + function intAt(s, i) { + var c = BI_RC[s.charCodeAt(i)]; + return c == null ? -1 : c; + } + + // (protected) copy this to r + function bnpCopyTo(r) { + for (var i = this.t - 1; i >= 0; --i) r[i] = this[i]; + r.t = this.t; + r.s = this.s; + } + + // (protected) set from integer value x, -DV <= x < DV + function bnpFromInt(x) { + this.t = 1; + this.s = x < 0 ? -1 : 0; + if (x > 0) this[0] = x; + else if (x < -1) this[0] = x + this.DV; + else this.t = 0; + } + + // return bigint initialized to value + function nbv(i) { + var r = nbi(); + r.fromInt(i); + return r; + } + + // (protected) set from string and radix + function bnpFromString(s, b) { + // Auto-detect string notations + if (!b && s.length >= 2 && s[0] === '0') { + var isDetected = true; + switch (s[1]) { + case 'x': // Hexadecimal notation + b = 16; + break; + case 'b': // Binary notation + b = 2; + break; + case 'o': // Octal notation + b = 8; + break; + default: + isDetected = false; + } + + // Remove the notation string if any has been detected + if (isDetected) { + s = s.substr(2); + } + } + + var k; + if (b == 16) k = 4; + else if (b == 8) k = 3; + else if (b == 256) k = 8; + // byte array + else if (b == 2) k = 1; + else if (b == 32) k = 5; + else if (b == 4) k = 2; + else { + this.fromRadix(s, b); + return; + } + this.t = 0; + this.s = 0; + var i = s.length, + mi = false, + sh = 0; + while (--i >= 0) { + var x = k == 8 ? s[i] & 0xff : intAt(s, i); + if (x < 0) { + if (s.charAt(i) == '-') mi = true; + continue; + } + mi = false; + if (sh == 0) this[this.t++] = x; + else if (sh + k > this.DB) { + this[this.t - 1] |= (x & ((1 << (this.DB - sh)) - 1)) << sh; + this[this.t++] = x >> (this.DB - sh); + } else this[this.t - 1] |= x << sh; + sh += k; + if (sh >= this.DB) sh -= this.DB; + } + if (k == 8 && (s[0] & 0x80) != 0) { + this.s = -1; + if (sh > 0) this[this.t - 1] |= ((1 << (this.DB - sh)) - 1) << sh; + } + this.clamp(); + if (mi) BigInteger.ZERO.subTo(this, this); + } + + // (protected) clamp off excess high words + function bnpClamp() { + var c = this.s & this.DM; + while (this.t > 0 && this[this.t - 1] == c) --this.t; + } + + // (public) return string representation in given radix + function bnToString(b) { + if (this.s < 0) return '-' + this.negate().toString(b); + var k; + if (b == 16) k = 4; + else if (b == 8) k = 3; + else if (b == 2) k = 1; + else if (b == 32) k = 5; + else if (b == 4) k = 2; + else return this.toRadix(b); + var km = (1 << k) - 1, + d, + m = false, + r = '', + i = this.t; + var p = this.DB - ((i * this.DB) % k); + if (i-- > 0) { + if (p < this.DB && (d = this[i] >> p) > 0) { + m = true; + r = int2char(d); + } + while (i >= 0) { + if (p < k) { + d = (this[i] & ((1 << p) - 1)) << (k - p); + d |= this[--i] >> (p += this.DB - k); + } else { + d = (this[i] >> (p -= k)) & km; + if (p <= 0) { + p += this.DB; + --i; + } + } + if (d > 0) m = true; + if (m) r += int2char(d); + } + } + return m ? r : '0'; + } + + // (public) -this + function bnNegate() { + var r = nbi(); + BigInteger.ZERO.subTo(this, r); + return r; + } + + // (public) |this| + function bnAbs() { + return this.s < 0 ? this.negate() : this; + } + + // (public) return + if this > a, - if this < a, 0 if equal + function bnCompareTo(a) { + var r = this.s - a.s; + if (r != 0) return r; + var i = this.t; + r = i - a.t; + if (r != 0) return this.s < 0 ? -r : r; + while (--i >= 0) if ((r = this[i] - a[i]) != 0) return r; + return 0; + } + + // returns bit length of the integer x + function nbits(x) { + var r = 1, + t; + if ((t = x >>> 16) != 0) { + x = t; + r += 16; + } + if ((t = x >> 8) != 0) { + x = t; + r += 8; + } + if ((t = x >> 4) != 0) { + x = t; + r += 4; + } + if ((t = x >> 2) != 0) { + x = t; + r += 2; + } + if ((t = x >> 1) != 0) { + x = t; + r += 1; + } + return r; + } + + // (public) return the number of bits in "this" + function bnBitLength() { + if (this.t <= 0) return 0; + return ( + this.DB * (this.t - 1) + nbits(this[this.t - 1] ^ (this.s & this.DM)) + ); + } + + // (protected) r = this << n*DB + function bnpDLShiftTo(n, r) { + var i; + for (i = this.t - 1; i >= 0; --i) r[i + n] = this[i]; + for (i = n - 1; i >= 0; --i) r[i] = 0; + r.t = this.t + n; + r.s = this.s; + } + + // (protected) r = this >> n*DB + function bnpDRShiftTo(n, r) { + for (var i = n; i < this.t; ++i) r[i - n] = this[i]; + r.t = Math.max(this.t - n, 0); + r.s = this.s; + } + + // (protected) r = this << n + function bnpLShiftTo(n, r) { + var bs = n % this.DB; + var cbs = this.DB - bs; + var bm = (1 << cbs) - 1; + var ds = Math.floor(n / this.DB), + c = (this.s << bs) & this.DM, + i; + for (i = this.t - 1; i >= 0; --i) { + r[i + ds + 1] = (this[i] >> cbs) | c; + c = (this[i] & bm) << bs; + } + for (i = ds - 1; i >= 0; --i) r[i] = 0; + r[ds] = c; + r.t = this.t + ds + 1; + r.s = this.s; + r.clamp(); + } + + // (protected) r = this >> n + function bnpRShiftTo(n, r) { + r.s = this.s; + var ds = Math.floor(n / this.DB); + if (ds >= this.t) { + r.t = 0; + return; + } + var bs = n % this.DB; + var cbs = this.DB - bs; + var bm = (1 << bs) - 1; + r[0] = this[ds] >> bs; + for (var i = ds + 1; i < this.t; ++i) { + r[i - ds - 1] |= (this[i] & bm) << cbs; + r[i - ds] = this[i] >> bs; + } + if (bs > 0) r[this.t - ds - 1] |= (this.s & bm) << cbs; + r.t = this.t - ds; + r.clamp(); + } + + // (protected) r = this - a + function bnpSubTo(a, r) { + var i = 0, + c = 0, + m = Math.min(a.t, this.t); + while (i < m) { + c += this[i] - a[i]; + r[i++] = c & this.DM; + c >>= this.DB; + } + if (a.t < this.t) { + c -= a.s; + while (i < this.t) { + c += this[i]; + r[i++] = c & this.DM; + c >>= this.DB; + } + c += this.s; + } else { + c += this.s; + while (i < a.t) { + c -= a[i]; + r[i++] = c & this.DM; + c >>= this.DB; + } + c -= a.s; + } + r.s = c < 0 ? -1 : 0; + if (c < -1) r[i++] = this.DV + c; + else if (c > 0) r[i++] = c; + r.t = i; + r.clamp(); + } + + // (protected) r = this * a, r != this,a (HAC 14.12) + // "this" should be the larger one if appropriate. + function bnpMultiplyTo(a, r) { + var x = this.abs(), + y = a.abs(); + var i = x.t; + r.t = i + y.t; + while (--i >= 0) r[i] = 0; + for (i = 0; i < y.t; ++i) r[i + x.t] = x.am(0, y[i], r, i, 0, x.t); + r.s = 0; + r.clamp(); + if (this.s != a.s) BigInteger.ZERO.subTo(r, r); + } + + // (protected) r = this^2, r != this (HAC 14.16) + function bnpSquareTo(r) { + var x = this.abs(); + var i = (r.t = 2 * x.t); + while (--i >= 0) r[i] = 0; + for (i = 0; i < x.t - 1; ++i) { + var c = x.am(i, x[i], r, 2 * i, 0, 1); + if ( + (r[i + x.t] += x.am(i + 1, 2 * x[i], r, 2 * i + 1, c, x.t - i - 1)) >= + x.DV + ) { + r[i + x.t] -= x.DV; + r[i + x.t + 1] = 1; + } + } + if (r.t > 0) r[r.t - 1] += x.am(i, x[i], r, 2 * i, 0, 1); + r.s = 0; + r.clamp(); + } + + // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) + // r != q, this != m. q or r may be null. + function bnpDivRemTo(m, q, r) { + var pm = m.abs(); + if (pm.t <= 0) return; + var pt = this.abs(); + if (pt.t < pm.t) { + if (q != null) q.fromInt(0); + if (r != null) this.copyTo(r); + return; + } + if (r == null) r = nbi(); + var y = nbi(), + ts = this.s, + ms = m.s; + var nsh = this.DB - nbits(pm[pm.t - 1]); // normalize modulus + if (nsh > 0) { + pm.lShiftTo(nsh, y); + pt.lShiftTo(nsh, r); + } else { + pm.copyTo(y); + pt.copyTo(r); + } + var ys = y.t; + var y0 = y[ys - 1]; + if (y0 == 0) return; + var yt = y0 * (1 << this.F1) + (ys > 1 ? y[ys - 2] >> this.F2 : 0); + var d1 = this.FV / yt, + d2 = (1 << this.F1) / yt, + e = 1 << this.F2; + var i = r.t, + j = i - ys, + t = q == null ? nbi() : q; + y.dlShiftTo(j, t); + if (r.compareTo(t) >= 0) { + r[r.t++] = 1; + r.subTo(t, r); + } + BigInteger.ONE.dlShiftTo(ys, t); + t.subTo(y, y); // "negative" y so we can replace sub with am later + while (y.t < ys) y[y.t++] = 0; + while (--j >= 0) { + // Estimate quotient digit + var qd = + r[--i] == y0 ? this.DM : Math.floor(r[i] * d1 + (r[i - 1] + e) * d2); + if ((r[i] += y.am(0, qd, r, j, 0, ys)) < qd) { + // Try it out + y.dlShiftTo(j, t); + r.subTo(t, r); + while (r[i] < --qd) r.subTo(t, r); + } + } + if (q != null) { + r.drShiftTo(ys, q); + if (ts != ms) BigInteger.ZERO.subTo(q, q); + } + r.t = ys; + r.clamp(); + if (nsh > 0) r.rShiftTo(nsh, r); // Denormalize remainder + if (ts < 0) BigInteger.ZERO.subTo(r, r); + } + + // (public) this mod a + function bnMod(a) { + var r = nbi(); + this.abs().divRemTo(a, null, r); + if (this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r, r); + return r; + } + + // Modular reduction using "classic" algorithm + function Classic(m) { + this.m = m; + } + function cConvert(x) { + if (x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m); + else return x; + } + function cRevert(x) { + return x; + } + function cReduce(x) { + x.divRemTo(this.m, null, x); + } + function cMulTo(x, y, r) { + x.multiplyTo(y, r); + this.reduce(r); + } + function cSqrTo(x, r) { + x.squareTo(r); + this.reduce(r); + } + + Classic.prototype.convert = cConvert; + Classic.prototype.revert = cRevert; + Classic.prototype.reduce = cReduce; + Classic.prototype.mulTo = cMulTo; + Classic.prototype.sqrTo = cSqrTo; + + // (protected) return "-1/this % 2^DB"; useful for Mont. reduction + // justification: + // xy == 1 (mod m) + // xy = 1+km + // xy(2-xy) = (1+km)(1-km) + // x[y(2-xy)] = 1-k^2m^2 + // x[y(2-xy)] == 1 (mod m^2) + // if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 + // should reduce x and y(2-xy) by m^2 at each step to keep size bounded. + // JS multiply "overflows" differently from C/C++, so care is needed here. + function bnpInvDigit() { + if (this.t < 1) return 0; + var x = this[0]; + if ((x & 1) == 0) return 0; + var y = x & 3; // y == 1/x mod 2^2 + y = (y * (2 - (x & 0xf) * y)) & 0xf; // y == 1/x mod 2^4 + y = (y * (2 - (x & 0xff) * y)) & 0xff; // y == 1/x mod 2^8 + y = (y * (2 - (((x & 0xffff) * y) & 0xffff))) & 0xffff; // y == 1/x mod 2^16 + // last step - calculate inverse mod DV directly; + // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints + y = (y * (2 - ((x * y) % this.DV))) % this.DV; // y == 1/x mod 2^dbits + // we really want the negative inverse, and -DV < y < DV + return y > 0 ? this.DV - y : -y; + } + + // Montgomery reduction + function Montgomery(m) { + this.m = m; + this.mp = m.invDigit(); + this.mpl = this.mp & 0x7fff; + this.mph = this.mp >> 15; + this.um = (1 << (m.DB - 15)) - 1; + this.mt2 = 2 * m.t; + } + + // xR mod m + function montConvert(x) { + var r = nbi(); + x.abs().dlShiftTo(this.m.t, r); + r.divRemTo(this.m, null, r); + if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r, r); + return r; + } + + // x/R mod m + function montRevert(x) { + var r = nbi(); + x.copyTo(r); + this.reduce(r); + return r; + } + + // x = x/R mod m (HAC 14.32) + function montReduce(x) { + while ( + x.t <= this.mt2 // pad x so am has enough room later + ) + x[x.t++] = 0; + for (var i = 0; i < this.m.t; ++i) { + // faster way of calculating u0 = x[i]*mp mod DV + var j = x[i] & 0x7fff; + var u0 = + (j * this.mpl + + (((j * this.mph + (x[i] >> 15) * this.mpl) & this.um) << 15)) & + x.DM; + // use am to combine the multiply-shift-add into one call + j = i + this.m.t; + x[j] += this.m.am(0, u0, x, i, 0, this.m.t); + // propagate carry + while (x[j] >= x.DV) { + x[j] -= x.DV; + x[++j]++; + } + } + x.clamp(); + x.drShiftTo(this.m.t, x); + if (x.compareTo(this.m) >= 0) x.subTo(this.m, x); + } + + // r = "x^2/R mod m"; x != r + function montSqrTo(x, r) { + x.squareTo(r); + this.reduce(r); + } + + // r = "xy/R mod m"; x,y != r + function montMulTo(x, y, r) { + x.multiplyTo(y, r); + this.reduce(r); + } + + Montgomery.prototype.convert = montConvert; + Montgomery.prototype.revert = montRevert; + Montgomery.prototype.reduce = montReduce; + Montgomery.prototype.mulTo = montMulTo; + Montgomery.prototype.sqrTo = montSqrTo; + + // (protected) true iff this is even + function bnpIsEven() { + return (this.t > 0 ? this[0] & 1 : this.s) == 0; + } + + // (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79) + function bnpExp(e, z) { + if (e > 0xffffffff || e < 1) return BigInteger.ONE; + var r = nbi(), + r2 = nbi(), + g = z.convert(this), + i = nbits(e) - 1; + g.copyTo(r); + while (--i >= 0) { + z.sqrTo(r, r2); + if ((e & (1 << i)) > 0) z.mulTo(r2, g, r); + else { + var t = r; + r = r2; + r2 = t; + } + } + return z.revert(r); + } + + // (public) this^e % m, 0 <= e < 2^32 + function bnModPowInt(e, m) { + var z; + if (e < 256 || m.isEven()) z = new Classic(m); + else z = new Montgomery(m); + return this.exp(e, z); + } + + // protected + BigInteger.prototype.copyTo = bnpCopyTo; + BigInteger.prototype.fromInt = bnpFromInt; + BigInteger.prototype.fromString = bnpFromString; + BigInteger.prototype.clamp = bnpClamp; + BigInteger.prototype.dlShiftTo = bnpDLShiftTo; + BigInteger.prototype.drShiftTo = bnpDRShiftTo; + BigInteger.prototype.lShiftTo = bnpLShiftTo; + BigInteger.prototype.rShiftTo = bnpRShiftTo; + BigInteger.prototype.subTo = bnpSubTo; + BigInteger.prototype.multiplyTo = bnpMultiplyTo; + BigInteger.prototype.squareTo = bnpSquareTo; + BigInteger.prototype.divRemTo = bnpDivRemTo; + BigInteger.prototype.invDigit = bnpInvDigit; + BigInteger.prototype.isEven = bnpIsEven; + BigInteger.prototype.exp = bnpExp; + + // public + BigInteger.prototype.toString = bnToString; + BigInteger.prototype.negate = bnNegate; + BigInteger.prototype.abs = bnAbs; + BigInteger.prototype.compareTo = bnCompareTo; + BigInteger.prototype.bitLength = bnBitLength; + BigInteger.prototype.mod = bnMod; + BigInteger.prototype.modPowInt = bnModPowInt; + + // "constants" + BigInteger.ZERO = nbv(0); + BigInteger.ONE = nbv(1); + BigInteger.valueOf = nbv; + + // Copyright (c) 2005-2009 Tom Wu + // All Rights Reserved. + // See "LICENSE" for details. + + // Extended JavaScript BN functions, required for RSA private ops. + + // Version 1.1: new BigInteger("0", 10) returns "proper" zero + // Version 1.2: square() API, isProbablePrime fix + + // (public) + function bnClone() { + var r = nbi(); + this.copyTo(r); + return r; + } + + // (public) return value as integer + function bnIntValue() { + if (this.s < 0) { + if (this.t == 1) return this[0] - this.DV; + else if (this.t == 0) return -1; + } else if (this.t == 1) return this[0]; + else if (this.t == 0) return 0; + // assumes 16 < DB < 32 + return ((this[1] & ((1 << (32 - this.DB)) - 1)) << this.DB) | this[0]; + } + + // (public) return value as byte + function bnByteValue() { + return this.t == 0 ? this.s : (this[0] << 24) >> 24; + } + + // (public) return value as short (assumes DB>=16) + function bnShortValue() { + return this.t == 0 ? this.s : (this[0] << 16) >> 16; + } + + // (protected) return x s.t. r^x < DV + function bnpChunkSize(r) { + return Math.floor((Math.LN2 * this.DB) / Math.log(r)); + } + + // (public) 0 if this == 0, 1 if this > 0 + function bnSigNum() { + if (this.s < 0) return -1; + else if (this.t <= 0 || (this.t == 1 && this[0] <= 0)) return 0; + else return 1; + } + + // (protected) convert to radix string + function bnpToRadix(b) { + if (b == null) b = 10; + if (this.signum() == 0 || b < 2 || b > 36) return '0'; + var cs = this.chunkSize(b); + var a = Math.pow(b, cs); + var d = nbv(a), + y = nbi(), + z = nbi(), + r = ''; + this.divRemTo(d, y, z); + while (y.signum() > 0) { + r = (a + z.intValue()).toString(b).substr(1) + r; + y.divRemTo(d, y, z); + } + return z.intValue().toString(b) + r; + } + + // (protected) convert from radix string + function bnpFromRadix(s, b) { + this.fromInt(0); + if (b == null) b = 10; + var cs = this.chunkSize(b); + var d = Math.pow(b, cs), + mi = false, + j = 0, + w = 0; + for (var i = 0; i < s.length; ++i) { + var x = intAt(s, i); + if (x < 0) { + if (s.charAt(i) == '-' && this.signum() == 0) mi = true; + continue; + } + w = b * w + x; + if (++j >= cs) { + this.dMultiply(d); + this.dAddOffset(w, 0); + j = 0; + w = 0; + } + } + if (j > 0) { + this.dMultiply(Math.pow(b, j)); + this.dAddOffset(w, 0); + } + if (mi) BigInteger.ZERO.subTo(this, this); + } + + // (protected) alternate constructor + function bnpFromNumber(a, b, c) { + if ('number' == typeof b) { + // new BigInteger(int,int,RNG) + if (a < 2) this.fromInt(1); + else { + this.fromNumber(a, c); + if (!this.testBit(a - 1)) + // force MSB set + this.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, this); + if (this.isEven()) this.dAddOffset(1, 0); // force odd + while (!this.isProbablePrime(b)) { + this.dAddOffset(2, 0); + if (this.bitLength() > a) + this.subTo(BigInteger.ONE.shiftLeft(a - 1), this); + } + } + } else { + // new BigInteger(int,RNG) + var x = new Array(), + t = a & 7; + x.length = (a >> 3) + 1; + b.nextBytes(x); + if (t > 0) x[0] &= (1 << t) - 1; + else x[0] = 0; + this.fromString(x, 256); + } + } + + // (public) convert to bigendian byte array + function bnToByteArray() { + var i = this.t, + r = new Array(); + r[0] = this.s; + var p = this.DB - ((i * this.DB) % 8), + d, + k = 0; + if (i-- > 0) { + if (p < this.DB && (d = this[i] >> p) != (this.s & this.DM) >> p) + r[k++] = d | (this.s << (this.DB - p)); + while (i >= 0) { + if (p < 8) { + d = (this[i] & ((1 << p) - 1)) << (8 - p); + d |= this[--i] >> (p += this.DB - 8); + } else { + d = (this[i] >> (p -= 8)) & 0xff; + if (p <= 0) { + p += this.DB; + --i; + } + } + if ((d & 0x80) != 0) d |= -256; + if (k == 0 && (this.s & 0x80) != (d & 0x80)) ++k; + if (k > 0 || d != this.s) r[k++] = d; + } + } + return r; + } + + function bnEquals(a) { + return this.compareTo(a) == 0; + } + function bnMin(a) { + return this.compareTo(a) < 0 ? this : a; + } + function bnMax(a) { + return this.compareTo(a) > 0 ? this : a; + } + + // (protected) r = this op a (bitwise) + function bnpBitwiseTo(a, op, r) { + var i, + f, + m = Math.min(a.t, this.t); + for (i = 0; i < m; ++i) r[i] = op(this[i], a[i]); + if (a.t < this.t) { + f = a.s & this.DM; + for (i = m; i < this.t; ++i) r[i] = op(this[i], f); + r.t = this.t; + } else { + f = this.s & this.DM; + for (i = m; i < a.t; ++i) r[i] = op(f, a[i]); + r.t = a.t; + } + r.s = op(this.s, a.s); + r.clamp(); + } + + // (public) this & a + function op_and(x, y) { + return x & y; + } + function bnAnd(a) { + var r = nbi(); + this.bitwiseTo(a, op_and, r); + return r; + } + + // (public) this | a + function op_or(x, y) { + return x | y; + } + function bnOr(a) { + var r = nbi(); + this.bitwiseTo(a, op_or, r); + return r; + } + + // (public) this ^ a + function op_xor(x, y) { + return x ^ y; + } + function bnXor(a) { + var r = nbi(); + this.bitwiseTo(a, op_xor, r); + return r; + } + + // (public) this & ~a + function op_andnot(x, y) { + return x & ~y; + } + function bnAndNot(a) { + var r = nbi(); + this.bitwiseTo(a, op_andnot, r); + return r; + } + + // (public) ~this + function bnNot() { + var r = nbi(); + for (var i = 0; i < this.t; ++i) r[i] = this.DM & ~this[i]; + r.t = this.t; + r.s = ~this.s; + return r; + } + + // (public) this << n + function bnShiftLeft(n) { + var r = nbi(); + if (n < 0) this.rShiftTo(-n, r); + else this.lShiftTo(n, r); + return r; + } + + // (public) this >> n + function bnShiftRight(n) { + var r = nbi(); + if (n < 0) this.lShiftTo(-n, r); + else this.rShiftTo(n, r); + return r; + } + + // return index of lowest 1-bit in x, x < 2^31 + function lbit(x) { + if (x == 0) return -1; + var r = 0; + if ((x & 0xffff) == 0) { + x >>= 16; + r += 16; + } + if ((x & 0xff) == 0) { + x >>= 8; + r += 8; + } + if ((x & 0xf) == 0) { + x >>= 4; + r += 4; + } + if ((x & 3) == 0) { + x >>= 2; + r += 2; + } + if ((x & 1) == 0) ++r; + return r; + } + + // (public) returns index of lowest 1-bit (or -1 if none) + function bnGetLowestSetBit() { + for (var i = 0; i < this.t; ++i) + if (this[i] != 0) return i * this.DB + lbit(this[i]); + if (this.s < 0) return this.t * this.DB; + return -1; + } + + // return number of 1 bits in x + function cbit(x) { + var r = 0; + while (x != 0) { + x &= x - 1; + ++r; + } + return r; + } + + // (public) return number of set bits + function bnBitCount() { + var r = 0, + x = this.s & this.DM; + for (var i = 0; i < this.t; ++i) r += cbit(this[i] ^ x); + return r; + } + + // (public) true iff nth bit is set + function bnTestBit(n) { + var j = Math.floor(n / this.DB); + if (j >= this.t) return this.s != 0; + return (this[j] & (1 << n % this.DB)) != 0; + } + + // (protected) this op (1<>= this.DB; + } + if (a.t < this.t) { + c += a.s; + while (i < this.t) { + c += this[i]; + r[i++] = c & this.DM; + c >>= this.DB; + } + c += this.s; + } else { + c += this.s; + while (i < a.t) { + c += a[i]; + r[i++] = c & this.DM; + c >>= this.DB; + } + c += a.s; + } + r.s = c < 0 ? -1 : 0; + if (c > 0) r[i++] = c; + else if (c < -1) r[i++] = this.DV + c; + r.t = i; + r.clamp(); + } + + // (public) this + a + function bnAdd(a) { + var r = nbi(); + this.addTo(a, r); + return r; + } + + // (public) this - a + function bnSubtract(a) { + var r = nbi(); + this.subTo(a, r); + return r; + } + + // (public) this * a + function bnMultiply(a) { + var r = nbi(); + this.multiplyTo(a, r); + return r; + } + + // (public) this^2 + function bnSquare() { + var r = nbi(); + this.squareTo(r); + return r; + } + + // (public) this / a + function bnDivide(a) { + var r = nbi(); + this.divRemTo(a, r, null); + return r; + } + + // (public) this % a + function bnRemainder(a) { + var r = nbi(); + this.divRemTo(a, null, r); + return r; + } + + // (public) [this/a,this%a] + function bnDivideAndRemainder(a) { + var q = nbi(), + r = nbi(); + this.divRemTo(a, q, r); + return new Array(q, r); + } + + // (protected) this *= n, this >= 0, 1 < n < DV + function bnpDMultiply(n) { + this[this.t] = this.am(0, n - 1, this, 0, 0, this.t); + ++this.t; + this.clamp(); + } + + // (protected) this += n << w words, this >= 0 + function bnpDAddOffset(n, w) { + if (n == 0) return; + while (this.t <= w) this[this.t++] = 0; + this[w] += n; + while (this[w] >= this.DV) { + this[w] -= this.DV; + if (++w >= this.t) this[this.t++] = 0; + ++this[w]; + } + } + + // A "null" reducer + function NullExp() { } + function nNop(x) { + return x; + } + function nMulTo(x, y, r) { + x.multiplyTo(y, r); + } + function nSqrTo(x, r) { + x.squareTo(r); + } + + NullExp.prototype.convert = nNop; + NullExp.prototype.revert = nNop; + NullExp.prototype.mulTo = nMulTo; + NullExp.prototype.sqrTo = nSqrTo; + + // (public) this^e + function bnPow(e) { + return this.exp(e, new NullExp()); + } + + // (protected) r = lower n words of "this * a", a.t <= n + // "this" should be the larger one if appropriate. + function bnpMultiplyLowerTo(a, n, r) { + var i = Math.min(this.t + a.t, n); + r.s = 0; // assumes a,this >= 0 + r.t = i; + while (i > 0) r[--i] = 0; + var j; + for (j = r.t - this.t; i < j; ++i) + r[i + this.t] = this.am(0, a[i], r, i, 0, this.t); + for (j = Math.min(a.t, n); i < j; ++i) this.am(0, a[i], r, i, 0, n - i); + r.clamp(); + } + + // (protected) r = "this * a" without lower n words, n > 0 + // "this" should be the larger one if appropriate. + function bnpMultiplyUpperTo(a, n, r) { + --n; + var i = (r.t = this.t + a.t - n); + r.s = 0; // assumes a,this >= 0 + while (--i >= 0) r[i] = 0; + for (i = Math.max(n - this.t, 0); i < a.t; ++i) + r[this.t + i - n] = this.am(n - i, a[i], r, 0, 0, this.t + i - n); + r.clamp(); + r.drShiftTo(1, r); + } + + // Barrett modular reduction + function Barrett(m) { + // setup Barrett + this.r2 = nbi(); + this.q3 = nbi(); + BigInteger.ONE.dlShiftTo(2 * m.t, this.r2); + this.mu = this.r2.divide(m); + this.m = m; + } + + function barrettConvert(x) { + if (x.s < 0 || x.t > 2 * this.m.t) return x.mod(this.m); + else if (x.compareTo(this.m) < 0) return x; + else { + var r = nbi(); + x.copyTo(r); + this.reduce(r); + return r; + } + } + + function barrettRevert(x) { + return x; + } + + // x = x mod m (HAC 14.42) + function barrettReduce(x) { + x.drShiftTo(this.m.t - 1, this.r2); + if (x.t > this.m.t + 1) { + x.t = this.m.t + 1; + x.clamp(); + } + this.mu.multiplyUpperTo(this.r2, this.m.t + 1, this.q3); + this.m.multiplyLowerTo(this.q3, this.m.t + 1, this.r2); + while (x.compareTo(this.r2) < 0) x.dAddOffset(1, this.m.t + 1); + x.subTo(this.r2, x); + while (x.compareTo(this.m) >= 0) x.subTo(this.m, x); + } + + // r = x^2 mod m; x != r + function barrettSqrTo(x, r) { + x.squareTo(r); + this.reduce(r); + } + + // r = x*y mod m; x,y != r + function barrettMulTo(x, y, r) { + x.multiplyTo(y, r); + this.reduce(r); + } + + Barrett.prototype.convert = barrettConvert; + Barrett.prototype.revert = barrettRevert; + Barrett.prototype.reduce = barrettReduce; + Barrett.prototype.mulTo = barrettMulTo; + Barrett.prototype.sqrTo = barrettSqrTo; + + // (public) this^e % m (HAC 14.85) + function bnModPow(e, m) { + var i = e.bitLength(), + k, + r = nbv(1), + z; + if (i <= 0) return r; + else if (i < 18) k = 1; + else if (i < 48) k = 3; + else if (i < 144) k = 4; + else if (i < 768) k = 5; + else k = 6; + if (i < 8) z = new Classic(m); + else if (m.isEven()) z = new Barrett(m); + else z = new Montgomery(m); + + // precomputation + var g = new Array(), + n = 3, + k1 = k - 1, + km = (1 << k) - 1; + g[1] = z.convert(this); + if (k > 1) { + var g2 = nbi(); + z.sqrTo(g[1], g2); + while (n <= km) { + g[n] = nbi(); + z.mulTo(g2, g[n - 2], g[n]); + n += 2; + } + } + + var j = e.t - 1, + w, + is1 = true, + r2 = nbi(), + t; + i = nbits(e[j]) - 1; + while (j >= 0) { + if (i >= k1) w = (e[j] >> (i - k1)) & km; + else { + w = (e[j] & ((1 << (i + 1)) - 1)) << (k1 - i); + if (j > 0) w |= e[j - 1] >> (this.DB + i - k1); + } + + n = k; + while ((w & 1) == 0) { + w >>= 1; + --n; + } + if ((i -= n) < 0) { + i += this.DB; + --j; + } + if (is1) { + // ret == 1, don't bother squaring or multiplying it + g[w].copyTo(r); + is1 = false; + } else { + while (n > 1) { + z.sqrTo(r, r2); + z.sqrTo(r2, r); + n -= 2; + } + if (n > 0) z.sqrTo(r, r2); + else { + t = r; + r = r2; + r2 = t; + } + z.mulTo(r2, g[w], r); + } + + while (j >= 0 && (e[j] & (1 << i)) == 0) { + z.sqrTo(r, r2); + t = r; + r = r2; + r2 = t; + if (--i < 0) { + i = this.DB - 1; + --j; + } + } + } + return z.revert(r); + } + + // (public) gcd(this,a) (HAC 14.54) + function bnGCD(a) { + var x = this.s < 0 ? this.negate() : this.clone(); + var y = a.s < 0 ? a.negate() : a.clone(); + if (x.compareTo(y) < 0) { + var t = x; + x = y; + y = t; + } + var i = x.getLowestSetBit(), + g = y.getLowestSetBit(); + if (g < 0) return x; + if (i < g) g = i; + if (g > 0) { + x.rShiftTo(g, x); + y.rShiftTo(g, y); + } + while (x.signum() > 0) { + if ((i = x.getLowestSetBit()) > 0) x.rShiftTo(i, x); + if ((i = y.getLowestSetBit()) > 0) y.rShiftTo(i, y); + if (x.compareTo(y) >= 0) { + x.subTo(y, x); + x.rShiftTo(1, x); + } else { + y.subTo(x, y); + y.rShiftTo(1, y); + } + } + if (g > 0) y.lShiftTo(g, y); + return y; + } + + // (protected) this % n, n < 2^26 + function bnpModInt(n) { + if (n <= 0) return 0; + var d = this.DV % n, + r = this.s < 0 ? n - 1 : 0; + if (this.t > 0) + if (d == 0) r = this[0] % n; + else for (var i = this.t - 1; i >= 0; --i) r = (d * r + this[i]) % n; + return r; + } + + // (public) 1/this % m (HAC 14.61) + function bnModInverse(m) { + var ac = m.isEven(); + if ((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO; + var u = m.clone(), + v = this.clone(); + var a = nbv(1), + b = nbv(0), + c = nbv(0), + d = nbv(1); + while (u.signum() != 0) { + while (u.isEven()) { + u.rShiftTo(1, u); + if (ac) { + if (!a.isEven() || !b.isEven()) { + a.addTo(this, a); + b.subTo(m, b); + } + a.rShiftTo(1, a); + } else if (!b.isEven()) b.subTo(m, b); + b.rShiftTo(1, b); + } + while (v.isEven()) { + v.rShiftTo(1, v); + if (ac) { + if (!c.isEven() || !d.isEven()) { + c.addTo(this, c); + d.subTo(m, d); + } + c.rShiftTo(1, c); + } else if (!d.isEven()) d.subTo(m, d); + d.rShiftTo(1, d); + } + if (u.compareTo(v) >= 0) { + u.subTo(v, u); + if (ac) a.subTo(c, a); + b.subTo(d, b); + } else { + v.subTo(u, v); + if (ac) c.subTo(a, c); + d.subTo(b, d); + } + } + if (v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO; + if (d.compareTo(m) >= 0) return d.subtract(m); + if (d.signum() < 0) d.addTo(m, d); + else return d; + if (d.signum() < 0) return d.add(m); + else return d; + } + + var lowprimes = [ + 2, + 3, + 5, + 7, + 11, + 13, + 17, + 19, + 23, + 29, + 31, + 37, + 41, + 43, + 47, + 53, + 59, + 61, + 67, + 71, + 73, + 79, + 83, + 89, + 97, + 101, + 103, + 107, + 109, + 113, + 127, + 131, + 137, + 139, + 149, + 151, + 157, + 163, + 167, + 173, + 179, + 181, + 191, + 193, + 197, + 199, + 211, + 223, + 227, + 229, + 233, + 239, + 241, + 251, + 257, + 263, + 269, + 271, + 277, + 281, + 283, + 293, + 307, + 311, + 313, + 317, + 331, + 337, + 347, + 349, + 353, + 359, + 367, + 373, + 379, + 383, + 389, + 397, + 401, + 409, + 419, + 421, + 431, + 433, + 439, + 443, + 449, + 457, + 461, + 463, + 467, + 479, + 487, + 491, + 499, + 503, + 509, + 521, + 523, + 541, + 547, + 557, + 563, + 569, + 571, + 577, + 587, + 593, + 599, + 601, + 607, + 613, + 617, + 619, + 631, + 641, + 643, + 647, + 653, + 659, + 661, + 673, + 677, + 683, + 691, + 701, + 709, + 719, + 727, + 733, + 739, + 743, + 751, + 757, + 761, + 769, + 773, + 787, + 797, + 809, + 811, + 821, + 823, + 827, + 829, + 839, + 853, + 857, + 859, + 863, + 877, + 881, + 883, + 887, + 907, + 911, + 919, + 929, + 937, + 941, + 947, + 953, + 967, + 971, + 977, + 983, + 991, + 997, + ]; + var lplim = (1 << 26) / lowprimes[lowprimes.length - 1]; + + // (public) test primality with certainty >= 1-.5^t + function bnIsProbablePrime(t) { + var i, + x = this.abs(); + if (x.t == 1 && x[0] <= lowprimes[lowprimes.length - 1]) { + for (i = 0; i < lowprimes.length; ++i) + if (x[0] == lowprimes[i]) return true; + return false; + } + if (x.isEven()) return false; + i = 1; + while (i < lowprimes.length) { + var m = lowprimes[i], + j = i + 1; + while (j < lowprimes.length && m < lplim) m *= lowprimes[j++]; + m = x.modInt(m); + while (i < j) if (m % lowprimes[i++] == 0) return false; + } + return x.millerRabin(t); + } + + // (protected) true if probably prime (HAC 4.24, Miller-Rabin) + function bnpMillerRabin(t) { + var n1 = this.subtract(BigInteger.ONE); + var k = n1.getLowestSetBit(); + if (k <= 0) return false; + var r = n1.shiftRight(k); + t = (t + 1) >> 1; + if (t > lowprimes.length) t = lowprimes.length; + var a = nbi(); + for (var i = 0; i < t; ++i) { + //Pick bases at random, instead of starting at 2 + a.fromInt(lowprimes[Math.floor(Math.random() * lowprimes.length)]); + var y = a.modPow(r, this); + if (y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { + var j = 1; + while (j++ < k && y.compareTo(n1) != 0) { + y = y.modPowInt(2, this); + if (y.compareTo(BigInteger.ONE) == 0) return false; + } + if (y.compareTo(n1) != 0) return false; + } + } + return true; + } + + // protected + BigInteger.prototype.chunkSize = bnpChunkSize; + BigInteger.prototype.toRadix = bnpToRadix; + BigInteger.prototype.fromRadix = bnpFromRadix; + BigInteger.prototype.fromNumber = bnpFromNumber; + BigInteger.prototype.bitwiseTo = bnpBitwiseTo; + BigInteger.prototype.changeBit = bnpChangeBit; + BigInteger.prototype.addTo = bnpAddTo; + BigInteger.prototype.dMultiply = bnpDMultiply; + BigInteger.prototype.dAddOffset = bnpDAddOffset; + BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo; + BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo; + BigInteger.prototype.modInt = bnpModInt; + BigInteger.prototype.millerRabin = bnpMillerRabin; + + // public + BigInteger.prototype.clone = bnClone; + BigInteger.prototype.intValue = bnIntValue; + BigInteger.prototype.byteValue = bnByteValue; + BigInteger.prototype.shortValue = bnShortValue; + BigInteger.prototype.signum = bnSigNum; + BigInteger.prototype.toByteArray = bnToByteArray; + BigInteger.prototype.equals = bnEquals; + BigInteger.prototype.min = bnMin; + BigInteger.prototype.max = bnMax; + BigInteger.prototype.and = bnAnd; + BigInteger.prototype.or = bnOr; + BigInteger.prototype.xor = bnXor; + BigInteger.prototype.andNot = bnAndNot; + BigInteger.prototype.not = bnNot; + BigInteger.prototype.shiftLeft = bnShiftLeft; + BigInteger.prototype.shiftRight = bnShiftRight; + BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit; + BigInteger.prototype.bitCount = bnBitCount; + BigInteger.prototype.testBit = bnTestBit; + BigInteger.prototype.setBit = bnSetBit; + BigInteger.prototype.clearBit = bnClearBit; + BigInteger.prototype.flipBit = bnFlipBit; + BigInteger.prototype.add = bnAdd; + BigInteger.prototype.subtract = bnSubtract; + BigInteger.prototype.multiply = bnMultiply; + BigInteger.prototype.divide = bnDivide; + BigInteger.prototype.remainder = bnRemainder; + BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder; + BigInteger.prototype.modPow = bnModPow; + BigInteger.prototype.modInverse = bnModInverse; + BigInteger.prototype.pow = bnPow; + BigInteger.prototype.gcd = bnGCD; + BigInteger.prototype.isProbablePrime = bnIsProbablePrime; + + // JSBN-specific extension + BigInteger.prototype.square = bnSquare; + + // Expose the Barrett function + BigInteger.prototype.Barrett = Barrett; + + // BigInteger interfaces not implemented in jsbn: + + // BigInteger(int signum, byte[] magnitude) + // double doubleValue() + // float floatValue() + // int hashCode() + // long longValue() + // static BigInteger valueOf(long val) + + // Imported from bitcoinjs-lib + + /** + * Turns a byte array into a big integer. + * + * This function will interpret a byte array as a big integer in big + * endian notation and ignore leading zeros. + */ + + BigInteger.fromByteArrayUnsigned = function (ba) { + + if (!ba.length) { + return new BigInteger.valueOf(0); + } else if (ba[0] & 0x80) { + // Prepend a zero so the BigInteger class doesn't mistake this + // for a negative integer. + return new BigInteger([0].concat(ba)); + } else { + return new BigInteger(ba); + } + }; + + /** + * Parse a signed big integer byte representation. + * + * For details on the format please see BigInteger.toByteArraySigned. + */ + + BigInteger.fromByteArraySigned = function (ba) { + // Check for negative value + if (ba[0] & 0x80) { + // Remove sign bit + ba[0] &= 0x7f; + + return BigInteger.fromByteArrayUnsigned(ba).negate(); + } else { + return BigInteger.fromByteArrayUnsigned(ba); + } + }; + + /** + * Returns a byte array representation of the big integer. + * + * This returns the absolute of the contained value in big endian + * form. A value of zero results in an empty array. + */ + + BigInteger.prototype.toByteArrayUnsigned = function () { + var ba = this.abs().toByteArray(); + + // Empty array, nothing to do + if (!ba.length) { + return ba; + } + + // remove leading 0 + if (ba[0] === 0) { + ba = ba.slice(1); + } + + // all values must be positive + for (var i = 0; i < ba.length; ++i) { + ba[i] = (ba[i] < 0) ? ba[i] + 256 : ba[i]; + } + + return ba; + }; + + /* + * Converts big integer to signed byte representation. + * + * The format for this value uses the most significant bit as a sign + * bit. If the most significant bit is already occupied by the + * absolute value, an extra byte is prepended and the sign bit is set + * there. + * + * Examples: + * + * 0 => 0x00 + * 1 => 0x01 + * -1 => 0x81 + * 127 => 0x7f + * -127 => 0xff + * 128 => 0x0080 + * -128 => 0x8080 + * 255 => 0x00ff + * -255 => 0x80ff + * 16300 => 0x3fac + * -16300 => 0xbfac + * 62300 => 0x00f35c + * -62300 => 0x80f35c + */ + + BigInteger.prototype.toByteArraySigned = function () { + var val = this.toByteArrayUnsigned(); + var neg = this.s < 0; + + // if the first bit is set, we always unshift + // either unshift 0x80 or 0x00 + if (val[0] & 0x80) { + val.unshift((neg) ? 0x80 : 0x00); + } + // if the first bit isn't set, set it if negative + else if (neg) { + val[0] |= 0x80; + } + + return val; + }; + + // Random number generator - requires a PRNG backend, e.g. prng4.js + + // For best results, put code like + // + // in your main HTML document. + + var rng_state; + var rng_pool; + var rng_pptr; + + // Mix in a 32-bit integer into the pool + function rng_seed_int(x) { + rng_pool[rng_pptr++] ^= x & 255; + rng_pool[rng_pptr++] ^= (x >> 8) & 255; + rng_pool[rng_pptr++] ^= (x >> 16) & 255; + rng_pool[rng_pptr++] ^= (x >> 24) & 255; + if (rng_pptr >= rng_psize) rng_pptr -= rng_psize; + } + + // Mix in the current time (w/milliseconds) into the pool + function rng_seed_time() { + rng_seed_int(new Date().getTime()); + } + + // Initialize the pool with junk if needed. + if (rng_pool == null) { + rng_pool = new Array(); + rng_pptr = 0; + var t; + if (typeof window !== 'undefined' && window.crypto) { + if (window.crypto.getRandomValues) { + // Use webcrypto if available + var ua = new Uint8Array(32); + window.crypto.getRandomValues(ua); + for (t = 0; t < 32; ++t) rng_pool[rng_pptr++] = ua[t]; + } else if ( + navigator.appName == 'Netscape' && + navigator.appVersion < '5' + ) { + // Extract entropy (256 bits) from NS4 RNG if available + var z = window.crypto.random(32); + for (t = 0; t < z.length; ++t) + rng_pool[rng_pptr++] = z.charCodeAt(t) & 255; + } + } + while (rng_pptr < rng_psize) { + // extract some randomness from Math.random() + t = Math.floor(65536 * Math.random()); + rng_pool[rng_pptr++] = t >>> 8; + rng_pool[rng_pptr++] = t & 255; + } + rng_pptr = 0; + rng_seed_time(); + } + + function rng_get_byte() { + if (rng_state == null) { + rng_seed_time(); + rng_state = prng_newstate(); + rng_state.init(rng_pool); + for (rng_pptr = 0; rng_pptr < rng_pool.length; ++rng_pptr) + rng_pool[rng_pptr] = 0; + rng_pptr = 0; + } + // TODO: allow reseeding after first request + return rng_state.next(); + } + + function rng_get_bytes(ba) { + var i; + for (i = 0; i < ba.length; ++i) ba[i] = rng_get_byte(); + } + + function SecureRandom() { } + + SecureRandom.prototype.nextBytes = rng_get_bytes; + + // prng4.js - uses Arcfour as a PRNG + + function Arcfour() { + this.i = 0; + this.j = 0; + this.S = new Array(); + } + + // Initialize arcfour context from key, an array of ints, each from [0..255] + function ARC4init(key) { + var i, j, t; + for (i = 0; i < 256; ++i) this.S[i] = i; + j = 0; + for (i = 0; i < 256; ++i) { + j = (j + this.S[i] + key[i % key.length]) & 255; + t = this.S[i]; + this.S[i] = this.S[j]; + this.S[j] = t; + } + this.i = 0; + this.j = 0; + } + + function ARC4next() { + var t; + this.i = (this.i + 1) & 255; + this.j = (this.j + this.S[this.i]) & 255; + t = this.S[this.i]; + this.S[this.i] = this.S[this.j]; + this.S[this.j] = t; + return this.S[(t + this.S[this.i]) & 255]; + } + + Arcfour.prototype.init = ARC4init; + Arcfour.prototype.next = ARC4next; + + // Plug in your RNG constructor here + function prng_newstate() { + return new Arcfour(); + } + + // Pool size must be a multiple of 4 and greater than 32. + // An array of bytes the size of the pool will be passed to init() + var rng_psize = 256; + + if (typeof exports !== 'undefined') { + exports = module.exports = { + default: BigInteger, + BigInteger: BigInteger, + SecureRandom: SecureRandom, + }; + } else { + this.jsbn = { + BigInteger: BigInteger, + SecureRandom: SecureRandom, + }; + } +}.call(this)); diff --git a/crypto/api/constants.js b/crypto/api/constants.js index c59f0faa..ebd180d3 100644 --- a/crypto/api/constants.js +++ b/crypto/api/constants.js @@ -1,5 +1,3 @@ -'use strict' - // Qortal TX types const TX_TYPES = { 1: "Genesis", diff --git a/crypto/api/createTransaction.js b/crypto/api/createTransaction.js index 3d9c19d9..c8b35543 100644 --- a/crypto/api/createTransaction.js +++ b/crypto/api/createTransaction.js @@ -1,9 +1,9 @@ -import {transactionTypes as transactions} from './transactions/transactions.js' -import Base58 from './deps/Base58.js' -import {request} from './fetch-request' -import signChat from './transactions/chat/signChat.js' -import signArbitrary from './transactions/arbitrary/signArbitrary.js' -import signArbitraryWithFee from './transactions/arbitrary/signArbitraryWithFee.js' +import { transactionTypes as transactions } from './transactions/transactions' +import Base58 from './deps/Base58' +import { request } from './fetch-request' +import signChat from './transactions/chat/signChat' +import signArbitrary from './transactions/arbitrary/signArbitrary' +import signArbitraryWithFee from './transactions/arbitrary/signArbitraryWithFee' export const createTransaction = (type, keyPair, params) => { const tx = new transactions[type]() @@ -31,8 +31,8 @@ export const signArbitraryTransaction = (arbitraryBytesBase58, arbitraryBytesFor return signArbitrary(arbitraryBytesBase58, arbitraryBytesForSigningBase58, nonce, keyPair) } -export const signArbitraryWithFeeTransaction = (arbitraryBytesBase58, arbitraryBytesForSigningBase58, keyPair) => { - return signArbitraryWithFee(arbitraryBytesBase58, arbitraryBytesForSigningBase58, keyPair) +export const signArbitraryWithFeeTransaction = (arbitraryBytesBase58, arbitraryBytesForSigningBase58, keyPair) => { + return signArbitraryWithFee(arbitraryBytesBase58, arbitraryBytesForSigningBase58, keyPair) } // Process Transactions diff --git a/crypto/api/createWallet.js b/crypto/api/createWallet.js index 1b05c93c..c9057af9 100644 --- a/crypto/api/createWallet.js +++ b/crypto/api/createWallet.js @@ -1,7 +1,7 @@ -import {kdf} from './kdf.js' -import PhraseWallet from './PhraseWallet.js' -import Base58 from './deps/Base58.js' -import {decryptStoredWallet} from './decryptStoredWallet.js' +import { kdf } from './kdf' +import PhraseWallet from './PhraseWallet' +import Base58 from './deps/Base58' +import { decryptStoredWallet } from './decryptStoredWallet' export const createWallet = async (sourceType, source, statusUpdateFn) => { let version, seed diff --git a/crypto/api/decryptStoredWallet.js b/crypto/api/decryptStoredWallet.js index ec8c8281..8fab5092 100644 --- a/crypto/api/decryptStoredWallet.js +++ b/crypto/api/decryptStoredWallet.js @@ -1,10 +1,10 @@ -import Base58 from './deps/Base58.js' -import {kdf} from './kdf.js' -import {AES_CBC, HmacSha512} from 'asmcrypto.js' -import {get, registerTranslateConfig} from '../../core/translate' +import Base58 from './deps/Base58' +import { kdf } from './kdf' +import { AES_CBC, HmacSha512 } from 'asmcrypto.js' +import { get, registerTranslateConfig } from '../../core/translate' registerTranslateConfig({ - loader: lang => fetch(`/language/${lang}.json`).then(res => res.json()) + loader: lang => fetch(`/language/${lang}.json`).then(res => res.json()) }) export const decryptStoredWallet = async (password, wallet, statusFn = () => { }) => { diff --git a/crypto/api/deps/Base58.js b/crypto/api/deps/Base58.js index c0caaca4..b5ac86ae 100644 --- a/crypto/api/deps/Base58.js +++ b/crypto/api/deps/Base58.js @@ -1,10 +1,6 @@ // Generated by CoffeeScript 1.8.0 // == Changed for ES6 modules == // -//(function() { -//var ALPHABET, ALPHABET_MAP, Base58, i; - -//const Base58 = (typeof module !== "undefined" && module !== null ? module.exports : void 0) || (window.Base58 = {}); const Base58 = {}; const ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; @@ -14,95 +10,92 @@ const ALPHABET_MAP = {}; let i = 0; while (i < ALPHABET.length) { -ALPHABET_MAP[ALPHABET.charAt(i)] = i; -i++; + ALPHABET_MAP[ALPHABET.charAt(i)] = i; + i++; } -Base58.encode = function(buffer) { -buffer = new Uint8Array(buffer); -var carry, digits, j; -if (buffer.length === 0) { - return ""; -} -i = void 0; -j = void 0; -digits = [0]; -i = 0; -while (i < buffer.length) { - j = 0; - while (j < digits.length) { - digits[j] <<= 8; - j++; - } - digits[0] += buffer[i]; - carry = 0; - j = 0; - while (j < digits.length) { - digits[j] += carry; - carry = (digits[j] / 58) | 0; - digits[j] %= 58; - ++j; - } - while (carry) { - digits.push(carry % 58); - carry = (carry / 58) | 0; - } - i++; -} -i = 0; -while (buffer[i] === 0 && i < buffer.length - 1) { - digits.push(0); - i++; -} -return digits.reverse().map(function(digit) { - return ALPHABET[digit]; -}).join(""); +Base58.encode = function (buffer) { + buffer = new Uint8Array(buffer); + var carry, digits, j; + if (buffer.length === 0) { + return ""; + } + i = void 0; + j = void 0; + digits = [0]; + i = 0; + while (i < buffer.length) { + j = 0; + while (j < digits.length) { + digits[j] <<= 8; + j++; + } + digits[0] += buffer[i]; + carry = 0; + j = 0; + while (j < digits.length) { + digits[j] += carry; + carry = (digits[j] / 58) | 0; + digits[j] %= 58; + ++j; + } + while (carry) { + digits.push(carry % 58); + carry = (carry / 58) | 0; + } + i++; + } + i = 0; + while (buffer[i] === 0 && i < buffer.length - 1) { + digits.push(0); + i++; + } + return digits.reverse().map(function (digit) { + return ALPHABET[digit]; + }).join(""); }; -Base58.decode = function(string) { -var bytes, c, carry, j; -if (string.length === 0) { - return new (typeof Uint8Array !== "undefined" && Uint8Array !== null ? Uint8Array : Buffer)(0); -} -i = void 0; -j = void 0; -bytes = [0]; -i = 0; -while (i < string.length) { - c = string[i]; - if (!(c in ALPHABET_MAP)) { - throw "Base58.decode received unacceptable input. Character '" + c + "' is not in the Base58 alphabet."; - } - j = 0; - while (j < bytes.length) { - bytes[j] *= 58; - j++; - } - bytes[0] += ALPHABET_MAP[c]; - carry = 0; - j = 0; - while (j < bytes.length) { - bytes[j] += carry; - carry = bytes[j] >> 8; - bytes[j] &= 0xff; - ++j; - } - while (carry) { - bytes.push(carry & 0xff); - carry >>= 8; - } - i++; -} -i = 0; -while (string[i] === "1" && i < string.length - 1) { - bytes.push(0); - i++; -} -return new (typeof Uint8Array !== "undefined" && Uint8Array !== null ? Uint8Array : Buffer)(bytes.reverse()); +Base58.decode = function (string) { + var bytes, c, carry, j; + if (string.length === 0) { + return new (typeof Uint8Array !== "undefined" && Uint8Array !== null ? Uint8Array : Buffer)(0); + } + i = void 0; + j = void 0; + bytes = [0]; + i = 0; + while (i < string.length) { + c = string[i]; + if (!(c in ALPHABET_MAP)) { + throw "Base58.decode received unacceptable input. Character '" + c + "' is not in the Base58 alphabet."; + } + j = 0; + while (j < bytes.length) { + bytes[j] *= 58; + j++; + } + bytes[0] += ALPHABET_MAP[c]; + carry = 0; + j = 0; + while (j < bytes.length) { + bytes[j] += carry; + carry = bytes[j] >> 8; + bytes[j] &= 0xff; + ++j; + } + while (carry) { + bytes.push(carry & 0xff); + carry >>= 8; + } + i++; + } + i = 0; + while (string[i] === "1" && i < string.length - 1) { + bytes.push(0); + i++; + } + return new (typeof Uint8Array !== "undefined" && Uint8Array !== null ? Uint8Array : Buffer)(bytes.reverse()); }; - // == Changed for ES6 modules == // -//}).call(this); - -export default Base58; \ No newline at end of file +export default Base58; diff --git a/crypto/api/deps/Base64.js b/crypto/api/deps/Base64.js index 1697dd6a..b97b3848 100644 --- a/crypto/api/deps/Base64.js +++ b/crypto/api/deps/Base64.js @@ -1,23 +1,18 @@ const Base64 = {}; - - Base64.decode = function (string) { - const binaryString = atob(string); - const binaryLength = binaryString.length; - const bytes = new Uint8Array(binaryLength); + const binaryString = atob(string); + const binaryLength = binaryString.length; + const bytes = new Uint8Array(binaryLength); - for (let i = 0; i < binaryLength; i++) { - bytes[i] = binaryString.charCodeAt(i); - } + for (let i = 0; i < binaryLength; i++) { + bytes[i] = binaryString.charCodeAt(i); + } - const decoder = new TextDecoder(); + const decoder = new TextDecoder(); return decoder.decode(bytes); }; - - - export default Base64; diff --git a/crypto/api/deps/bcrypt.js b/crypto/api/deps/bcrypt.js index b067a2fa..ce9e3ce9 100644 --- a/crypto/api/deps/bcrypt.js +++ b/crypto/api/deps/bcrypt.js @@ -31,1349 +31,1351 @@ * Released under the Apache License, Version 2.0 * see: https://github.com/dcodeIO/bcrypt.js for details */ -(function(global, factory) { +(function (global, factory) { /* AMD */ if (typeof define === 'function' && define["amd"]) - define([], factory); + define([], factory); /* CommonJS */ else if (typeof require === 'function' && typeof module === "object" && module && module["exports"]) - module["exports"] = factory(); + module["exports"] = factory(); /* Global */ else - (global["dcodeIO"] = global["dcodeIO"] || {})["bcrypt"] = factory(); + (global["dcodeIO"] = global["dcodeIO"] || {})["bcrypt"] = factory(); -}(this, function() { - "use strict"; +}(this, function () { + // == Changed for ESM support == // + // "use strict"; - /** - * bcrypt namespace. - * @type {Object.} - */ - var bcrypt = {}; + /** + * bcrypt namespace. + * @type {Object.} + */ + var bcrypt = {}; - /** - * The random implementation to use as a fallback. - * @type {?function(number):!Array.} - * @inner - */ - var randomFallback = null; + /** + * The random implementation to use as a fallback. + * @type {?function(number):!Array.} + * @inner + */ + var randomFallback = null; - /** - * Generates cryptographically secure random bytes. - * @function - * @param {number} len Bytes length - * @returns {!Array.} Random bytes - * @throws {Error} If no random implementation is available - * @inner - */ - function random(len) { + /** + * Generates cryptographically secure random bytes. + * @function + * @param {number} len Bytes length + * @returns {!Array.} Random bytes + * @throws {Error} If no random implementation is available + * @inner + */ + function random(len) { /* node */ if (typeof module !== 'undefined' && module && module['exports']) - try { - return require("crypto")['randomBytes'](len); - } catch (e) {} + try { + return require("crypto")['randomBytes'](len); + } catch (e) { } /* WCA */ try { - var a; (self['crypto']||self['msCrypto'])['getRandomValues'](a = new Uint32Array(len)); - return Array.prototype.slice.call(a); - } catch (e) {} + var a; (self['crypto'] || self['msCrypto'])['getRandomValues'](a = new Uint32Array(len)); + return Array.prototype.slice.call(a); + } catch (e) { } /* fallback */ if (!randomFallback) - throw Error("Neither WebCryptoAPI nor a crypto module is available. Use bcrypt.setRandomFallback to set an alternative"); - return randomFallback(len); - } - - // Test if any secure randomness source is available - var randomAvailable = false; - try { - random(1); - randomAvailable = true; - } catch (e) {} - - // Default fallback, if any - randomFallback = null; - /** - * Sets the pseudo random number generator to use as a fallback if neither node's `crypto` module nor the Web Crypto - * API is available. Please note: It is highly important that the PRNG used is cryptographically secure and that it - * is seeded properly! - * @param {?function(number):!Array.} random Function taking the number of bytes to generate as its - * sole argument, returning the corresponding array of cryptographically secure random byte values. - * @see http://nodejs.org/api/crypto.html - * @see http://www.w3.org/TR/WebCryptoAPI/ - */ - bcrypt.setRandomFallback = function(random) { - randomFallback = random; - }; - - /** - * Synchronously generates a salt. - * @param {number=} rounds Number of rounds to use, defaults to 10 if omitted - * @param {number=} seed_length Not supported. - * @returns {string} Resulting salt - * @throws {Error} If a random fallback is required but not set - * @expose - */ - bcrypt.genSaltSync = function(rounds, seed_length) { - rounds = rounds || GENSALT_DEFAULT_LOG2_ROUNDS; - if (typeof rounds !== 'number') - throw Error("Illegal arguments: "+(typeof rounds)+", "+(typeof seed_length)); - if (rounds < 4) - rounds = 4; - else if (rounds > 31) - rounds = 31; - var salt = []; - salt.push("$2a$"); - if (rounds < 10) - salt.push("0"); - salt.push(rounds.toString()); - salt.push('$'); - salt.push(base64_encode(random(BCRYPT_SALT_LEN), BCRYPT_SALT_LEN)); // May throw - return salt.join(''); - }; - - /** - * Asynchronously generates a salt. - * @param {(number|function(Error, string=))=} rounds Number of rounds to use, defaults to 10 if omitted - * @param {(number|function(Error, string=))=} seed_length Not supported. - * @param {function(Error, string=)=} callback Callback receiving the error, if any, and the resulting salt - * @returns {!Promise} If `callback` has been omitted - * @throws {Error} If `callback` is present but not a function - * @expose - */ - bcrypt.genSalt = function(rounds, seed_length, callback) { - if (typeof seed_length === 'function') - callback = seed_length, - seed_length = undefined; // Not supported. - if (typeof rounds === 'function') - callback = rounds, - rounds = undefined; - if (typeof rounds === 'undefined') - rounds = GENSALT_DEFAULT_LOG2_ROUNDS; - else if (typeof rounds !== 'number') - throw Error("illegal arguments: "+(typeof rounds)); - - function _async(callback) { - nextTick(function() { // Pretty thin, but salting is fast enough - try { - callback(null, bcrypt.genSaltSync(rounds)); - } catch (err) { - callback(err); - } - }); - } - - if (callback) { - if (typeof callback !== 'function') - throw Error("Illegal callback: "+typeof(callback)); - _async(callback); - } else - return new Promise(function(resolve, reject) { - _async(function(err, res) { - if (err) { - reject(err); - return; - } - resolve(res); - }); - }); - }; - - /** - * Synchronously generates a hash for the given string. - * @param {string} s String to hash - * @param {(number|string)=} salt Salt length to generate or salt to use, default to 10 - * @returns {string} Resulting hash - * @expose - */ - bcrypt.hashSync = function(s, salt) { - if (typeof salt === 'undefined') - salt = GENSALT_DEFAULT_LOG2_ROUNDS; - if (typeof salt === 'number') - salt = bcrypt.genSaltSync(salt); - if (typeof s !== 'string' || typeof salt !== 'string') - throw Error("Illegal arguments: "+(typeof s)+', '+(typeof salt)); - return _hash(s, salt); - }; - - /** - * Asynchronously generates a hash for the given string. - * @param {string} s String to hash - * @param {number|string} salt Salt length to generate or salt to use - * @param {function(Error, string=)=} callback Callback receiving the error, if any, and the resulting hash - * @param {function(number)=} progressCallback Callback successively called with the percentage of rounds completed - * (0.0 - 1.0), maximally once per `MAX_EXECUTION_TIME = 100` ms. - * @returns {!Promise} If `callback` has been omitted - * @throws {Error} If `callback` is present but not a function - * @expose - */ - bcrypt.hash = function(s, salt, callback, progressCallback) { - - function _async(callback) { - if (typeof s === 'string' && typeof salt === 'number') - bcrypt.genSalt(salt, function(err, salt) { - _hash(s, salt, callback, progressCallback); - }); - else if (typeof s === 'string' && typeof salt === 'string') - _hash(s, salt, callback, progressCallback); - else - nextTick(callback.bind(this, Error("Illegal arguments: "+(typeof s)+', '+(typeof salt)))); - } - - if (callback) { - if (typeof callback !== 'function') - throw Error("Illegal callback: "+typeof(callback)); - _async(callback); - } else - return new Promise(function(resolve, reject) { - _async(function(err, res) { - if (err) { - reject(err); - return; - } - resolve(res); - }); - }); - }; - - /** - * Compares two strings of the same length in constant time. - * @param {string} known Must be of the correct length - * @param {string} unknown Must be the same length as `known` - * @returns {boolean} - * @inner - */ - function safeStringCompare(known, unknown) { - var right = 0, - wrong = 0; - for (var i=0, k=known.length; i} UTF8 bytes - * @inner - */ - function stringToBytes(str) { - var out = [], - i = 0; - utfx.encodeUTF16toUTF8(function() { - if (i >= str.length) return null; - return str.charCodeAt(i++); - }, function(b) { - out.push(b); - }); - return out; - } - - // A base64 implementation for the bcrypt algorithm. This is partly non-standard. - - /** - * bcrypt's own non-standard base64 dictionary. - * @type {!Array.} - * @const - * @inner - **/ - var BASE64_CODE = "./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split(''); - - /** - * @type {!Array.} - * @const - * @inner - **/ - var BASE64_INDEX = [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, - 1, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, -1, -1, -1, -1, -1, -1, - -1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, - 20, 21, 22, 23, 24, 25, 26, 27, -1, -1, -1, -1, -1, -1, 28, 29, 30, - 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, - 48, 49, 50, 51, 52, 53, -1, -1, -1, -1, -1]; - - /** - * @type {!function(...number):string} - * @inner - */ - var stringFromCharCode = String.fromCharCode; - - /** - * Encodes a byte array to base64 with up to len bytes of input. - * @param {!Array.} b Byte array - * @param {number} len Maximum input length - * @returns {string} - * @inner - */ - function base64_encode(b, len) { - var off = 0, - rs = [], - c1, c2; - if (len <= 0 || len > b.length) - throw Error("Illegal len: "+len); - while (off < len) { - c1 = b[off++] & 0xff; - rs.push(BASE64_CODE[(c1 >> 2) & 0x3f]); - c1 = (c1 & 0x03) << 4; - if (off >= len) { - rs.push(BASE64_CODE[c1 & 0x3f]); - break; - } - c2 = b[off++] & 0xff; - c1 |= (c2 >> 4) & 0x0f; - rs.push(BASE64_CODE[c1 & 0x3f]); - c1 = (c2 & 0x0f) << 2; - if (off >= len) { - rs.push(BASE64_CODE[c1 & 0x3f]); - break; - } - c2 = b[off++] & 0xff; - c1 |= (c2 >> 6) & 0x03; - rs.push(BASE64_CODE[c1 & 0x3f]); - rs.push(BASE64_CODE[c2 & 0x3f]); - } - return rs.join(''); - } - - /** - * Decodes a base64 encoded string to up to len bytes of output. - * @param {string} s String to decode - * @param {number} len Maximum output length - * @returns {!Array.} - * @inner - */ - function base64_decode(s, len) { - var off = 0, - slen = s.length, - olen = 0, - rs = [], - c1, c2, c3, c4, o, code; - if (len <= 0) - throw Error("Illegal len: "+len); - while (off < slen - 1 && olen < len) { - code = s.charCodeAt(off++); - c1 = code < BASE64_INDEX.length ? BASE64_INDEX[code] : -1; - code = s.charCodeAt(off++); - c2 = code < BASE64_INDEX.length ? BASE64_INDEX[code] : -1; - if (c1 == -1 || c2 == -1) - break; - o = (c1 << 2) >>> 0; - o |= (c2 & 0x30) >> 4; - rs.push(stringFromCharCode(o)); - if (++olen >= len || off >= slen) - break; - code = s.charCodeAt(off++); - c3 = code < BASE64_INDEX.length ? BASE64_INDEX[code] : -1; - if (c3 == -1) - break; - o = ((c2 & 0x0f) << 4) >>> 0; - o |= (c3 & 0x3c) >> 2; - rs.push(stringFromCharCode(o)); - if (++olen >= len || off >= slen) - break; - code = s.charCodeAt(off++); - c4 = code < BASE64_INDEX.length ? BASE64_INDEX[code] : -1; - o = ((c3 & 0x03) << 6) >>> 0; - o |= c4; - rs.push(stringFromCharCode(o)); - ++olen; - } - var res = []; - for (off = 0; off - * Released under the Apache License, Version 2.0 - * see: https://github.com/dcodeIO/utfx for details - */ - var utfx = function() { - "use strict"; - - /** - * utfx namespace. - * @inner - * @type {!Object.} - */ - var utfx = {}; - - /** - * Maximum valid code point. - * @type {number} - * @const - */ - utfx.MAX_CODEPOINT = 0x10FFFF; - - /** - * Encodes UTF8 code points to UTF8 bytes. - * @param {(!function():number|null) | number} src Code points source, either as a function returning the next code point - * respectively `null` if there are no more code points left or a single numeric code point. - * @param {!function(number)} dst Bytes destination as a function successively called with the next byte - */ - utfx.encodeUTF8 = function(src, dst) { - var cp = null; - if (typeof src === 'number') - cp = src, - src = function() { return null; }; - while (cp !== null || (cp = src()) !== null) { - if (cp < 0x80) - dst(cp&0x7F); - else if (cp < 0x800) - dst(((cp>>6)&0x1F)|0xC0), - dst((cp&0x3F)|0x80); - else if (cp < 0x10000) - dst(((cp>>12)&0x0F)|0xE0), - dst(((cp>>6)&0x3F)|0x80), - dst((cp&0x3F)|0x80); - else - dst(((cp>>18)&0x07)|0xF0), - dst(((cp>>12)&0x3F)|0x80), - dst(((cp>>6)&0x3F)|0x80), - dst((cp&0x3F)|0x80); - cp = null; - } - }; - - /** - * Decodes UTF8 bytes to UTF8 code points. - * @param {!function():number|null} src Bytes source as a function returning the next byte respectively `null` if there - * are no more bytes left. - * @param {!function(number)} dst Code points destination as a function successively called with each decoded code point. - * @throws {RangeError} If a starting byte is invalid in UTF8 - * @throws {Error} If the last sequence is truncated. Has an array property `bytes` holding the - * remaining bytes. - */ - utfx.decodeUTF8 = function(src, dst) { - var a, b, c, d, fail = function(b) { - b = b.slice(0, b.indexOf(null)); - var err = Error(b.toString()); - err.name = "TruncatedError"; - err['bytes'] = b; - throw err; - }; - while ((a = src()) !== null) { - if ((a&0x80) === 0) - dst(a); - else if ((a&0xE0) === 0xC0) - ((b = src()) === null) && fail([a, b]), - dst(((a&0x1F)<<6) | (b&0x3F)); - else if ((a&0xF0) === 0xE0) - ((b=src()) === null || (c=src()) === null) && fail([a, b, c]), - dst(((a&0x0F)<<12) | ((b&0x3F)<<6) | (c&0x3F)); - else if ((a&0xF8) === 0xF0) - ((b=src()) === null || (c=src()) === null || (d=src()) === null) && fail([a, b, c ,d]), - dst(((a&0x07)<<18) | ((b&0x3F)<<12) | ((c&0x3F)<<6) | (d&0x3F)); - else throw RangeError("Illegal starting byte: "+a); - } - }; - - /** - * Converts UTF16 characters to UTF8 code points. - * @param {!function():number|null} src Characters source as a function returning the next char code respectively - * `null` if there are no more characters left. - * @param {!function(number)} dst Code points destination as a function successively called with each converted code - * point. - */ - utfx.UTF16toUTF8 = function(src, dst) { - var c1, c2 = null; - while (true) { - if ((c1 = c2 !== null ? c2 : src()) === null) - break; - if (c1 >= 0xD800 && c1 <= 0xDFFF) { - if ((c2 = src()) !== null) { - if (c2 >= 0xDC00 && c2 <= 0xDFFF) { - dst((c1-0xD800)*0x400+c2-0xDC00+0x10000); - c2 = null; continue; - } - } - } - dst(c1); - } - if (false) dst(c2); - }; - - /** - * Converts UTF8 code points to UTF16 characters. - * @param {(!function():number|null) | number} src Code points source, either as a function returning the next code point - * respectively `null` if there are no more code points left or a single numeric code point. - * @param {!function(number)} dst Characters destination as a function successively called with each converted char code. - * @throws {RangeError} If a code point is out of range - */ - utfx.UTF8toUTF16 = function(src, dst) { - var cp = null; - if (typeof src === 'number') - cp = src, src = function() { return null; }; - while (cp !== null || (cp = src()) !== null) { - if (cp <= 0xFFFF) - dst(cp); - else - cp -= 0x10000, - dst((cp>>10)+0xD800), - dst((cp%0x400)+0xDC00); - cp = null; - } - }; - - /** - * Converts and encodes UTF16 characters to UTF8 bytes. - * @param {!function():number|null} src Characters source as a function returning the next char code respectively `null` - * if there are no more characters left. - * @param {!function(number)} dst Bytes destination as a function successively called with the next byte. - */ - utfx.encodeUTF16toUTF8 = function(src, dst) { - utfx.UTF16toUTF8(src, function(cp) { - utfx.encodeUTF8(cp, dst); - }); - }; - - /** - * Decodes and converts UTF8 bytes to UTF16 characters. - * @param {!function():number|null} src Bytes source as a function returning the next byte respectively `null` if there - * are no more bytes left. - * @param {!function(number)} dst Characters destination as a function successively called with each converted char code. - * @throws {RangeError} If a starting byte is invalid in UTF8 - * @throws {Error} If the last sequence is truncated. Has an array property `bytes` holding the remaining bytes. - */ - utfx.decodeUTF8toUTF16 = function(src, dst) { - utfx.decodeUTF8(src, function(cp) { - utfx.UTF8toUTF16(cp, dst); - }); - }; - - /** - * Calculates the byte length of an UTF8 code point. - * @param {number} cp UTF8 code point - * @returns {number} Byte length - */ - utfx.calculateCodePoint = function(cp) { - return (cp < 0x80) ? 1 : (cp < 0x800) ? 2 : (cp < 0x10000) ? 3 : 4; - }; - - /** - * Calculates the number of UTF8 bytes required to store UTF8 code points. - * @param {(!function():number|null)} src Code points source as a function returning the next code point respectively - * `null` if there are no more code points left. - * @returns {number} The number of UTF8 bytes required - */ - utfx.calculateUTF8 = function(src) { - var cp, l=0; - while ((cp = src()) !== null) - l += utfx.calculateCodePoint(cp); - return l; - }; - - /** - * Calculates the number of UTF8 code points respectively UTF8 bytes required to store UTF16 char codes. - * @param {(!function():number|null)} src Characters source as a function returning the next char code respectively - * `null` if there are no more characters left. - * @returns {!Array.} The number of UTF8 code points at index 0 and the number of UTF8 bytes required at index 1. - */ - utfx.calculateUTF16asUTF8 = function(src) { - var n=0, l=0; - utfx.UTF16toUTF8(src, function(cp) { - ++n; l += utfx.calculateCodePoint(cp); - }); - return [n,l]; - }; - - return utfx; - }(); - - Date.now = Date.now || function() { return +new Date; }; - - /** - * @type {number} - * @const - * @inner - */ - var BCRYPT_SALT_LEN = 16; - - /** - * @type {number} - * @const - * @inner - */ - var GENSALT_DEFAULT_LOG2_ROUNDS = 10; - - /** - * @type {number} - * @const - * @inner - */ - var BLOWFISH_NUM_ROUNDS = 16; - - /** - * @type {number} - * @const - * @inner - */ - var MAX_EXECUTION_TIME = 100; - - /** - * @type {Array.} - * @const - * @inner - */ - var P_ORIG = [ - 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, - 0x299f31d0, 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, - 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, - 0xb5470917, 0x9216d5d9, 0x8979fb1b - ]; - - /** - * @type {Array.} - * @const - * @inner - */ - var S_ORIG = [ - 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, - 0x6a267e96, 0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, - 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, 0xa458fea3, - 0xf4933d7e, 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, - 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013, 0xc5d1b023, - 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, - 0x6c9e0e8b, 0xb01e8a3e, 0xd71577c1, 0xbd314b27, 0x78af2fda, - 0x55605c60, 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, - 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, 0xa15486af, - 0x7c72e993, 0xb3ee1411, 0x636fbc2a, 0x2ba9c55d, 0x741831f6, - 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, 0x7a325381, - 0x28958677, 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, - 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, 0xef845d5d, - 0xe98575b1, 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, - 0x0f6d6ff3, 0x83f44239, 0x2e0b4482, 0xa4842004, 0x69c8f04a, - 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0, - 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, 0x6eef0b6c, - 0x137a3be4, 0xba3bf050, 0x7efb2a98, 0xa1f1651d, 0x39af0176, - 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, - 0x3b8b5ebe, 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, - 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d, 0x37d0d724, - 0xd00a1248, 0xdb0fead3, 0x49f1c09b, 0x075372c9, 0x80991b7b, - 0x25d479d8, 0xf6e8def7, 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, - 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463, - 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, - 0x9b30952c, 0xcc814544, 0xaf5ebd09, 0xbee3d004, 0xde334afd, - 0x660f2807, 0x192e4bb3, 0xc0cba857, 0x45c8740f, 0xd20b5f39, - 0xb9d3fbdb, 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, - 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8, 0x3c7516df, - 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, - 0x53317b48, 0x3e00df82, 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, - 0xdf1769db, 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, - 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, - 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b, 0x9a53e479, 0xb6f84565, - 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, - 0xcee4c6e8, 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, - 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, 0xd08ed1d0, - 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, - 0x8888b812, 0x900df01c, 0x4fad5ea0, 0x688fc31c, 0xd1cff191, - 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1, - 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, 0xb4a84fe0, - 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, 0x165fa266, 0x80957705, - 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, - 0xfb9d35cf, 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, - 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af, 0x2464369b, - 0xf009b91e, 0x5563911d, 0x59dfa6aa, 0x78c14389, 0xd95a537f, - 0x207d5ba2, 0x02e5b9c5, 0x83260376, 0x6295cfa9, 0x11c81968, - 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915, - 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, - 0x571be91f, 0xf296ec6b, 0x2a0dd915, 0xb6636521, 0xe7b9f9b6, - 0xff34052e, 0xc5855664, 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, - 0x6e85076a, 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, - 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266, 0xecaa8c71, - 0x699a17ff, 0x5664526c, 0xc2b19ee1, 0x193602a5, 0x75094c29, - 0xa0591340, 0xe4183a3e, 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, - 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1, - 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, - 0x3ebaefc9, 0x3c971814, 0x6b6a70a1, 0x687f3584, 0x52a0e286, - 0xb79c5305, 0xaa500737, 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, - 0x5716f2b8, 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, - 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd, 0xd19113f9, - 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, - 0xc8b57634, 0x9af3dda7, 0xa9446146, 0x0fd0030e, 0xecc8c73e, - 0xa4751e41, 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, - 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, 0x2cb81290, - 0x24977c79, 0x5679b072, 0xbcaf89af, 0xde9a771f, 0xd9930810, - 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, 0x501adde6, - 0x9f84cd87, 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, - 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, 0xef1c1847, - 0x3215d908, 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, - 0x50940002, 0x133ae4dd, 0x71dff89e, 0x10314e55, 0x81ac77d6, - 0x5f11199b, 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509, - 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, 0x86e34570, - 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, 0x771fe71c, 0x4e3d06fa, - 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, - 0x9c10b36a, 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, - 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960, 0x5223a708, - 0xf71312b6, 0xebadfe6e, 0xeac31f66, 0xe3bc4595, 0xa67bc883, - 0xb17f37d1, 0x018cff28, 0xc332ddef, 0xbe6c5aa5, 0x65582185, - 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84, - 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, - 0xeb61bd96, 0x0334fe1e, 0xaa0363cf, 0xb5735c90, 0x4c70a239, - 0xd59e9e0b, 0xcbaade14, 0xeecc86bc, 0x60622ca7, 0x9cab5cab, - 0xb2f3846e, 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, - 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7, 0x9b540b19, - 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, - 0x11ed935f, 0x16681281, 0x0e358829, 0xc7e61fd6, 0x96dedfa1, - 0x7858ba99, 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, - 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, - 0x34c6ffea, 0xfe28ed61, 0xee7c3c73, 0x5d4a14d9, 0xe864b7e3, - 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, - 0xfacb4fd0, 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, - 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, 0xcf62a1f2, - 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, - 0x47848a0b, 0x5692b285, 0x095bbf00, 0xad19489d, 0x1462b174, - 0x23820e00, 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061, - 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, 0x7cde3759, - 0xcbee7460, 0x4085f2a7, 0xce77326e, 0xa6078084, 0x19f8509e, - 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, - 0x800bcadc, 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, - 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340, 0xc5c43465, - 0x713e38d8, 0x3d28f89e, 0xf16dff20, 0x153e21e7, 0x8fb03d4a, - 0xe6e39f2b, 0xdb83adf7, 0xe93d5a68, 0x948140f7, 0xf64c261c, - 0x94692934, 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068, - 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, 0x1e39f62e, - 0x97244546, 0x14214f74, 0xbf8b8840, 0x4d95fc1d, 0x96b591af, - 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, - 0x31cb8504, 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, - 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb, 0x68dc1462, - 0xd7486900, 0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c, - 0xb58ce006, 0x7af4d6b6, 0xaace1e7c, 0xd3375fec, 0xce78a399, - 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b, - 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, - 0xdd5b4332, 0x6841e7f7, 0xca7820fb, 0xfb0af54e, 0xd8feb397, - 0x454056ac, 0xba489527, 0x55533a3a, 0x20838d87, 0xfe6ba9b7, - 0xd096954b, 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, - 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c, 0xfdf8e802, - 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, - 0x48c1133f, 0xc70f86dc, 0x07f9c9ee, 0x41041f0f, 0x404779a4, - 0x5d886e17, 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, - 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, - 0x02e1329e, 0xaf664fd1, 0xcad18115, 0x6b2395e0, 0x333e92e1, - 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, - 0x2da2f728, 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, - 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, 0x0a476341, - 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, - 0x991be14c, 0xdb6e6b0d, 0xc67b5510, 0x6d672c37, 0x2765d43b, - 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b, - 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, 0xbb132f88, - 0x515bad24, 0x7b9479bf, 0x763bd6eb, 0x37392eb3, 0xcc115979, - 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, - 0x782ef11c, 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, - 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9, 0x44421659, - 0x0a121386, 0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f, - 0xbebfe988, 0x64e4c3fe, 0x9dbc8057, 0xf0f7c086, 0x60787bf8, - 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc, - 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, - 0xbde8ae24, 0x55464299, 0xbf582e61, 0x4e58f48f, 0xf2ddfda2, - 0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74, 0xb475f255, - 0x46fcd9b9, 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, - 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c, 0xb90bace1, - 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, - 0x662d09a1, 0xc4324633, 0xe85a1f02, 0x09f0be8c, 0x4a99a025, - 0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, - 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, - 0xa70683fa, 0xa002b5c4, 0x0de6d027, 0x9af88c27, 0x773f8641, - 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, 0x006058aa, - 0x30dc7d62, 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, - 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, 0x6f05e409, - 0x4b7c0188, 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, - 0x1ac15bb4, 0xd39eb8fc, 0xed545578, 0x08fca5b5, 0xd83d7cd3, - 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c, - 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, 0xd79a3234, - 0x92638212, 0x670efa8e, 0x406000e0, 0x3a39ce37, 0xd3faf5cf, - 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, 0xd3822740, - 0x99bc9bbe, 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, - 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, 0x5748ab2f, - 0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, - 0xd5730a1d, 0x4cd04dc6, 0x2939bbdb, 0xa9ba4650, 0xac9526e8, - 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22, - 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, 0x83c061ba, - 0x9be96a4d, 0x8fe51550, 0xba645bd6, 0x2826a2f9, 0xa73a3ae1, - 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, - 0x77fa0a59, 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, - 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51, 0x96d5ac3a, - 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, 0x1f9f25cf, 0xadf2b89b, - 0x5ad6b472, 0x5a88f54c, 0xe029ac71, 0xe019a5e6, 0x47b0acfd, - 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28, - 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, - 0x88f46dba, 0x03a16125, 0x0564f0bd, 0xc3eb9e15, 0x3c9057a2, - 0x97271aec, 0xa93a072a, 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, - 0x26dcf319, 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, - 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f, 0x4de81751, - 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, - 0x5121ce64, 0x774fbe32, 0xa8b6e37e, 0xc3293d46, 0x48de5369, - 0x6413e680, 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, - 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, - 0x1b588d40, 0xccd2017f, 0x6bb4e3bb, 0xdda26a7e, 0x3a59ff45, - 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, 0x8d6612ae, - 0xbf3c6f47, 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, - 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, 0x4040cb08, - 0x4eb4e2cc, 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, - 0x06b89fb4, 0xce6ea048, 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, - 0x277227f8, 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd, - 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, 0xe01cc87e, - 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, 0x1a908749, 0xd44fbd9a, - 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, - 0xe0b12b4f, 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, - 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525, 0xfae59361, - 0xceb69ceb, 0xc2a86459, 0x12baa8d1, 0xb6c1075e, 0xe3056a0c, - 0x10d25065, 0xcb03a442, 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, - 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e, - 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, - 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d, 0xe54cda54, 0x1edad891, - 0xce6279cf, 0xcd3e7e6f, 0x1618b166, 0xfd2c1d05, 0x848fd2c5, - 0xf6fb2299, 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, - 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc, 0xde966292, - 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, - 0x45e1d006, 0xc3f27b9a, 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, - 0x35bdd2f6, 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, - 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, 0xba38209c, - 0xf746ce76, 0x77afa1c5, 0x20756060, 0x85cbfe4e, 0x8ae88dd8, - 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, - 0xd6ebe1f9, 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, - 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6 - ]; - - /** - * @type {Array.} - * @const - * @inner - */ - var C_ORIG = [ - 0x4f727068, 0x65616e42, 0x65686f6c, 0x64657253, 0x63727944, - 0x6f756274 - ]; - - /** - * @param {Array.} lr - * @param {number} off - * @param {Array.} P - * @param {Array.} S - * @returns {Array.} - * @inner - */ - function _encipher(lr, off, P, S) { // This is our bottleneck: 1714/1905 ticks / 90% - see profile.txt - var n, - l = lr[off], - r = lr[off + 1]; - - l ^= P[0]; - - /* - for (var i=0, k=BLOWFISH_NUM_ROUNDS-2; i<=k;) - // Feistel substitution on left word - n = S[l >>> 24], - n += S[0x100 | ((l >> 16) & 0xff)], - n ^= S[0x200 | ((l >> 8) & 0xff)], - n += S[0x300 | (l & 0xff)], - r ^= n ^ P[++i], - // Feistel substitution on right word - n = S[r >>> 24], - n += S[0x100 | ((r >> 16) & 0xff)], - n ^= S[0x200 | ((r >> 8) & 0xff)], - n += S[0x300 | (r & 0xff)], - l ^= n ^ P[++i]; - */ - - //The following is an unrolled version of the above loop. - //Iteration 0 - n = S[l >>> 24]; - n += S[0x100 | ((l >> 16) & 0xff)]; - n ^= S[0x200 | ((l >> 8) & 0xff)]; - n += S[0x300 | (l & 0xff)]; - r ^= n ^ P[1]; - n = S[r >>> 24]; - n += S[0x100 | ((r >> 16) & 0xff)]; - n ^= S[0x200 | ((r >> 8) & 0xff)]; - n += S[0x300 | (r & 0xff)]; - l ^= n ^ P[2]; - //Iteration 1 - n = S[l >>> 24]; - n += S[0x100 | ((l >> 16) & 0xff)]; - n ^= S[0x200 | ((l >> 8) & 0xff)]; - n += S[0x300 | (l & 0xff)]; - r ^= n ^ P[3]; - n = S[r >>> 24]; - n += S[0x100 | ((r >> 16) & 0xff)]; - n ^= S[0x200 | ((r >> 8) & 0xff)]; - n += S[0x300 | (r & 0xff)]; - l ^= n ^ P[4]; - //Iteration 2 - n = S[l >>> 24]; - n += S[0x100 | ((l >> 16) & 0xff)]; - n ^= S[0x200 | ((l >> 8) & 0xff)]; - n += S[0x300 | (l & 0xff)]; - r ^= n ^ P[5]; - n = S[r >>> 24]; - n += S[0x100 | ((r >> 16) & 0xff)]; - n ^= S[0x200 | ((r >> 8) & 0xff)]; - n += S[0x300 | (r & 0xff)]; - l ^= n ^ P[6]; - //Iteration 3 - n = S[l >>> 24]; - n += S[0x100 | ((l >> 16) & 0xff)]; - n ^= S[0x200 | ((l >> 8) & 0xff)]; - n += S[0x300 | (l & 0xff)]; - r ^= n ^ P[7]; - n = S[r >>> 24]; - n += S[0x100 | ((r >> 16) & 0xff)]; - n ^= S[0x200 | ((r >> 8) & 0xff)]; - n += S[0x300 | (r & 0xff)]; - l ^= n ^ P[8]; - //Iteration 4 - n = S[l >>> 24]; - n += S[0x100 | ((l >> 16) & 0xff)]; - n ^= S[0x200 | ((l >> 8) & 0xff)]; - n += S[0x300 | (l & 0xff)]; - r ^= n ^ P[9]; - n = S[r >>> 24]; - n += S[0x100 | ((r >> 16) & 0xff)]; - n ^= S[0x200 | ((r >> 8) & 0xff)]; - n += S[0x300 | (r & 0xff)]; - l ^= n ^ P[10]; - //Iteration 5 - n = S[l >>> 24]; - n += S[0x100 | ((l >> 16) & 0xff)]; - n ^= S[0x200 | ((l >> 8) & 0xff)]; - n += S[0x300 | (l & 0xff)]; - r ^= n ^ P[11]; - n = S[r >>> 24]; - n += S[0x100 | ((r >> 16) & 0xff)]; - n ^= S[0x200 | ((r >> 8) & 0xff)]; - n += S[0x300 | (r & 0xff)]; - l ^= n ^ P[12]; - //Iteration 6 - n = S[l >>> 24]; - n += S[0x100 | ((l >> 16) & 0xff)]; - n ^= S[0x200 | ((l >> 8) & 0xff)]; - n += S[0x300 | (l & 0xff)]; - r ^= n ^ P[13]; - n = S[r >>> 24]; - n += S[0x100 | ((r >> 16) & 0xff)]; - n ^= S[0x200 | ((r >> 8) & 0xff)]; - n += S[0x300 | (r & 0xff)]; - l ^= n ^ P[14]; - //Iteration 7 - n = S[l >>> 24]; - n += S[0x100 | ((l >> 16) & 0xff)]; - n ^= S[0x200 | ((l >> 8) & 0xff)]; - n += S[0x300 | (l & 0xff)]; - r ^= n ^ P[15]; - n = S[r >>> 24]; - n += S[0x100 | ((r >> 16) & 0xff)]; - n ^= S[0x200 | ((r >> 8) & 0xff)]; - n += S[0x300 | (r & 0xff)]; - l ^= n ^ P[16]; - - lr[off] = r ^ P[BLOWFISH_NUM_ROUNDS + 1]; - lr[off + 1] = l; - return lr; - } - - /** - * @param {Array.} data - * @param {number} offp - * @returns {{key: number, offp: number}} - * @inner - */ - function _streamtoword(data, offp) { - for (var i = 0, word = 0; i < 4; ++i) - word = (word << 8) | (data[offp] & 0xff), - offp = (offp + 1) % data.length; - return { key: word, offp: offp }; - } - - /** - * @param {Array.} key - * @param {Array.} P - * @param {Array.} S - * @inner - */ - function _key(key, P, S) { - var offset = 0, - lr = [0, 0], - plen = P.length, - slen = S.length, - sw; - for (var i = 0; i < plen; i++) - sw = _streamtoword(key, offset), - offset = sw.offp, - P[i] = P[i] ^ sw.key; - for (i = 0; i < plen; i += 2) - lr = _encipher(lr, 0, P, S), - P[i] = lr[0], - P[i + 1] = lr[1]; - for (i = 0; i < slen; i += 2) - lr = _encipher(lr, 0, P, S), - S[i] = lr[0], - S[i + 1] = lr[1]; - } - - /** - * Expensive key schedule Blowfish. - * @param {Array.} data - * @param {Array.} key - * @param {Array.} P - * @param {Array.} S - * @inner - */ - function _ekskey(data, key, P, S) { - var offp = 0, - lr = [0, 0], - plen = P.length, - slen = S.length, - sw; - for (var i = 0; i < plen; i++) - sw = _streamtoword(key, offp), - offp = sw.offp, - P[i] = P[i] ^ sw.key; - offp = 0; - for (i = 0; i < plen; i += 2) - sw = _streamtoword(data, offp), - offp = sw.offp, - lr[0] ^= sw.key, - sw = _streamtoword(data, offp), - offp = sw.offp, - lr[1] ^= sw.key, - lr = _encipher(lr, 0, P, S), - P[i] = lr[0], - P[i + 1] = lr[1]; - for (i = 0; i < slen; i += 2) - sw = _streamtoword(data, offp), - offp = sw.offp, - lr[0] ^= sw.key, - sw = _streamtoword(data, offp), - offp = sw.offp, - lr[1] ^= sw.key, - lr = _encipher(lr, 0, P, S), - S[i] = lr[0], - S[i + 1] = lr[1]; - } - - /** - * Internaly crypts a string. - * @param {Array.} b Bytes to crypt - * @param {Array.} salt Salt bytes to use - * @param {number} rounds Number of rounds - * @param {function(Error, Array.=)=} callback Callback receiving the error, if any, and the resulting bytes. If - * omitted, the operation will be performed synchronously. - * @param {function(number)=} progressCallback Callback called with the current progress - * @returns {!Array.|undefined} Resulting bytes if callback has been omitted, otherwise `undefined` - * @inner - */ - function _crypt(b, salt, rounds, callback, progressCallback) { - var cdata = C_ORIG.slice(), - clen = cdata.length, - err; - - // Validate - if (rounds < 4 || rounds > 31) { - err = Error("Illegal number of rounds (4-31): "+rounds); - if (callback) { - nextTick(callback.bind(this, err)); - return; - } else - throw err; - } - if (salt.length !== BCRYPT_SALT_LEN) { - err =Error("Illegal salt length: "+salt.length+" != "+BCRYPT_SALT_LEN); - if (callback) { - nextTick(callback.bind(this, err)); - return; - } else - throw err; - } - rounds = (1 << rounds) >>> 0; - - var P, S, i = 0, j; - - //Use typed arrays when available - huge speedup! - if (Int32Array) { - P = new Int32Array(P_ORIG); - S = new Int32Array(S_ORIG); - } else { - P = P_ORIG.slice(); - S = S_ORIG.slice(); - } - - _ekskey(salt, b, P, S); - - /** - * Calcualtes the next round. - * @returns {Array.|undefined} Resulting array if callback has been omitted, otherwise `undefined` - * @inner - */ - function next() { - if (progressCallback) - progressCallback(i / rounds); - if (i < rounds) { - var start = Date.now(); - for (; i < rounds;) { - i = i + 1; - _key(b, P, S); - _key(salt, P, S); - if (Date.now() - start > MAX_EXECUTION_TIME) - break; - } - } else { - for (i = 0; i < 64; i++) - for (j = 0; j < (clen >> 1); j++) - _encipher(cdata, j << 1, P, S); - var ret = []; - for (i = 0; i < clen; i++) - ret.push(((cdata[i] >> 24) & 0xff) >>> 0), - ret.push(((cdata[i] >> 16) & 0xff) >>> 0), - ret.push(((cdata[i] >> 8) & 0xff) >>> 0), - ret.push((cdata[i] & 0xff) >>> 0); - if (callback) { - callback(null, ret); - return; - } else - return ret; - } - if (callback) - nextTick(next); - } - - // Async - if (typeof callback !== 'undefined') { - next(); - - // Sync - } else { - var res; - while (true) - if (typeof(res = next()) !== 'undefined') - return res || []; - } - } - - /** - * Internally hashes a string. - * @param {string} s String to hash - * @param {?string} salt Salt to use, actually never null - * @param {function(Error, string=)=} callback Callback receiving the error, if any, and the resulting hash. If omitted, - * hashing is perormed synchronously. - * @param {function(number)=} progressCallback Callback called with the current progress - * @returns {string|undefined} Resulting hash if callback has been omitted, otherwise `undefined` - * @inner - */ - function _hash(s, salt, callback, progressCallback) { - var err; - if (typeof s !== 'string' || typeof salt !== 'string') { - err = Error("Invalid string / salt: Not a string"); - if (callback) { - nextTick(callback.bind(this, err)); - return; - } - else - throw err; - } - - // Validate the salt - var minor, offset; - if (salt.charAt(0) !== '$' || salt.charAt(1) !== '2') { - err = Error("Invalid salt version: "+salt.substring(0,2)); - if (callback) { - nextTick(callback.bind(this, err)); - return; - } - else - throw err; - } - if (salt.charAt(2) === '$') - minor = String.fromCharCode(0), - offset = 3; - else { - minor = salt.charAt(2); - if ((minor !== 'a' && minor !== 'b' && minor !== 'y') || salt.charAt(3) !== '$') { - err = Error("Invalid salt revision: "+salt.substring(2,4)); - if (callback) { - nextTick(callback.bind(this, err)); - return; - } else - throw err; - } - offset = 4; - } - - // Extract number of rounds - if (salt.charAt(offset + 2) > '$') { - err = Error("Missing salt rounds"); - if (callback) { - nextTick(callback.bind(this, err)); - return; - } else - throw err; - } - var r1 = parseInt(salt.substring(offset, offset + 1), 10) * 10, - r2 = parseInt(salt.substring(offset + 1, offset + 2), 10), - rounds = r1 + r2, - real_salt = salt.substring(offset + 3, offset + 25); - s += minor >= 'a' ? "\x00" : ""; - - var passwordb = stringToBytes(s), - saltb = base64_decode(real_salt, BCRYPT_SALT_LEN); - - /** - * Finishes hashing. - * @param {Array.} bytes Byte array - * @returns {string} - * @inner - */ - function finish(bytes) { - var res = []; - res.push("$2"); - if (minor >= 'a') - res.push(minor); - res.push("$"); - if (rounds < 10) - res.push("0"); - res.push(rounds.toString()); - res.push("$"); - res.push(base64_encode(saltb, saltb.length)); - res.push(base64_encode(bytes, C_ORIG.length * 4 - 1)); - return res.join(''); - } - - // Sync - if (typeof callback == 'undefined') - return finish(_crypt(passwordb, saltb, rounds)); - - // Async - else { - _crypt(passwordb, saltb, rounds, function(err, bytes) { - if (err) - callback(err, null); - else - callback(null, finish(bytes)); - }, progressCallback); - } - } - - /** - * Encodes a byte array to base64 with up to len bytes of input, using the custom bcrypt alphabet. - * @function - * @param {!Array.} b Byte array - * @param {number} len Maximum input length - * @returns {string} - * @expose - */ - bcrypt.encodeBase64 = base64_encode; - - /** - * Decodes a base64 encoded string to up to len bytes of output, using the custom bcrypt alphabet. - * @function - * @param {string} s String to decode - * @param {number} len Maximum output length - * @returns {!Array.} - * @expose - */ - bcrypt.decodeBase64 = base64_decode; - - return bcrypt; + throw Error("Neither WebCryptoAPI nor a crypto module is available. Use bcrypt.setRandomFallback to set an alternative"); + return randomFallback(len); + } + + // Test if any secure randomness source is available + var randomAvailable = false; + try { + random(1); + randomAvailable = true; + } catch (e) { } + + // Default fallback, if any + randomFallback = null; + /** + * Sets the pseudo random number generator to use as a fallback if neither node's `crypto` module nor the Web Crypto + * API is available. Please note: It is highly important that the PRNG used is cryptographically secure and that it + * is seeded properly! + * @param {?function(number):!Array.} random Function taking the number of bytes to generate as its + * sole argument, returning the corresponding array of cryptographically secure random byte values. + * @see http://nodejs.org/api/crypto.html + * @see http://www.w3.org/TR/WebCryptoAPI/ + */ + bcrypt.setRandomFallback = function (random) { + randomFallback = random; + }; + + /** + * Synchronously generates a salt. + * @param {number=} rounds Number of rounds to use, defaults to 10 if omitted + * @param {number=} seed_length Not supported. + * @returns {string} Resulting salt + * @throws {Error} If a random fallback is required but not set + * @expose + */ + bcrypt.genSaltSync = function (rounds, seed_length) { + rounds = rounds || GENSALT_DEFAULT_LOG2_ROUNDS; + if (typeof rounds !== 'number') + throw Error("Illegal arguments: " + (typeof rounds) + ", " + (typeof seed_length)); + if (rounds < 4) + rounds = 4; + else if (rounds > 31) + rounds = 31; + var salt = []; + salt.push("$2a$"); + if (rounds < 10) + salt.push("0"); + salt.push(rounds.toString()); + salt.push('$'); + salt.push(base64_encode(random(BCRYPT_SALT_LEN), BCRYPT_SALT_LEN)); // May throw + return salt.join(''); + }; + + /** + * Asynchronously generates a salt. + * @param {(number|function(Error, string=))=} rounds Number of rounds to use, defaults to 10 if omitted + * @param {(number|function(Error, string=))=} seed_length Not supported. + * @param {function(Error, string=)=} callback Callback receiving the error, if any, and the resulting salt + * @returns {!Promise} If `callback` has been omitted + * @throws {Error} If `callback` is present but not a function + * @expose + */ + bcrypt.genSalt = function (rounds, seed_length, callback) { + if (typeof seed_length === 'function') + callback = seed_length, + seed_length = undefined; // Not supported. + if (typeof rounds === 'function') + callback = rounds, + rounds = undefined; + if (typeof rounds === 'undefined') + rounds = GENSALT_DEFAULT_LOG2_ROUNDS; + else if (typeof rounds !== 'number') + throw Error("illegal arguments: " + (typeof rounds)); + + function _async(callback) { + nextTick(function () { // Pretty thin, but salting is fast enough + try { + callback(null, bcrypt.genSaltSync(rounds)); + } catch (err) { + callback(err); + } + }); + } + + if (callback) { + if (typeof callback !== 'function') + throw Error("Illegal callback: " + typeof (callback)); + _async(callback); + } else + return new Promise(function (resolve, reject) { + _async(function (err, res) { + if (err) { + reject(err); + return; + } + resolve(res); + }); + }); + }; + + /** + * Synchronously generates a hash for the given string. + * @param {string} s String to hash + * @param {(number|string)=} salt Salt length to generate or salt to use, default to 10 + * @returns {string} Resulting hash + * @expose + */ + bcrypt.hashSync = function (s, salt) { + if (typeof salt === 'undefined') + salt = GENSALT_DEFAULT_LOG2_ROUNDS; + if (typeof salt === 'number') + salt = bcrypt.genSaltSync(salt); + if (typeof s !== 'string' || typeof salt !== 'string') + throw Error("Illegal arguments: " + (typeof s) + ', ' + (typeof salt)); + return _hash(s, salt); + }; + + /** + * Asynchronously generates a hash for the given string. + * @param {string} s String to hash + * @param {number|string} salt Salt length to generate or salt to use + * @param {function(Error, string=)=} callback Callback receiving the error, if any, and the resulting hash + * @param {function(number)=} progressCallback Callback successively called with the percentage of rounds completed + * (0.0 - 1.0), maximally once per `MAX_EXECUTION_TIME = 100` ms. + * @returns {!Promise} If `callback` has been omitted + * @throws {Error} If `callback` is present but not a function + * @expose + */ + bcrypt.hash = function (s, salt, callback, progressCallback) { + + function _async(callback) { + if (typeof s === 'string' && typeof salt === 'number') + bcrypt.genSalt(salt, function (err, salt) { + _hash(s, salt, callback, progressCallback); + }); + else if (typeof s === 'string' && typeof salt === 'string') + _hash(s, salt, callback, progressCallback); + else + nextTick(callback.bind(this, Error("Illegal arguments: " + (typeof s) + ', ' + (typeof salt)))); + } + + if (callback) { + if (typeof callback !== 'function') + throw Error("Illegal callback: " + typeof (callback)); + _async(callback); + } else + return new Promise(function (resolve, reject) { + _async(function (err, res) { + if (err) { + reject(err); + return; + } + resolve(res); + }); + }); + }; + + /** + * Compares two strings of the same length in constant time. + * @param {string} known Must be of the correct length + * @param {string} unknown Must be the same length as `known` + * @returns {boolean} + * @inner + */ + function safeStringCompare(known, unknown) { + var right = 0, + wrong = 0; + for (var i = 0, k = known.length; i < k; ++i) { + if (known.charCodeAt(i) === unknown.charCodeAt(i)) + ++right; + else + ++wrong; + } + // Prevent removal of unused variables (never true, actually) + if (right < 0) + return false; + return wrong === 0; + } + + /** + * Synchronously tests a string against a hash. + * @param {string} s String to compare + * @param {string} hash Hash to test against + * @returns {boolean} true if matching, otherwise false + * @throws {Error} If an argument is illegal + * @expose + */ + bcrypt.compareSync = function (s, hash) { + if (typeof s !== "string" || typeof hash !== "string") + throw Error("Illegal arguments: " + (typeof s) + ', ' + (typeof hash)); + if (hash.length !== 60) + return false; + return safeStringCompare(bcrypt.hashSync(s, hash.substr(0, hash.length - 31)), hash); + }; + + /** + * Asynchronously compares the given data against the given hash. + * @param {string} s Data to compare + * @param {string} hash Data to be compared to + * @param {function(Error, boolean)=} callback Callback receiving the error, if any, otherwise the result + * @param {function(number)=} progressCallback Callback successively called with the percentage of rounds completed + * (0.0 - 1.0), maximally once per `MAX_EXECUTION_TIME = 100` ms. + * @returns {!Promise} If `callback` has been omitted + * @throws {Error} If `callback` is present but not a function + * @expose + */ + bcrypt.compare = function (s, hash, callback, progressCallback) { + + function _async(callback) { + if (typeof s !== "string" || typeof hash !== "string") { + nextTick(callback.bind(this, Error("Illegal arguments: " + (typeof s) + ', ' + (typeof hash)))); + return; + } + if (hash.length !== 60) { + nextTick(callback.bind(this, null, false)); + return; + } + bcrypt.hash(s, hash.substr(0, 29), function (err, comp) { + if (err) + callback(err); + else + callback(null, safeStringCompare(comp, hash)); + }, progressCallback); + } + + if (callback) { + if (typeof callback !== 'function') + throw Error("Illegal callback: " + typeof (callback)); + _async(callback); + } else + return new Promise(function (resolve, reject) { + _async(function (err, res) { + if (err) { + reject(err); + return; + } + resolve(res); + }); + }); + }; + + /** + * Gets the number of rounds used to encrypt the specified hash. + * @param {string} hash Hash to extract the used number of rounds from + * @returns {number} Number of rounds used + * @throws {Error} If `hash` is not a string + * @expose + */ + bcrypt.getRounds = function (hash) { + if (typeof hash !== "string") + throw Error("Illegal arguments: " + (typeof hash)); + return parseInt(hash.split("$")[2], 10); + }; + + /** + * Gets the salt portion from a hash. Does not validate the hash. + * @param {string} hash Hash to extract the salt from + * @returns {string} Extracted salt part + * @throws {Error} If `hash` is not a string or otherwise invalid + * @expose + */ + bcrypt.getSalt = function (hash) { + if (typeof hash !== 'string') + throw Error("Illegal arguments: " + (typeof hash)); + if (hash.length !== 60) + throw Error("Illegal hash length: " + hash.length + " != 60"); + return hash.substring(0, 29); + }; + + /** + * Continues with the callback on the next tick. + * @function + * @param {function(...[*])} callback Callback to execute + * @inner + */ + var nextTick = typeof process !== 'undefined' && process && typeof process.nextTick === 'function' + ? (typeof setImmediate === 'function' ? setImmediate : process.nextTick) + : setTimeout; + + /** + * Converts a JavaScript string to UTF8 bytes. + * @param {string} str String + * @returns {!Array.} UTF8 bytes + * @inner + */ + function stringToBytes(str) { + var out = [], + i = 0; + utfx.encodeUTF16toUTF8(function () { + if (i >= str.length) return null; + return str.charCodeAt(i++); + }, function (b) { + out.push(b); + }); + return out; + } + + // A base64 implementation for the bcrypt algorithm. This is partly non-standard. + + /** + * bcrypt's own non-standard base64 dictionary. + * @type {!Array.} + * @const + * @inner + **/ + var BASE64_CODE = "./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split(''); + + /** + * @type {!Array.} + * @const + * @inner + **/ + var BASE64_INDEX = [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, + 1, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, -1, -1, -1, -1, -1, -1, + -1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, + 20, 21, 22, 23, 24, 25, 26, 27, -1, -1, -1, -1, -1, -1, 28, 29, 30, + 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, + 48, 49, 50, 51, 52, 53, -1, -1, -1, -1, -1]; + + /** + * @type {!function(...number):string} + * @inner + */ + var stringFromCharCode = String.fromCharCode; + + /** + * Encodes a byte array to base64 with up to len bytes of input. + * @param {!Array.} b Byte array + * @param {number} len Maximum input length + * @returns {string} + * @inner + */ + function base64_encode(b, len) { + var off = 0, + rs = [], + c1, c2; + if (len <= 0 || len > b.length) + throw Error("Illegal len: " + len); + while (off < len) { + c1 = b[off++] & 0xff; + rs.push(BASE64_CODE[(c1 >> 2) & 0x3f]); + c1 = (c1 & 0x03) << 4; + if (off >= len) { + rs.push(BASE64_CODE[c1 & 0x3f]); + break; + } + c2 = b[off++] & 0xff; + c1 |= (c2 >> 4) & 0x0f; + rs.push(BASE64_CODE[c1 & 0x3f]); + c1 = (c2 & 0x0f) << 2; + if (off >= len) { + rs.push(BASE64_CODE[c1 & 0x3f]); + break; + } + c2 = b[off++] & 0xff; + c1 |= (c2 >> 6) & 0x03; + rs.push(BASE64_CODE[c1 & 0x3f]); + rs.push(BASE64_CODE[c2 & 0x3f]); + } + return rs.join(''); + } + + /** + * Decodes a base64 encoded string to up to len bytes of output. + * @param {string} s String to decode + * @param {number} len Maximum output length + * @returns {!Array.} + * @inner + */ + function base64_decode(s, len) { + var off = 0, + slen = s.length, + olen = 0, + rs = [], + c1, c2, c3, c4, o, code; + if (len <= 0) + throw Error("Illegal len: " + len); + while (off < slen - 1 && olen < len) { + code = s.charCodeAt(off++); + c1 = code < BASE64_INDEX.length ? BASE64_INDEX[code] : -1; + code = s.charCodeAt(off++); + c2 = code < BASE64_INDEX.length ? BASE64_INDEX[code] : -1; + if (c1 == -1 || c2 == -1) + break; + o = (c1 << 2) >>> 0; + o |= (c2 & 0x30) >> 4; + rs.push(stringFromCharCode(o)); + if (++olen >= len || off >= slen) + break; + code = s.charCodeAt(off++); + c3 = code < BASE64_INDEX.length ? BASE64_INDEX[code] : -1; + if (c3 == -1) + break; + o = ((c2 & 0x0f) << 4) >>> 0; + o |= (c3 & 0x3c) >> 2; + rs.push(stringFromCharCode(o)); + if (++olen >= len || off >= slen) + break; + code = s.charCodeAt(off++); + c4 = code < BASE64_INDEX.length ? BASE64_INDEX[code] : -1; + o = ((c3 & 0x03) << 6) >>> 0; + o |= c4; + rs.push(stringFromCharCode(o)); + ++olen; + } + var res = []; + for (off = 0; off < olen; off++) + res.push(rs[off].charCodeAt(0)); + return res; + } + + /** + * utfx-embeddable (c) 2014 Daniel Wirtz + * Released under the Apache License, Version 2.0 + * see: https://github.com/dcodeIO/utfx for details + */ + var utfx = function () { + // == Changed for ESM support == // + // "use strict"; + + /** + * utfx namespace. + * @inner + * @type {!Object.} + */ + var utfx = {}; + + /** + * Maximum valid code point. + * @type {number} + * @const + */ + utfx.MAX_CODEPOINT = 0x10FFFF; + + /** + * Encodes UTF8 code points to UTF8 bytes. + * @param {(!function():number|null) | number} src Code points source, either as a function returning the next code point + * respectively `null` if there are no more code points left or a single numeric code point. + * @param {!function(number)} dst Bytes destination as a function successively called with the next byte + */ + utfx.encodeUTF8 = function (src, dst) { + var cp = null; + if (typeof src === 'number') + cp = src, + src = function () { return null; }; + while (cp !== null || (cp = src()) !== null) { + if (cp < 0x80) + dst(cp & 0x7F); + else if (cp < 0x800) + dst(((cp >> 6) & 0x1F) | 0xC0), + dst((cp & 0x3F) | 0x80); + else if (cp < 0x10000) + dst(((cp >> 12) & 0x0F) | 0xE0), + dst(((cp >> 6) & 0x3F) | 0x80), + dst((cp & 0x3F) | 0x80); + else + dst(((cp >> 18) & 0x07) | 0xF0), + dst(((cp >> 12) & 0x3F) | 0x80), + dst(((cp >> 6) & 0x3F) | 0x80), + dst((cp & 0x3F) | 0x80); + cp = null; + } + }; + + /** + * Decodes UTF8 bytes to UTF8 code points. + * @param {!function():number|null} src Bytes source as a function returning the next byte respectively `null` if there + * are no more bytes left. + * @param {!function(number)} dst Code points destination as a function successively called with each decoded code point. + * @throws {RangeError} If a starting byte is invalid in UTF8 + * @throws {Error} If the last sequence is truncated. Has an array property `bytes` holding the + * remaining bytes. + */ + utfx.decodeUTF8 = function (src, dst) { + var a, b, c, d, fail = function (b) { + b = b.slice(0, b.indexOf(null)); + var err = Error(b.toString()); + err.name = "TruncatedError"; + err['bytes'] = b; + throw err; + }; + while ((a = src()) !== null) { + if ((a & 0x80) === 0) + dst(a); + else if ((a & 0xE0) === 0xC0) + ((b = src()) === null) && fail([a, b]), + dst(((a & 0x1F) << 6) | (b & 0x3F)); + else if ((a & 0xF0) === 0xE0) + ((b = src()) === null || (c = src()) === null) && fail([a, b, c]), + dst(((a & 0x0F) << 12) | ((b & 0x3F) << 6) | (c & 0x3F)); + else if ((a & 0xF8) === 0xF0) + ((b = src()) === null || (c = src()) === null || (d = src()) === null) && fail([a, b, c, d]), + dst(((a & 0x07) << 18) | ((b & 0x3F) << 12) | ((c & 0x3F) << 6) | (d & 0x3F)); + else throw RangeError("Illegal starting byte: " + a); + } + }; + + /** + * Converts UTF16 characters to UTF8 code points. + * @param {!function():number|null} src Characters source as a function returning the next char code respectively + * `null` if there are no more characters left. + * @param {!function(number)} dst Code points destination as a function successively called with each converted code + * point. + */ + utfx.UTF16toUTF8 = function (src, dst) { + var c1, c2 = null; + while (true) { + if ((c1 = c2 !== null ? c2 : src()) === null) + break; + if (c1 >= 0xD800 && c1 <= 0xDFFF) { + if ((c2 = src()) !== null) { + if (c2 >= 0xDC00 && c2 <= 0xDFFF) { + dst((c1 - 0xD800) * 0x400 + c2 - 0xDC00 + 0x10000); + c2 = null; continue; + } + } + } + dst(c1); + } + if (false) dst(c2); + }; + + /** + * Converts UTF8 code points to UTF16 characters. + * @param {(!function():number|null) | number} src Code points source, either as a function returning the next code point + * respectively `null` if there are no more code points left or a single numeric code point. + * @param {!function(number)} dst Characters destination as a function successively called with each converted char code. + * @throws {RangeError} If a code point is out of range + */ + utfx.UTF8toUTF16 = function (src, dst) { + var cp = null; + if (typeof src === 'number') + cp = src, src = function () { return null; }; + while (cp !== null || (cp = src()) !== null) { + if (cp <= 0xFFFF) + dst(cp); + else + cp -= 0x10000, + dst((cp >> 10) + 0xD800), + dst((cp % 0x400) + 0xDC00); + cp = null; + } + }; + + /** + * Converts and encodes UTF16 characters to UTF8 bytes. + * @param {!function():number|null} src Characters source as a function returning the next char code respectively `null` + * if there are no more characters left. + * @param {!function(number)} dst Bytes destination as a function successively called with the next byte. + */ + utfx.encodeUTF16toUTF8 = function (src, dst) { + utfx.UTF16toUTF8(src, function (cp) { + utfx.encodeUTF8(cp, dst); + }); + }; + + /** + * Decodes and converts UTF8 bytes to UTF16 characters. + * @param {!function():number|null} src Bytes source as a function returning the next byte respectively `null` if there + * are no more bytes left. + * @param {!function(number)} dst Characters destination as a function successively called with each converted char code. + * @throws {RangeError} If a starting byte is invalid in UTF8 + * @throws {Error} If the last sequence is truncated. Has an array property `bytes` holding the remaining bytes. + */ + utfx.decodeUTF8toUTF16 = function (src, dst) { + utfx.decodeUTF8(src, function (cp) { + utfx.UTF8toUTF16(cp, dst); + }); + }; + + /** + * Calculates the byte length of an UTF8 code point. + * @param {number} cp UTF8 code point + * @returns {number} Byte length + */ + utfx.calculateCodePoint = function (cp) { + return (cp < 0x80) ? 1 : (cp < 0x800) ? 2 : (cp < 0x10000) ? 3 : 4; + }; + + /** + * Calculates the number of UTF8 bytes required to store UTF8 code points. + * @param {(!function():number|null)} src Code points source as a function returning the next code point respectively + * `null` if there are no more code points left. + * @returns {number} The number of UTF8 bytes required + */ + utfx.calculateUTF8 = function (src) { + var cp, l = 0; + while ((cp = src()) !== null) + l += utfx.calculateCodePoint(cp); + return l; + }; + + /** + * Calculates the number of UTF8 code points respectively UTF8 bytes required to store UTF16 char codes. + * @param {(!function():number|null)} src Characters source as a function returning the next char code respectively + * `null` if there are no more characters left. + * @returns {!Array.} The number of UTF8 code points at index 0 and the number of UTF8 bytes required at index 1. + */ + utfx.calculateUTF16asUTF8 = function (src) { + var n = 0, l = 0; + utfx.UTF16toUTF8(src, function (cp) { + ++n; l += utfx.calculateCodePoint(cp); + }); + return [n, l]; + }; + + return utfx; + }(); + + Date.now = Date.now || function () { return +new Date; }; + + /** + * @type {number} + * @const + * @inner + */ + var BCRYPT_SALT_LEN = 16; + + /** + * @type {number} + * @const + * @inner + */ + var GENSALT_DEFAULT_LOG2_ROUNDS = 10; + + /** + * @type {number} + * @const + * @inner + */ + var BLOWFISH_NUM_ROUNDS = 16; + + /** + * @type {number} + * @const + * @inner + */ + var MAX_EXECUTION_TIME = 100; + + /** + * @type {Array.} + * @const + * @inner + */ + var P_ORIG = [ + 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, + 0x299f31d0, 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, + 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, + 0xb5470917, 0x9216d5d9, 0x8979fb1b + ]; + + /** + * @type {Array.} + * @const + * @inner + */ + var S_ORIG = [ + 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, + 0x6a267e96, 0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, + 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, 0xa458fea3, + 0xf4933d7e, 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, + 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013, 0xc5d1b023, + 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, + 0x6c9e0e8b, 0xb01e8a3e, 0xd71577c1, 0xbd314b27, 0x78af2fda, + 0x55605c60, 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, + 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, 0xa15486af, + 0x7c72e993, 0xb3ee1411, 0x636fbc2a, 0x2ba9c55d, 0x741831f6, + 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, 0x7a325381, + 0x28958677, 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, + 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, 0xef845d5d, + 0xe98575b1, 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, + 0x0f6d6ff3, 0x83f44239, 0x2e0b4482, 0xa4842004, 0x69c8f04a, + 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0, + 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, 0x6eef0b6c, + 0x137a3be4, 0xba3bf050, 0x7efb2a98, 0xa1f1651d, 0x39af0176, + 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, + 0x3b8b5ebe, 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, + 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d, 0x37d0d724, + 0xd00a1248, 0xdb0fead3, 0x49f1c09b, 0x075372c9, 0x80991b7b, + 0x25d479d8, 0xf6e8def7, 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, + 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463, + 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, + 0x9b30952c, 0xcc814544, 0xaf5ebd09, 0xbee3d004, 0xde334afd, + 0x660f2807, 0x192e4bb3, 0xc0cba857, 0x45c8740f, 0xd20b5f39, + 0xb9d3fbdb, 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, + 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8, 0x3c7516df, + 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, + 0x53317b48, 0x3e00df82, 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, + 0xdf1769db, 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, + 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, + 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b, 0x9a53e479, 0xb6f84565, + 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, + 0xcee4c6e8, 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, + 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, 0xd08ed1d0, + 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, + 0x8888b812, 0x900df01c, 0x4fad5ea0, 0x688fc31c, 0xd1cff191, + 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1, + 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, 0xb4a84fe0, + 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, 0x165fa266, 0x80957705, + 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, + 0xfb9d35cf, 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, + 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af, 0x2464369b, + 0xf009b91e, 0x5563911d, 0x59dfa6aa, 0x78c14389, 0xd95a537f, + 0x207d5ba2, 0x02e5b9c5, 0x83260376, 0x6295cfa9, 0x11c81968, + 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915, + 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, + 0x571be91f, 0xf296ec6b, 0x2a0dd915, 0xb6636521, 0xe7b9f9b6, + 0xff34052e, 0xc5855664, 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, + 0x6e85076a, 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, + 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266, 0xecaa8c71, + 0x699a17ff, 0x5664526c, 0xc2b19ee1, 0x193602a5, 0x75094c29, + 0xa0591340, 0xe4183a3e, 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, + 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1, + 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, + 0x3ebaefc9, 0x3c971814, 0x6b6a70a1, 0x687f3584, 0x52a0e286, + 0xb79c5305, 0xaa500737, 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, + 0x5716f2b8, 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, + 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd, 0xd19113f9, + 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, + 0xc8b57634, 0x9af3dda7, 0xa9446146, 0x0fd0030e, 0xecc8c73e, + 0xa4751e41, 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, + 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, 0x2cb81290, + 0x24977c79, 0x5679b072, 0xbcaf89af, 0xde9a771f, 0xd9930810, + 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, 0x501adde6, + 0x9f84cd87, 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, + 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, 0xef1c1847, + 0x3215d908, 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, + 0x50940002, 0x133ae4dd, 0x71dff89e, 0x10314e55, 0x81ac77d6, + 0x5f11199b, 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509, + 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, 0x86e34570, + 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, 0x771fe71c, 0x4e3d06fa, + 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, + 0x9c10b36a, 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, + 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960, 0x5223a708, + 0xf71312b6, 0xebadfe6e, 0xeac31f66, 0xe3bc4595, 0xa67bc883, + 0xb17f37d1, 0x018cff28, 0xc332ddef, 0xbe6c5aa5, 0x65582185, + 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84, + 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, + 0xeb61bd96, 0x0334fe1e, 0xaa0363cf, 0xb5735c90, 0x4c70a239, + 0xd59e9e0b, 0xcbaade14, 0xeecc86bc, 0x60622ca7, 0x9cab5cab, + 0xb2f3846e, 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, + 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7, 0x9b540b19, + 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, + 0x11ed935f, 0x16681281, 0x0e358829, 0xc7e61fd6, 0x96dedfa1, + 0x7858ba99, 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, + 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, + 0x34c6ffea, 0xfe28ed61, 0xee7c3c73, 0x5d4a14d9, 0xe864b7e3, + 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, + 0xfacb4fd0, 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, + 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, 0xcf62a1f2, + 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, + 0x47848a0b, 0x5692b285, 0x095bbf00, 0xad19489d, 0x1462b174, + 0x23820e00, 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061, + 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, 0x7cde3759, + 0xcbee7460, 0x4085f2a7, 0xce77326e, 0xa6078084, 0x19f8509e, + 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, + 0x800bcadc, 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, + 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340, 0xc5c43465, + 0x713e38d8, 0x3d28f89e, 0xf16dff20, 0x153e21e7, 0x8fb03d4a, + 0xe6e39f2b, 0xdb83adf7, 0xe93d5a68, 0x948140f7, 0xf64c261c, + 0x94692934, 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068, + 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, 0x1e39f62e, + 0x97244546, 0x14214f74, 0xbf8b8840, 0x4d95fc1d, 0x96b591af, + 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, + 0x31cb8504, 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, + 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb, 0x68dc1462, + 0xd7486900, 0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c, + 0xb58ce006, 0x7af4d6b6, 0xaace1e7c, 0xd3375fec, 0xce78a399, + 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b, + 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, + 0xdd5b4332, 0x6841e7f7, 0xca7820fb, 0xfb0af54e, 0xd8feb397, + 0x454056ac, 0xba489527, 0x55533a3a, 0x20838d87, 0xfe6ba9b7, + 0xd096954b, 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, + 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c, 0xfdf8e802, + 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, + 0x48c1133f, 0xc70f86dc, 0x07f9c9ee, 0x41041f0f, 0x404779a4, + 0x5d886e17, 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, + 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, + 0x02e1329e, 0xaf664fd1, 0xcad18115, 0x6b2395e0, 0x333e92e1, + 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, + 0x2da2f728, 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, + 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, 0x0a476341, + 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, + 0x991be14c, 0xdb6e6b0d, 0xc67b5510, 0x6d672c37, 0x2765d43b, + 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b, + 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, 0xbb132f88, + 0x515bad24, 0x7b9479bf, 0x763bd6eb, 0x37392eb3, 0xcc115979, + 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, + 0x782ef11c, 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, + 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9, 0x44421659, + 0x0a121386, 0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f, + 0xbebfe988, 0x64e4c3fe, 0x9dbc8057, 0xf0f7c086, 0x60787bf8, + 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc, + 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, + 0xbde8ae24, 0x55464299, 0xbf582e61, 0x4e58f48f, 0xf2ddfda2, + 0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74, 0xb475f255, + 0x46fcd9b9, 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, + 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c, 0xb90bace1, + 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, + 0x662d09a1, 0xc4324633, 0xe85a1f02, 0x09f0be8c, 0x4a99a025, + 0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, + 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, + 0xa70683fa, 0xa002b5c4, 0x0de6d027, 0x9af88c27, 0x773f8641, + 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, 0x006058aa, + 0x30dc7d62, 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, + 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, 0x6f05e409, + 0x4b7c0188, 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, + 0x1ac15bb4, 0xd39eb8fc, 0xed545578, 0x08fca5b5, 0xd83d7cd3, + 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c, + 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, 0xd79a3234, + 0x92638212, 0x670efa8e, 0x406000e0, 0x3a39ce37, 0xd3faf5cf, + 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, 0xd3822740, + 0x99bc9bbe, 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, + 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, 0x5748ab2f, + 0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, + 0xd5730a1d, 0x4cd04dc6, 0x2939bbdb, 0xa9ba4650, 0xac9526e8, + 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22, + 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, 0x83c061ba, + 0x9be96a4d, 0x8fe51550, 0xba645bd6, 0x2826a2f9, 0xa73a3ae1, + 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, + 0x77fa0a59, 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, + 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51, 0x96d5ac3a, + 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, 0x1f9f25cf, 0xadf2b89b, + 0x5ad6b472, 0x5a88f54c, 0xe029ac71, 0xe019a5e6, 0x47b0acfd, + 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28, + 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, + 0x88f46dba, 0x03a16125, 0x0564f0bd, 0xc3eb9e15, 0x3c9057a2, + 0x97271aec, 0xa93a072a, 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, + 0x26dcf319, 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, + 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f, 0x4de81751, + 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, + 0x5121ce64, 0x774fbe32, 0xa8b6e37e, 0xc3293d46, 0x48de5369, + 0x6413e680, 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, + 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, + 0x1b588d40, 0xccd2017f, 0x6bb4e3bb, 0xdda26a7e, 0x3a59ff45, + 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, 0x8d6612ae, + 0xbf3c6f47, 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, + 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, 0x4040cb08, + 0x4eb4e2cc, 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, + 0x06b89fb4, 0xce6ea048, 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, + 0x277227f8, 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd, + 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, 0xe01cc87e, + 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, 0x1a908749, 0xd44fbd9a, + 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, + 0xe0b12b4f, 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, + 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525, 0xfae59361, + 0xceb69ceb, 0xc2a86459, 0x12baa8d1, 0xb6c1075e, 0xe3056a0c, + 0x10d25065, 0xcb03a442, 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, + 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e, + 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, + 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d, 0xe54cda54, 0x1edad891, + 0xce6279cf, 0xcd3e7e6f, 0x1618b166, 0xfd2c1d05, 0x848fd2c5, + 0xf6fb2299, 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, + 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc, 0xde966292, + 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, + 0x45e1d006, 0xc3f27b9a, 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, + 0x35bdd2f6, 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, + 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, 0xba38209c, + 0xf746ce76, 0x77afa1c5, 0x20756060, 0x85cbfe4e, 0x8ae88dd8, + 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, + 0xd6ebe1f9, 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, + 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6 + ]; + + /** + * @type {Array.} + * @const + * @inner + */ + var C_ORIG = [ + 0x4f727068, 0x65616e42, 0x65686f6c, 0x64657253, 0x63727944, + 0x6f756274 + ]; + + /** + * @param {Array.} lr + * @param {number} off + * @param {Array.} P + * @param {Array.} S + * @returns {Array.} + * @inner + */ + function _encipher(lr, off, P, S) { // This is our bottleneck: 1714/1905 ticks / 90% - see profile.txt + var n, + l = lr[off], + r = lr[off + 1]; + + l ^= P[0]; + + /* + for (var i=0, k=BLOWFISH_NUM_ROUNDS-2; i<=k;) + // Feistel substitution on left word + n = S[l >>> 24], + n += S[0x100 | ((l >> 16) & 0xff)], + n ^= S[0x200 | ((l >> 8) & 0xff)], + n += S[0x300 | (l & 0xff)], + r ^= n ^ P[++i], + // Feistel substitution on right word + n = S[r >>> 24], + n += S[0x100 | ((r >> 16) & 0xff)], + n ^= S[0x200 | ((r >> 8) & 0xff)], + n += S[0x300 | (r & 0xff)], + l ^= n ^ P[++i]; + */ + + //The following is an unrolled version of the above loop. + //Iteration 0 + n = S[l >>> 24]; + n += S[0x100 | ((l >> 16) & 0xff)]; + n ^= S[0x200 | ((l >> 8) & 0xff)]; + n += S[0x300 | (l & 0xff)]; + r ^= n ^ P[1]; + n = S[r >>> 24]; + n += S[0x100 | ((r >> 16) & 0xff)]; + n ^= S[0x200 | ((r >> 8) & 0xff)]; + n += S[0x300 | (r & 0xff)]; + l ^= n ^ P[2]; + //Iteration 1 + n = S[l >>> 24]; + n += S[0x100 | ((l >> 16) & 0xff)]; + n ^= S[0x200 | ((l >> 8) & 0xff)]; + n += S[0x300 | (l & 0xff)]; + r ^= n ^ P[3]; + n = S[r >>> 24]; + n += S[0x100 | ((r >> 16) & 0xff)]; + n ^= S[0x200 | ((r >> 8) & 0xff)]; + n += S[0x300 | (r & 0xff)]; + l ^= n ^ P[4]; + //Iteration 2 + n = S[l >>> 24]; + n += S[0x100 | ((l >> 16) & 0xff)]; + n ^= S[0x200 | ((l >> 8) & 0xff)]; + n += S[0x300 | (l & 0xff)]; + r ^= n ^ P[5]; + n = S[r >>> 24]; + n += S[0x100 | ((r >> 16) & 0xff)]; + n ^= S[0x200 | ((r >> 8) & 0xff)]; + n += S[0x300 | (r & 0xff)]; + l ^= n ^ P[6]; + //Iteration 3 + n = S[l >>> 24]; + n += S[0x100 | ((l >> 16) & 0xff)]; + n ^= S[0x200 | ((l >> 8) & 0xff)]; + n += S[0x300 | (l & 0xff)]; + r ^= n ^ P[7]; + n = S[r >>> 24]; + n += S[0x100 | ((r >> 16) & 0xff)]; + n ^= S[0x200 | ((r >> 8) & 0xff)]; + n += S[0x300 | (r & 0xff)]; + l ^= n ^ P[8]; + //Iteration 4 + n = S[l >>> 24]; + n += S[0x100 | ((l >> 16) & 0xff)]; + n ^= S[0x200 | ((l >> 8) & 0xff)]; + n += S[0x300 | (l & 0xff)]; + r ^= n ^ P[9]; + n = S[r >>> 24]; + n += S[0x100 | ((r >> 16) & 0xff)]; + n ^= S[0x200 | ((r >> 8) & 0xff)]; + n += S[0x300 | (r & 0xff)]; + l ^= n ^ P[10]; + //Iteration 5 + n = S[l >>> 24]; + n += S[0x100 | ((l >> 16) & 0xff)]; + n ^= S[0x200 | ((l >> 8) & 0xff)]; + n += S[0x300 | (l & 0xff)]; + r ^= n ^ P[11]; + n = S[r >>> 24]; + n += S[0x100 | ((r >> 16) & 0xff)]; + n ^= S[0x200 | ((r >> 8) & 0xff)]; + n += S[0x300 | (r & 0xff)]; + l ^= n ^ P[12]; + //Iteration 6 + n = S[l >>> 24]; + n += S[0x100 | ((l >> 16) & 0xff)]; + n ^= S[0x200 | ((l >> 8) & 0xff)]; + n += S[0x300 | (l & 0xff)]; + r ^= n ^ P[13]; + n = S[r >>> 24]; + n += S[0x100 | ((r >> 16) & 0xff)]; + n ^= S[0x200 | ((r >> 8) & 0xff)]; + n += S[0x300 | (r & 0xff)]; + l ^= n ^ P[14]; + //Iteration 7 + n = S[l >>> 24]; + n += S[0x100 | ((l >> 16) & 0xff)]; + n ^= S[0x200 | ((l >> 8) & 0xff)]; + n += S[0x300 | (l & 0xff)]; + r ^= n ^ P[15]; + n = S[r >>> 24]; + n += S[0x100 | ((r >> 16) & 0xff)]; + n ^= S[0x200 | ((r >> 8) & 0xff)]; + n += S[0x300 | (r & 0xff)]; + l ^= n ^ P[16]; + + lr[off] = r ^ P[BLOWFISH_NUM_ROUNDS + 1]; + lr[off + 1] = l; + return lr; + } + + /** + * @param {Array.} data + * @param {number} offp + * @returns {{key: number, offp: number}} + * @inner + */ + function _streamtoword(data, offp) { + for (var i = 0, word = 0; i < 4; ++i) + word = (word << 8) | (data[offp] & 0xff), + offp = (offp + 1) % data.length; + return { key: word, offp: offp }; + } + + /** + * @param {Array.} key + * @param {Array.} P + * @param {Array.} S + * @inner + */ + function _key(key, P, S) { + var offset = 0, + lr = [0, 0], + plen = P.length, + slen = S.length, + sw; + for (var i = 0; i < plen; i++) + sw = _streamtoword(key, offset), + offset = sw.offp, + P[i] = P[i] ^ sw.key; + for (i = 0; i < plen; i += 2) + lr = _encipher(lr, 0, P, S), + P[i] = lr[0], + P[i + 1] = lr[1]; + for (i = 0; i < slen; i += 2) + lr = _encipher(lr, 0, P, S), + S[i] = lr[0], + S[i + 1] = lr[1]; + } + + /** + * Expensive key schedule Blowfish. + * @param {Array.} data + * @param {Array.} key + * @param {Array.} P + * @param {Array.} S + * @inner + */ + function _ekskey(data, key, P, S) { + var offp = 0, + lr = [0, 0], + plen = P.length, + slen = S.length, + sw; + for (var i = 0; i < plen; i++) + sw = _streamtoword(key, offp), + offp = sw.offp, + P[i] = P[i] ^ sw.key; + offp = 0; + for (i = 0; i < plen; i += 2) + sw = _streamtoword(data, offp), + offp = sw.offp, + lr[0] ^= sw.key, + sw = _streamtoword(data, offp), + offp = sw.offp, + lr[1] ^= sw.key, + lr = _encipher(lr, 0, P, S), + P[i] = lr[0], + P[i + 1] = lr[1]; + for (i = 0; i < slen; i += 2) + sw = _streamtoword(data, offp), + offp = sw.offp, + lr[0] ^= sw.key, + sw = _streamtoword(data, offp), + offp = sw.offp, + lr[1] ^= sw.key, + lr = _encipher(lr, 0, P, S), + S[i] = lr[0], + S[i + 1] = lr[1]; + } + + /** + * Internaly crypts a string. + * @param {Array.} b Bytes to crypt + * @param {Array.} salt Salt bytes to use + * @param {number} rounds Number of rounds + * @param {function(Error, Array.=)=} callback Callback receiving the error, if any, and the resulting bytes. If + * omitted, the operation will be performed synchronously. + * @param {function(number)=} progressCallback Callback called with the current progress + * @returns {!Array.|undefined} Resulting bytes if callback has been omitted, otherwise `undefined` + * @inner + */ + function _crypt(b, salt, rounds, callback, progressCallback) { + var cdata = C_ORIG.slice(), + clen = cdata.length, + err; + + // Validate + if (rounds < 4 || rounds > 31) { + err = Error("Illegal number of rounds (4-31): " + rounds); + if (callback) { + nextTick(callback.bind(this, err)); + return; + } else + throw err; + } + if (salt.length !== BCRYPT_SALT_LEN) { + err = Error("Illegal salt length: " + salt.length + " != " + BCRYPT_SALT_LEN); + if (callback) { + nextTick(callback.bind(this, err)); + return; + } else + throw err; + } + rounds = (1 << rounds) >>> 0; + + var P, S, i = 0, j; + + //Use typed arrays when available - huge speedup! + if (Int32Array) { + P = new Int32Array(P_ORIG); + S = new Int32Array(S_ORIG); + } else { + P = P_ORIG.slice(); + S = S_ORIG.slice(); + } + + _ekskey(salt, b, P, S); + + /** + * Calcualtes the next round. + * @returns {Array.|undefined} Resulting array if callback has been omitted, otherwise `undefined` + * @inner + */ + function next() { + if (progressCallback) + progressCallback(i / rounds); + if (i < rounds) { + var start = Date.now(); + for (; i < rounds;) { + i = i + 1; + _key(b, P, S); + _key(salt, P, S); + if (Date.now() - start > MAX_EXECUTION_TIME) + break; + } + } else { + for (i = 0; i < 64; i++) + for (j = 0; j < (clen >> 1); j++) + _encipher(cdata, j << 1, P, S); + var ret = []; + for (i = 0; i < clen; i++) + ret.push(((cdata[i] >> 24) & 0xff) >>> 0), + ret.push(((cdata[i] >> 16) & 0xff) >>> 0), + ret.push(((cdata[i] >> 8) & 0xff) >>> 0), + ret.push((cdata[i] & 0xff) >>> 0); + if (callback) { + callback(null, ret); + return; + } else + return ret; + } + if (callback) + nextTick(next); + } + + // Async + if (typeof callback !== 'undefined') { + next(); + + // Sync + } else { + var res; + while (true) + if (typeof (res = next()) !== 'undefined') + return res || []; + } + } + + /** + * Internally hashes a string. + * @param {string} s String to hash + * @param {?string} salt Salt to use, actually never null + * @param {function(Error, string=)=} callback Callback receiving the error, if any, and the resulting hash. If omitted, + * hashing is perormed synchronously. + * @param {function(number)=} progressCallback Callback called with the current progress + * @returns {string|undefined} Resulting hash if callback has been omitted, otherwise `undefined` + * @inner + */ + function _hash(s, salt, callback, progressCallback) { + var err; + if (typeof s !== 'string' || typeof salt !== 'string') { + err = Error("Invalid string / salt: Not a string"); + if (callback) { + nextTick(callback.bind(this, err)); + return; + } + else + throw err; + } + + // Validate the salt + var minor, offset; + if (salt.charAt(0) !== '$' || salt.charAt(1) !== '2') { + err = Error("Invalid salt version: " + salt.substring(0, 2)); + if (callback) { + nextTick(callback.bind(this, err)); + return; + } + else + throw err; + } + if (salt.charAt(2) === '$') + minor = String.fromCharCode(0), + offset = 3; + else { + minor = salt.charAt(2); + if ((minor !== 'a' && minor !== 'b' && minor !== 'y') || salt.charAt(3) !== '$') { + err = Error("Invalid salt revision: " + salt.substring(2, 4)); + if (callback) { + nextTick(callback.bind(this, err)); + return; + } else + throw err; + } + offset = 4; + } + + // Extract number of rounds + if (salt.charAt(offset + 2) > '$') { + err = Error("Missing salt rounds"); + if (callback) { + nextTick(callback.bind(this, err)); + return; + } else + throw err; + } + var r1 = parseInt(salt.substring(offset, offset + 1), 10) * 10, + r2 = parseInt(salt.substring(offset + 1, offset + 2), 10), + rounds = r1 + r2, + real_salt = salt.substring(offset + 3, offset + 25); + s += minor >= 'a' ? "\x00" : ""; + + var passwordb = stringToBytes(s), + saltb = base64_decode(real_salt, BCRYPT_SALT_LEN); + + /** + * Finishes hashing. + * @param {Array.} bytes Byte array + * @returns {string} + * @inner + */ + function finish(bytes) { + var res = []; + res.push("$2"); + if (minor >= 'a') + res.push(minor); + res.push("$"); + if (rounds < 10) + res.push("0"); + res.push(rounds.toString()); + res.push("$"); + res.push(base64_encode(saltb, saltb.length)); + res.push(base64_encode(bytes, C_ORIG.length * 4 - 1)); + return res.join(''); + } + + // Sync + if (typeof callback == 'undefined') + return finish(_crypt(passwordb, saltb, rounds)); + + // Async + else { + _crypt(passwordb, saltb, rounds, function (err, bytes) { + if (err) + callback(err, null); + else + callback(null, finish(bytes)); + }, progressCallback); + } + } + + /** + * Encodes a byte array to base64 with up to len bytes of input, using the custom bcrypt alphabet. + * @function + * @param {!Array.} b Byte array + * @param {number} len Maximum input length + * @returns {string} + * @expose + */ + bcrypt.encodeBase64 = base64_encode; + + /** + * Decodes a base64 encoded string to up to len bytes of output, using the custom bcrypt alphabet. + * @function + * @param {string} s String to decode + * @param {number} len Maximum output length + * @returns {!Array.} + * @expose + */ + bcrypt.decodeBase64 = base64_decode; + + return bcrypt; })); diff --git a/crypto/api/deps/broken-ripemd160.js b/crypto/api/deps/broken-ripemd160.js index 9045ef21..1f266194 100644 --- a/crypto/api/deps/broken-ripemd160.js +++ b/crypto/api/deps/broken-ripemd160.js @@ -1,180 +1,179 @@ // "Generated from Java with JSweet 1.0.0 - http://www.jsweet.org"; // BAD IMPLEMENTATION. BROKEN, BUT MUST KEEP CAUSE OF NETWORK -//const RIPEMD160 = (function () { // == Convert to ES6 module for export == // const RIPEMD160 = (function () { - function RIPEMD160() { - this.MDbuf = []; - this.MDbuf[0] = 1732584193; - this.MDbuf[1] = -271733879; - this.MDbuf[2] = -1732584194; - this.MDbuf[3] = 271733878; - this.MDbuf[4] = -1009589776; - this.working = new Int32Array(16); + function RIPEMD160() { + this.MDbuf = []; + this.MDbuf[0] = 1732584193; + this.MDbuf[1] = -271733879; + this.MDbuf[2] = -1732584194; + this.MDbuf[3] = 271733878; + this.MDbuf[4] = -1009589776; + this.working = new Int32Array(16); - this.working_ptr = 0; - this.msglen = 0; - } - RIPEMD160.prototype.reset = function () { - this.MDbuf = []; - this.MDbuf[0] = 1732584193; - this.MDbuf[1] = -271733879; - this.MDbuf[2] = -1732584194; - this.MDbuf[3] = 271733878; - this.MDbuf[4] = -1009589776; - this.working = new Int32Array(16); - this.working_ptr = 0; - this.msglen = 0; - }; - RIPEMD160.prototype.compress = function (X) { - var index = 0; - var a; - var b; - var c; - var d; - var e; - var A; - var B; - var C; - var D; - var E; - var temp; - var s; - A = a = this.MDbuf[0]; - B = b = this.MDbuf[1]; - C = c = this.MDbuf[2]; - D = d = this.MDbuf[3]; - E = e = this.MDbuf[4]; - for (; index < 16; index++) { - temp = a + (b ^ c ^ d) + X[RIPEMD160.IndexArray[0][index]]; - a = e; - e = d; - d = (c << 10) | (c >>> 22); - c = b; - s = RIPEMD160.ArgArray[0][index]; - b = ((temp << s) | (temp >>> (32 - s))) + a; - temp = A + (B ^ (C | ~D)) + X[RIPEMD160.IndexArray[1][index]] + 1352829926; - A = E; - E = D; - D = (C << 10) | (C >>> 22); - C = B; - s = RIPEMD160.ArgArray[1][index]; - B = ((temp << s) | (temp >>> (32 - s))) + A; - } - for (; index < 32; index++) { - temp = a + ((b & c) | (~b & d)) + X[RIPEMD160.IndexArray[0][index]] + 1518500249; - a = e; - e = d; - d = (c << 10) | (c >>> 22); - c = b; - s = RIPEMD160.ArgArray[0][index]; - b = ((temp << s) | (temp >>> (32 - s))) + a; - temp = A + ((B & D) | (C & ~D)) + X[RIPEMD160.IndexArray[1][index]] + 1548603684; - A = E; - E = D; - D = (C << 10) | (C >>> 22); - C = B; - s = RIPEMD160.ArgArray[1][index]; - B = ((temp << s) | (temp >>> (32 - s))) + A; - } - for (; index < 48; index++) { - temp = a + ((b | ~c) ^ d) + X[RIPEMD160.IndexArray[0][index]] + 1859775393; - a = e; - e = d; - d = (c << 10) | (c >>> 22); - c = b; - s = RIPEMD160.ArgArray[0][index]; - b = ((temp << s) | (temp >>> (32 - s))) + a; - temp = A + ((B | ~C) ^ D) + X[RIPEMD160.IndexArray[1][index]] + 1836072691; - A = E; - E = D; - D = (C << 10) | (C >>> 22); - C = B; - s = RIPEMD160.ArgArray[1][index]; - B = ((temp << s) | (temp >>> (32 - s))) + A; - } - for (; index < 64; index++) { - temp = a + ((b & d) | (c & ~d)) + X[RIPEMD160.IndexArray[0][index]] + -1894007588; - a = e; - e = d; - d = (c << 10) | (c >>> 22); - c = b; - s = RIPEMD160.ArgArray[0][index]; - b = ((temp << s) | (temp >>> (32 - s))) + a; - temp = A + ((B & C) | (~B & D)) + X[RIPEMD160.IndexArray[1][index]] + 2053994217; - A = E; - E = D; - D = (C << 10) | (C >>> 22); - C = B; - s = RIPEMD160.ArgArray[1][index]; - B = ((temp << s) | (temp >>> (32 - s))) + A; - } - for (; index < 80; index++) { - temp = a + (b ^ (c | ~d)) + X[RIPEMD160.IndexArray[0][index]] + -1454113458; - a = e; - e = d; - d = (c << 10) | (c >>> 22); - c = b; - s = RIPEMD160.ArgArray[0][index]; - b = ((temp << s) | (temp >>> (32 - s))) + a; - temp = A + (B ^ C ^ D) + X[RIPEMD160.IndexArray[1][index]]; - A = E; - E = D; - D = (C << 10) | (C >>> 22); - C = B; - s = RIPEMD160.ArgArray[1][index]; - B = ((temp << s) | (temp >>> (32 - s))) + A; - } - D += c + this.MDbuf[1]; - this.MDbuf[1] = this.MDbuf[2] + d + E; - this.MDbuf[2] = this.MDbuf[3] + e + A; - this.MDbuf[3] = this.MDbuf[4] + a + B; - this.MDbuf[4] = this.MDbuf[0] + b + C; - this.MDbuf[0] = D; - }; - RIPEMD160.prototype.MDfinish = function (array, lswlen, mswlen) { - var X = array; - X[(lswlen >> 2) & 15] ^= 1 << (((lswlen & 3) << 3) + 7); - if (((lswlen & 63) > 55)) { - this.compress(X); - for (var i = 0; i < 14; i++) { - X[i] = 0; - } - } - X[14] = lswlen << 3; - X[15] = (lswlen >> 29) | (mswlen << 3); - this.compress(X); - }; - RIPEMD160.prototype.update = function (input) { - for (var i = 0; i < input.length; i++) { - this.working[this.working_ptr >> 2] ^= input[i] << ((this.working_ptr & 3) << 3); - this.working_ptr++; - if ((this.working_ptr == 64)) { - this.compress(this.working); - for (var j = 0; j < 16; j++) { - this.working[j] = 0; - } - this.working_ptr = 0; - } - } - this.msglen += input.length; - }; - RIPEMD160.prototype.digestBin = function () { - this.MDfinish(this.working, this.msglen, 0); - //var res = new Int8Array(); - var res = []; - for (var i = 0; i < 20; i++) { - res[i] = ((this.MDbuf[i >> 2] >>> ((i & 3) << 3)) & 255); - } - return new Uint8Array(res); - }; - RIPEMD160.prototype.digest = function (input) { - this.update(new Int8Array(input)); - return this.digestBin(); - }; - RIPEMD160.ArgArray = [[11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6], [8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11]]; - RIPEMD160.IndexArray = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13], [5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11]]; - return RIPEMD160; + this.working_ptr = 0; + this.msglen = 0; + } + RIPEMD160.prototype.reset = function () { + this.MDbuf = []; + this.MDbuf[0] = 1732584193; + this.MDbuf[1] = -271733879; + this.MDbuf[2] = -1732584194; + this.MDbuf[3] = 271733878; + this.MDbuf[4] = -1009589776; + this.working = new Int32Array(16); + this.working_ptr = 0; + this.msglen = 0; + }; + RIPEMD160.prototype.compress = function (X) { + var index = 0; + var a; + var b; + var c; + var d; + var e; + var A; + var B; + var C; + var D; + var E; + var temp; + var s; + A = a = this.MDbuf[0]; + B = b = this.MDbuf[1]; + C = c = this.MDbuf[2]; + D = d = this.MDbuf[3]; + E = e = this.MDbuf[4]; + for (; index < 16; index++) { + temp = a + (b ^ c ^ d) + X[RIPEMD160.IndexArray[0][index]]; + a = e; + e = d; + d = (c << 10) | (c >>> 22); + c = b; + s = RIPEMD160.ArgArray[0][index]; + b = ((temp << s) | (temp >>> (32 - s))) + a; + temp = A + (B ^ (C | ~D)) + X[RIPEMD160.IndexArray[1][index]] + 1352829926; + A = E; + E = D; + D = (C << 10) | (C >>> 22); + C = B; + s = RIPEMD160.ArgArray[1][index]; + B = ((temp << s) | (temp >>> (32 - s))) + A; + } + for (; index < 32; index++) { + temp = a + ((b & c) | (~b & d)) + X[RIPEMD160.IndexArray[0][index]] + 1518500249; + a = e; + e = d; + d = (c << 10) | (c >>> 22); + c = b; + s = RIPEMD160.ArgArray[0][index]; + b = ((temp << s) | (temp >>> (32 - s))) + a; + temp = A + ((B & D) | (C & ~D)) + X[RIPEMD160.IndexArray[1][index]] + 1548603684; + A = E; + E = D; + D = (C << 10) | (C >>> 22); + C = B; + s = RIPEMD160.ArgArray[1][index]; + B = ((temp << s) | (temp >>> (32 - s))) + A; + } + for (; index < 48; index++) { + temp = a + ((b | ~c) ^ d) + X[RIPEMD160.IndexArray[0][index]] + 1859775393; + a = e; + e = d; + d = (c << 10) | (c >>> 22); + c = b; + s = RIPEMD160.ArgArray[0][index]; + b = ((temp << s) | (temp >>> (32 - s))) + a; + temp = A + ((B | ~C) ^ D) + X[RIPEMD160.IndexArray[1][index]] + 1836072691; + A = E; + E = D; + D = (C << 10) | (C >>> 22); + C = B; + s = RIPEMD160.ArgArray[1][index]; + B = ((temp << s) | (temp >>> (32 - s))) + A; + } + for (; index < 64; index++) { + temp = a + ((b & d) | (c & ~d)) + X[RIPEMD160.IndexArray[0][index]] + -1894007588; + a = e; + e = d; + d = (c << 10) | (c >>> 22); + c = b; + s = RIPEMD160.ArgArray[0][index]; + b = ((temp << s) | (temp >>> (32 - s))) + a; + temp = A + ((B & C) | (~B & D)) + X[RIPEMD160.IndexArray[1][index]] + 2053994217; + A = E; + E = D; + D = (C << 10) | (C >>> 22); + C = B; + s = RIPEMD160.ArgArray[1][index]; + B = ((temp << s) | (temp >>> (32 - s))) + A; + } + for (; index < 80; index++) { + temp = a + (b ^ (c | ~d)) + X[RIPEMD160.IndexArray[0][index]] + -1454113458; + a = e; + e = d; + d = (c << 10) | (c >>> 22); + c = b; + s = RIPEMD160.ArgArray[0][index]; + b = ((temp << s) | (temp >>> (32 - s))) + a; + temp = A + (B ^ C ^ D) + X[RIPEMD160.IndexArray[1][index]]; + A = E; + E = D; + D = (C << 10) | (C >>> 22); + C = B; + s = RIPEMD160.ArgArray[1][index]; + B = ((temp << s) | (temp >>> (32 - s))) + A; + } + D += c + this.MDbuf[1]; + this.MDbuf[1] = this.MDbuf[2] + d + E; + this.MDbuf[2] = this.MDbuf[3] + e + A; + this.MDbuf[3] = this.MDbuf[4] + a + B; + this.MDbuf[4] = this.MDbuf[0] + b + C; + this.MDbuf[0] = D; + }; + RIPEMD160.prototype.MDfinish = function (array, lswlen, mswlen) { + var X = array; + X[(lswlen >> 2) & 15] ^= 1 << (((lswlen & 3) << 3) + 7); + if (((lswlen & 63) > 55)) { + this.compress(X); + for (var i = 0; i < 14; i++) { + X[i] = 0; + } + } + X[14] = lswlen << 3; + X[15] = (lswlen >> 29) | (mswlen << 3); + this.compress(X); + }; + RIPEMD160.prototype.update = function (input) { + for (var i = 0; i < input.length; i++) { + this.working[this.working_ptr >> 2] ^= input[i] << ((this.working_ptr & 3) << 3); + this.working_ptr++; + if ((this.working_ptr == 64)) { + this.compress(this.working); + for (var j = 0; j < 16; j++) { + this.working[j] = 0; + } + this.working_ptr = 0; + } + } + this.msglen += input.length; + }; + RIPEMD160.prototype.digestBin = function () { + this.MDfinish(this.working, this.msglen, 0); + //var res = new Int8Array(); + var res = []; + for (var i = 0; i < 20; i++) { + res[i] = ((this.MDbuf[i >> 2] >>> ((i & 3) << 3)) & 255); + } + return new Uint8Array(res); + }; + RIPEMD160.prototype.digest = function (input) { + this.update(new Int8Array(input)); + return this.digestBin(); + }; + RIPEMD160.ArgArray = [[11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6], [8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11]]; + RIPEMD160.IndexArray = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13], [5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11]]; + return RIPEMD160; })(); export default RIPEMD160 diff --git a/crypto/api/deps/deps.js b/crypto/api/deps/deps.js index 48eb8130..331f6ad0 100644 --- a/crypto/api/deps/deps.js +++ b/crypto/api/deps/deps.js @@ -1,3 +1,2 @@ -export { default as Base58 } from './Base58.js' - -export { default as utils } from './utils.js' +export { default as Base58 } from './Base58' +export { default as utils } from './utils' diff --git a/crypto/api/deps/ed2curve.js b/crypto/api/deps/ed2curve.js index e7ede3d0..1fcabdea 100644 --- a/crypto/api/deps/ed2curve.js +++ b/crypto/api/deps/ed2curve.js @@ -10,255 +10,239 @@ Change to es6 import/export */ -import nacl from './nacl-fast.js' +import nacl from './nacl-fast' -// (function(root, f) { -// 'use strict'; -// if (typeof module !== 'undefined' && module.exports) module.exports = f(require('tweetnacl')); -// else root.ed2curve = f(root.nacl); -// }(this, function(nacl) { -// 'use strict'; -// if (!nacl) throw new Error('tweetnacl not loaded'); +// -- Operations copied from TweetNaCl.js. -- - // -- Operations copied from TweetNaCl.js. -- +var gf = function (init) { + var i, r = new Float64Array(16); + if (init) for (i = 0; i < init.length; i++) r[i] = init[i]; + return r; +}; - var gf = function(init) { - var i, r = new Float64Array(16); - if (init) for (i = 0; i < init.length; i++) r[i] = init[i]; - return r; - }; +var gf0 = gf(), + gf1 = gf([1]), + D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]), + I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]); - var gf0 = gf(), - gf1 = gf([1]), - D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]), - I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]); - - function car25519(o) { - var c; - var i; - for (i = 0; i < 16; i++) { - o[i] += 65536; - c = Math.floor(o[i] / 65536); - o[(i+1)*(i<15?1:0)] += c - 1 + 37 * (c-1) * (i===15?1:0); - o[i] -= (c * 65536); - } - } - - function sel25519(p, q, b) { - var t, c = ~(b-1); - for (var i = 0; i < 16; i++) { - t = c & (p[i] ^ q[i]); - p[i] ^= t; - q[i] ^= t; - } - } - - function unpack25519(o, n) { - var i; - for (i = 0; i < 16; i++) o[i] = n[2*i] + (n[2*i+1] << 8); - o[15] &= 0x7fff; - } - - // addition - function A(o, a, b) { - var i; - for (i = 0; i < 16; i++) o[i] = (a[i] + b[i])|0; - } - - // subtraction - function Z(o, a, b) { - var i; - for (i = 0; i < 16; i++) o[i] = (a[i] - b[i])|0; - } - - // multiplication - function M(o, a, b) { - var i, j, t = new Float64Array(31); - for (i = 0; i < 31; i++) t[i] = 0; - for (i = 0; i < 16; i++) { - for (j = 0; j < 16; j++) { - t[i+j] += a[i] * b[j]; - } - } - for (i = 0; i < 15; i++) { - t[i] += 38 * t[i+16]; - } - for (i = 0; i < 16; i++) o[i] = t[i]; - car25519(o); - car25519(o); - } - - // squaring - function S(o, a) { - M(o, a, a); - } - - // inversion - function inv25519(o, i) { - var c = gf(); - var a; - for (a = 0; a < 16; a++) c[a] = i[a]; - for (a = 253; a >= 0; a--) { - S(c, c); - if(a !== 2 && a !== 4) M(c, c, i); - } - for (a = 0; a < 16; a++) o[a] = c[a]; - } - - function pack25519(o, n) { - var i, j, b; - var m = gf(), t = gf(); - for (i = 0; i < 16; i++) t[i] = n[i]; - car25519(t); - car25519(t); - car25519(t); - for (j = 0; j < 2; j++) { - m[0] = t[0] - 0xffed; - for (i = 1; i < 15; i++) { - m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1); - m[i-1] &= 0xffff; - } - m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1); - b = (m[15]>>16) & 1; - m[14] &= 0xffff; - sel25519(t, m, 1-b); - } - for (i = 0; i < 16; i++) { - o[2*i] = t[i] & 0xff; - o[2*i+1] = t[i] >> 8; - } - } - - function par25519(a) { - var d = new Uint8Array(32); - pack25519(d, a); - return d[0] & 1; - } - - function vn(x, xi, y, yi, n) { - var i, d = 0; - for (i = 0; i < n; i++) d |= x[xi + i] ^ y[yi + i]; - return (1 & ((d - 1) >>> 8)) - 1; - } - - function crypto_verify_32(x, xi, y, yi) { - return vn(x, xi, y, yi, 32); - } - - function neq25519(a, b) { - var c = new Uint8Array(32), d = new Uint8Array(32); - pack25519(c, a); - pack25519(d, b); - return crypto_verify_32(c, 0, d, 0); - } - - function pow2523(o, i) { - var c = gf(); - var a; - for (a = 0; a < 16; a++) c[a] = i[a]; - for (a = 250; a >= 0; a--) { - S(c, c); - if (a !== 1) M(c, c, i); - } - for (a = 0; a < 16; a++) o[a] = c[a]; - } - - function set25519(r, a) { - var i; - for (i = 0; i < 16; i++) r[i] = a[i] | 0; - } - - function unpackneg(r, p) { - var t = gf(), chk = gf(), num = gf(), - den = gf(), den2 = gf(), den4 = gf(), - den6 = gf(); - - set25519(r[2], gf1); - unpack25519(r[1], p); - S(num, r[1]); - M(den, num, D); - Z(num, num, r[2]); - A(den, r[2], den); - - S(den2, den); - S(den4, den2); - M(den6, den4, den2); - M(t, den6, num); - M(t, t, den); - - pow2523(t, t); - M(t, t, num); - M(t, t, den); - M(t, t, den); - M(r[0], t, den); - - S(chk, r[0]); - M(chk, chk, den); - if (neq25519(chk, num)) M(r[0], r[0], I); - - S(chk, r[0]); - M(chk, chk, den); - if (neq25519(chk, num)) return -1; - - if (par25519(r[0]) === (p[31] >> 7)) Z(r[0], gf0, r[0]); - - M(r[3], r[0], r[1]); - return 0; - } - - // ---- - - // Converts Ed25519 public key to Curve25519 public key. - // montgomeryX = (edwardsY + 1)*inverse(1 - edwardsY) mod p - function convertPublicKey(pk) { - var z = new Uint8Array(32), - q = [gf(), gf(), gf(), gf()], - a = gf(), b = gf(); - - if (unpackneg(q, pk)) return null; // reject invalid key - - var y = q[1]; - - A(a, gf1, y); - Z(b, gf1, y); - inv25519(b, b); - M(a, a, b); - - pack25519(z, a); - return z; - } - - // Converts Ed25519 secret key to Curve25519 secret key. - function convertSecretKey(sk) { - var d = new Uint8Array(64), o = new Uint8Array(32), i; - nacl.lowlevel.crypto_hash(d, sk, 32); - d[0] &= 248; - d[31] &= 127; - d[31] |= 64; - for (i = 0; i < 32; i++) o[i] = d[i]; - for (i = 0; i < 64; i++) d[i] = 0; - return o; - } - - function convertKeyPair(edKeyPair) { - var publicKey = convertPublicKey(edKeyPair.publicKey); - if (!publicKey) return null; - return { - publicKey: publicKey, - secretKey: convertSecretKey(edKeyPair.secretKey) - }; - } - -// return { -// convertPublicKey: convertPublicKey, -// convertSecretKey: convertSecretKey, -// convertKeyPair: convertKeyPair, -// }; - -export default { - convertPublicKey: convertPublicKey, - convertSecretKey: convertSecretKey, - convertKeyPair: convertKeyPair, +function car25519(o) { + var c; + var i; + for (i = 0; i < 16; i++) { + o[i] += 65536; + c = Math.floor(o[i] / 65536); + o[(i + 1) * (i < 15 ? 1 : 0)] += c - 1 + 37 * (c - 1) * (i === 15 ? 1 : 0); + o[i] -= (c * 65536); + } } -// })); +function sel25519(p, q, b) { + var t, c = ~(b - 1); + for (var i = 0; i < 16; i++) { + t = c & (p[i] ^ q[i]); + p[i] ^= t; + q[i] ^= t; + } +} + +function unpack25519(o, n) { + var i; + for (i = 0; i < 16; i++) o[i] = n[2 * i] + (n[2 * i + 1] << 8); + o[15] &= 0x7fff; +} + +// addition +function A(o, a, b) { + var i; + for (i = 0; i < 16; i++) o[i] = (a[i] + b[i]) | 0; +} + +// subtraction +function Z(o, a, b) { + var i; + for (i = 0; i < 16; i++) o[i] = (a[i] - b[i]) | 0; +} + +// multiplication +function M(o, a, b) { + var i, j, t = new Float64Array(31); + for (i = 0; i < 31; i++) t[i] = 0; + for (i = 0; i < 16; i++) { + for (j = 0; j < 16; j++) { + t[i + j] += a[i] * b[j]; + } + } + for (i = 0; i < 15; i++) { + t[i] += 38 * t[i + 16]; + } + for (i = 0; i < 16; i++) o[i] = t[i]; + car25519(o); + car25519(o); +} + +// squaring +function S(o, a) { + M(o, a, a); +} + +// inversion +function inv25519(o, i) { + var c = gf(); + var a; + for (a = 0; a < 16; a++) c[a] = i[a]; + for (a = 253; a >= 0; a--) { + S(c, c); + if (a !== 2 && a !== 4) M(c, c, i); + } + for (a = 0; a < 16; a++) o[a] = c[a]; +} + +function pack25519(o, n) { + var i, j, b; + var m = gf(), t = gf(); + for (i = 0; i < 16; i++) t[i] = n[i]; + car25519(t); + car25519(t); + car25519(t); + for (j = 0; j < 2; j++) { + m[0] = t[0] - 0xffed; + for (i = 1; i < 15; i++) { + m[i] = t[i] - 0xffff - ((m[i - 1] >> 16) & 1); + m[i - 1] &= 0xffff; + } + m[15] = t[15] - 0x7fff - ((m[14] >> 16) & 1); + b = (m[15] >> 16) & 1; + m[14] &= 0xffff; + sel25519(t, m, 1 - b); + } + for (i = 0; i < 16; i++) { + o[2 * i] = t[i] & 0xff; + o[2 * i + 1] = t[i] >> 8; + } +} + +function par25519(a) { + var d = new Uint8Array(32); + pack25519(d, a); + return d[0] & 1; +} + +function vn(x, xi, y, yi, n) { + var i, d = 0; + for (i = 0; i < n; i++) d |= x[xi + i] ^ y[yi + i]; + return (1 & ((d - 1) >>> 8)) - 1; +} + +function crypto_verify_32(x, xi, y, yi) { + return vn(x, xi, y, yi, 32); +} + +function neq25519(a, b) { + var c = new Uint8Array(32), d = new Uint8Array(32); + pack25519(c, a); + pack25519(d, b); + return crypto_verify_32(c, 0, d, 0); +} + +function pow2523(o, i) { + var c = gf(); + var a; + for (a = 0; a < 16; a++) c[a] = i[a]; + for (a = 250; a >= 0; a--) { + S(c, c); + if (a !== 1) M(c, c, i); + } + for (a = 0; a < 16; a++) o[a] = c[a]; +} + +function set25519(r, a) { + var i; + for (i = 0; i < 16; i++) r[i] = a[i] | 0; +} + +function unpackneg(r, p) { + var t = gf(), chk = gf(), num = gf(), + den = gf(), den2 = gf(), den4 = gf(), + den6 = gf(); + + set25519(r[2], gf1); + unpack25519(r[1], p); + S(num, r[1]); + M(den, num, D); + Z(num, num, r[2]); + A(den, r[2], den); + + S(den2, den); + S(den4, den2); + M(den6, den4, den2); + M(t, den6, num); + M(t, t, den); + + pow2523(t, t); + M(t, t, num); + M(t, t, den); + M(t, t, den); + M(r[0], t, den); + + S(chk, r[0]); + M(chk, chk, den); + if (neq25519(chk, num)) M(r[0], r[0], I); + + S(chk, r[0]); + M(chk, chk, den); + if (neq25519(chk, num)) return -1; + + if (par25519(r[0]) === (p[31] >> 7)) Z(r[0], gf0, r[0]); + + M(r[3], r[0], r[1]); + return 0; +} + +// ---- + +// Converts Ed25519 public key to Curve25519 public key. +// montgomeryX = (edwardsY + 1)*inverse(1 - edwardsY) mod p +function convertPublicKey(pk) { + var z = new Uint8Array(32), + q = [gf(), gf(), gf(), gf()], + a = gf(), b = gf(); + + if (unpackneg(q, pk)) return null; // reject invalid key + + var y = q[1]; + + A(a, gf1, y); + Z(b, gf1, y); + inv25519(b, b); + M(a, a, b); + + pack25519(z, a); + return z; +} + +// Converts Ed25519 secret key to Curve25519 secret key. +function convertSecretKey(sk) { + var d = new Uint8Array(64), o = new Uint8Array(32), i; + nacl.lowlevel.crypto_hash(d, sk, 32); + d[0] &= 248; + d[31] &= 127; + d[31] |= 64; + for (i = 0; i < 32; i++) o[i] = d[i]; + for (i = 0; i < 64; i++) d[i] = 0; + return o; +} + +function convertKeyPair(edKeyPair) { + var publicKey = convertPublicKey(edKeyPair.publicKey); + if (!publicKey) return null; + return { + publicKey: publicKey, + secretKey: convertSecretKey(edKeyPair.secretKey) + }; +} + +export default { + convertPublicKey: convertPublicKey, + convertSecretKey: convertSecretKey, + convertKeyPair: convertKeyPair, +} diff --git a/crypto/api/deps/nacl-fast.js b/crypto/api/deps/nacl-fast.js index b2fd186f..6693543b 100644 --- a/crypto/api/deps/nacl-fast.js +++ b/crypto/api/deps/nacl-fast.js @@ -1,7 +1,5 @@ // == CHANGE TO ES6 EXPORT == // const nacl = {} -//(function(nacl) { -'use strict'; // Ported in 2014 by Dmitry Chestnykh and Devi Mandiri. // Public domain. @@ -9,456 +7,456 @@ const nacl = {} // Implementation derived from TweetNaCl version 20140427. // See for details: http://tweetnacl.cr.yp.to/ -var gf = function(init) { - var i, r = new Float64Array(16); - if (init) for (i = 0; i < init.length; i++) r[i] = init[i]; - return r; +var gf = function (init) { + var i, r = new Float64Array(16); + if (init) for (i = 0; i < init.length; i++) r[i] = init[i]; + return r; }; // Pluggable, initialized in high-level API below. -var randombytes = function(/* x, n */) { throw new Error('no PRNG'); }; +var randombytes = function (/* x, n */) { throw new Error('no PRNG'); }; var _0 = new Uint8Array(16); var _9 = new Uint8Array(32); _9[0] = 9; var gf0 = gf(), - gf1 = gf([1]), - _121665 = gf([0xdb41, 1]), - D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]), - D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]), - X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]), - Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]), - I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]); + gf1 = gf([1]), + _121665 = gf([0xdb41, 1]), + D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]), + D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]), + X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]), + Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]), + I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]); function ts64(x, i, h, l) { - x[i] = (h >> 24) & 0xff; - x[i+1] = (h >> 16) & 0xff; - x[i+2] = (h >> 8) & 0xff; - x[i+3] = h & 0xff; - x[i+4] = (l >> 24) & 0xff; - x[i+5] = (l >> 16) & 0xff; - x[i+6] = (l >> 8) & 0xff; - x[i+7] = l & 0xff; + x[i] = (h >> 24) & 0xff; + x[i + 1] = (h >> 16) & 0xff; + x[i + 2] = (h >> 8) & 0xff; + x[i + 3] = h & 0xff; + x[i + 4] = (l >> 24) & 0xff; + x[i + 5] = (l >> 16) & 0xff; + x[i + 6] = (l >> 8) & 0xff; + x[i + 7] = l & 0xff; } function vn(x, xi, y, yi, n) { - var i,d = 0; - for (i = 0; i < n; i++) d |= x[xi+i]^y[yi+i]; - return (1 & ((d - 1) >>> 8)) - 1; + var i, d = 0; + for (i = 0; i < n; i++) d |= x[xi + i] ^ y[yi + i]; + return (1 & ((d - 1) >>> 8)) - 1; } function crypto_verify_16(x, xi, y, yi) { - return vn(x,xi,y,yi,16); + return vn(x, xi, y, yi, 16); } function crypto_verify_32(x, xi, y, yi) { - return vn(x,xi,y,yi,32); + return vn(x, xi, y, yi, 32); } function core_salsa20(o, p, k, c) { - var j0 = c[ 0] & 0xff | (c[ 1] & 0xff)<<8 | (c[ 2] & 0xff)<<16 | (c[ 3] & 0xff)<<24, - j1 = k[ 0] & 0xff | (k[ 1] & 0xff)<<8 | (k[ 2] & 0xff)<<16 | (k[ 3] & 0xff)<<24, - j2 = k[ 4] & 0xff | (k[ 5] & 0xff)<<8 | (k[ 6] & 0xff)<<16 | (k[ 7] & 0xff)<<24, - j3 = k[ 8] & 0xff | (k[ 9] & 0xff)<<8 | (k[10] & 0xff)<<16 | (k[11] & 0xff)<<24, - j4 = k[12] & 0xff | (k[13] & 0xff)<<8 | (k[14] & 0xff)<<16 | (k[15] & 0xff)<<24, - j5 = c[ 4] & 0xff | (c[ 5] & 0xff)<<8 | (c[ 6] & 0xff)<<16 | (c[ 7] & 0xff)<<24, - j6 = p[ 0] & 0xff | (p[ 1] & 0xff)<<8 | (p[ 2] & 0xff)<<16 | (p[ 3] & 0xff)<<24, - j7 = p[ 4] & 0xff | (p[ 5] & 0xff)<<8 | (p[ 6] & 0xff)<<16 | (p[ 7] & 0xff)<<24, - j8 = p[ 8] & 0xff | (p[ 9] & 0xff)<<8 | (p[10] & 0xff)<<16 | (p[11] & 0xff)<<24, - j9 = p[12] & 0xff | (p[13] & 0xff)<<8 | (p[14] & 0xff)<<16 | (p[15] & 0xff)<<24, - j10 = c[ 8] & 0xff | (c[ 9] & 0xff)<<8 | (c[10] & 0xff)<<16 | (c[11] & 0xff)<<24, - j11 = k[16] & 0xff | (k[17] & 0xff)<<8 | (k[18] & 0xff)<<16 | (k[19] & 0xff)<<24, - j12 = k[20] & 0xff | (k[21] & 0xff)<<8 | (k[22] & 0xff)<<16 | (k[23] & 0xff)<<24, - j13 = k[24] & 0xff | (k[25] & 0xff)<<8 | (k[26] & 0xff)<<16 | (k[27] & 0xff)<<24, - j14 = k[28] & 0xff | (k[29] & 0xff)<<8 | (k[30] & 0xff)<<16 | (k[31] & 0xff)<<24, - j15 = c[12] & 0xff | (c[13] & 0xff)<<8 | (c[14] & 0xff)<<16 | (c[15] & 0xff)<<24; + var j0 = c[0] & 0xff | (c[1] & 0xff) << 8 | (c[2] & 0xff) << 16 | (c[3] & 0xff) << 24, + j1 = k[0] & 0xff | (k[1] & 0xff) << 8 | (k[2] & 0xff) << 16 | (k[3] & 0xff) << 24, + j2 = k[4] & 0xff | (k[5] & 0xff) << 8 | (k[6] & 0xff) << 16 | (k[7] & 0xff) << 24, + j3 = k[8] & 0xff | (k[9] & 0xff) << 8 | (k[10] & 0xff) << 16 | (k[11] & 0xff) << 24, + j4 = k[12] & 0xff | (k[13] & 0xff) << 8 | (k[14] & 0xff) << 16 | (k[15] & 0xff) << 24, + j5 = c[4] & 0xff | (c[5] & 0xff) << 8 | (c[6] & 0xff) << 16 | (c[7] & 0xff) << 24, + j6 = p[0] & 0xff | (p[1] & 0xff) << 8 | (p[2] & 0xff) << 16 | (p[3] & 0xff) << 24, + j7 = p[4] & 0xff | (p[5] & 0xff) << 8 | (p[6] & 0xff) << 16 | (p[7] & 0xff) << 24, + j8 = p[8] & 0xff | (p[9] & 0xff) << 8 | (p[10] & 0xff) << 16 | (p[11] & 0xff) << 24, + j9 = p[12] & 0xff | (p[13] & 0xff) << 8 | (p[14] & 0xff) << 16 | (p[15] & 0xff) << 24, + j10 = c[8] & 0xff | (c[9] & 0xff) << 8 | (c[10] & 0xff) << 16 | (c[11] & 0xff) << 24, + j11 = k[16] & 0xff | (k[17] & 0xff) << 8 | (k[18] & 0xff) << 16 | (k[19] & 0xff) << 24, + j12 = k[20] & 0xff | (k[21] & 0xff) << 8 | (k[22] & 0xff) << 16 | (k[23] & 0xff) << 24, + j13 = k[24] & 0xff | (k[25] & 0xff) << 8 | (k[26] & 0xff) << 16 | (k[27] & 0xff) << 24, + j14 = k[28] & 0xff | (k[29] & 0xff) << 8 | (k[30] & 0xff) << 16 | (k[31] & 0xff) << 24, + j15 = c[12] & 0xff | (c[13] & 0xff) << 8 | (c[14] & 0xff) << 16 | (c[15] & 0xff) << 24; - var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7, - x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14, - x15 = j15, u; + var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7, + x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14, + x15 = j15, u; - for (var i = 0; i < 20; i += 2) { - u = x0 + x12 | 0; - x4 ^= u<<7 | u>>>(32-7); - u = x4 + x0 | 0; - x8 ^= u<<9 | u>>>(32-9); - u = x8 + x4 | 0; - x12 ^= u<<13 | u>>>(32-13); - u = x12 + x8 | 0; - x0 ^= u<<18 | u>>>(32-18); + for (var i = 0; i < 20; i += 2) { + u = x0 + x12 | 0; + x4 ^= u << 7 | u >>> (32 - 7); + u = x4 + x0 | 0; + x8 ^= u << 9 | u >>> (32 - 9); + u = x8 + x4 | 0; + x12 ^= u << 13 | u >>> (32 - 13); + u = x12 + x8 | 0; + x0 ^= u << 18 | u >>> (32 - 18); - u = x5 + x1 | 0; - x9 ^= u<<7 | u>>>(32-7); - u = x9 + x5 | 0; - x13 ^= u<<9 | u>>>(32-9); - u = x13 + x9 | 0; - x1 ^= u<<13 | u>>>(32-13); - u = x1 + x13 | 0; - x5 ^= u<<18 | u>>>(32-18); + u = x5 + x1 | 0; + x9 ^= u << 7 | u >>> (32 - 7); + u = x9 + x5 | 0; + x13 ^= u << 9 | u >>> (32 - 9); + u = x13 + x9 | 0; + x1 ^= u << 13 | u >>> (32 - 13); + u = x1 + x13 | 0; + x5 ^= u << 18 | u >>> (32 - 18); - u = x10 + x6 | 0; - x14 ^= u<<7 | u>>>(32-7); - u = x14 + x10 | 0; - x2 ^= u<<9 | u>>>(32-9); - u = x2 + x14 | 0; - x6 ^= u<<13 | u>>>(32-13); - u = x6 + x2 | 0; - x10 ^= u<<18 | u>>>(32-18); + u = x10 + x6 | 0; + x14 ^= u << 7 | u >>> (32 - 7); + u = x14 + x10 | 0; + x2 ^= u << 9 | u >>> (32 - 9); + u = x2 + x14 | 0; + x6 ^= u << 13 | u >>> (32 - 13); + u = x6 + x2 | 0; + x10 ^= u << 18 | u >>> (32 - 18); - u = x15 + x11 | 0; - x3 ^= u<<7 | u>>>(32-7); - u = x3 + x15 | 0; - x7 ^= u<<9 | u>>>(32-9); - u = x7 + x3 | 0; - x11 ^= u<<13 | u>>>(32-13); - u = x11 + x7 | 0; - x15 ^= u<<18 | u>>>(32-18); + u = x15 + x11 | 0; + x3 ^= u << 7 | u >>> (32 - 7); + u = x3 + x15 | 0; + x7 ^= u << 9 | u >>> (32 - 9); + u = x7 + x3 | 0; + x11 ^= u << 13 | u >>> (32 - 13); + u = x11 + x7 | 0; + x15 ^= u << 18 | u >>> (32 - 18); - u = x0 + x3 | 0; - x1 ^= u<<7 | u>>>(32-7); - u = x1 + x0 | 0; - x2 ^= u<<9 | u>>>(32-9); - u = x2 + x1 | 0; - x3 ^= u<<13 | u>>>(32-13); - u = x3 + x2 | 0; - x0 ^= u<<18 | u>>>(32-18); + u = x0 + x3 | 0; + x1 ^= u << 7 | u >>> (32 - 7); + u = x1 + x0 | 0; + x2 ^= u << 9 | u >>> (32 - 9); + u = x2 + x1 | 0; + x3 ^= u << 13 | u >>> (32 - 13); + u = x3 + x2 | 0; + x0 ^= u << 18 | u >>> (32 - 18); - u = x5 + x4 | 0; - x6 ^= u<<7 | u>>>(32-7); - u = x6 + x5 | 0; - x7 ^= u<<9 | u>>>(32-9); - u = x7 + x6 | 0; - x4 ^= u<<13 | u>>>(32-13); - u = x4 + x7 | 0; - x5 ^= u<<18 | u>>>(32-18); + u = x5 + x4 | 0; + x6 ^= u << 7 | u >>> (32 - 7); + u = x6 + x5 | 0; + x7 ^= u << 9 | u >>> (32 - 9); + u = x7 + x6 | 0; + x4 ^= u << 13 | u >>> (32 - 13); + u = x4 + x7 | 0; + x5 ^= u << 18 | u >>> (32 - 18); - u = x10 + x9 | 0; - x11 ^= u<<7 | u>>>(32-7); - u = x11 + x10 | 0; - x8 ^= u<<9 | u>>>(32-9); - u = x8 + x11 | 0; - x9 ^= u<<13 | u>>>(32-13); - u = x9 + x8 | 0; - x10 ^= u<<18 | u>>>(32-18); + u = x10 + x9 | 0; + x11 ^= u << 7 | u >>> (32 - 7); + u = x11 + x10 | 0; + x8 ^= u << 9 | u >>> (32 - 9); + u = x8 + x11 | 0; + x9 ^= u << 13 | u >>> (32 - 13); + u = x9 + x8 | 0; + x10 ^= u << 18 | u >>> (32 - 18); - u = x15 + x14 | 0; - x12 ^= u<<7 | u>>>(32-7); - u = x12 + x15 | 0; - x13 ^= u<<9 | u>>>(32-9); - u = x13 + x12 | 0; - x14 ^= u<<13 | u>>>(32-13); - u = x14 + x13 | 0; - x15 ^= u<<18 | u>>>(32-18); - } - x0 = x0 + j0 | 0; - x1 = x1 + j1 | 0; - x2 = x2 + j2 | 0; - x3 = x3 + j3 | 0; - x4 = x4 + j4 | 0; - x5 = x5 + j5 | 0; - x6 = x6 + j6 | 0; - x7 = x7 + j7 | 0; - x8 = x8 + j8 | 0; - x9 = x9 + j9 | 0; - x10 = x10 + j10 | 0; - x11 = x11 + j11 | 0; - x12 = x12 + j12 | 0; - x13 = x13 + j13 | 0; - x14 = x14 + j14 | 0; - x15 = x15 + j15 | 0; + u = x15 + x14 | 0; + x12 ^= u << 7 | u >>> (32 - 7); + u = x12 + x15 | 0; + x13 ^= u << 9 | u >>> (32 - 9); + u = x13 + x12 | 0; + x14 ^= u << 13 | u >>> (32 - 13); + u = x14 + x13 | 0; + x15 ^= u << 18 | u >>> (32 - 18); + } + x0 = x0 + j0 | 0; + x1 = x1 + j1 | 0; + x2 = x2 + j2 | 0; + x3 = x3 + j3 | 0; + x4 = x4 + j4 | 0; + x5 = x5 + j5 | 0; + x6 = x6 + j6 | 0; + x7 = x7 + j7 | 0; + x8 = x8 + j8 | 0; + x9 = x9 + j9 | 0; + x10 = x10 + j10 | 0; + x11 = x11 + j11 | 0; + x12 = x12 + j12 | 0; + x13 = x13 + j13 | 0; + x14 = x14 + j14 | 0; + x15 = x15 + j15 | 0; - o[ 0] = x0 >>> 0 & 0xff; - o[ 1] = x0 >>> 8 & 0xff; - o[ 2] = x0 >>> 16 & 0xff; - o[ 3] = x0 >>> 24 & 0xff; + o[0] = x0 >>> 0 & 0xff; + o[1] = x0 >>> 8 & 0xff; + o[2] = x0 >>> 16 & 0xff; + o[3] = x0 >>> 24 & 0xff; - o[ 4] = x1 >>> 0 & 0xff; - o[ 5] = x1 >>> 8 & 0xff; - o[ 6] = x1 >>> 16 & 0xff; - o[ 7] = x1 >>> 24 & 0xff; + o[4] = x1 >>> 0 & 0xff; + o[5] = x1 >>> 8 & 0xff; + o[6] = x1 >>> 16 & 0xff; + o[7] = x1 >>> 24 & 0xff; - o[ 8] = x2 >>> 0 & 0xff; - o[ 9] = x2 >>> 8 & 0xff; - o[10] = x2 >>> 16 & 0xff; - o[11] = x2 >>> 24 & 0xff; + o[8] = x2 >>> 0 & 0xff; + o[9] = x2 >>> 8 & 0xff; + o[10] = x2 >>> 16 & 0xff; + o[11] = x2 >>> 24 & 0xff; - o[12] = x3 >>> 0 & 0xff; - o[13] = x3 >>> 8 & 0xff; - o[14] = x3 >>> 16 & 0xff; - o[15] = x3 >>> 24 & 0xff; + o[12] = x3 >>> 0 & 0xff; + o[13] = x3 >>> 8 & 0xff; + o[14] = x3 >>> 16 & 0xff; + o[15] = x3 >>> 24 & 0xff; - o[16] = x4 >>> 0 & 0xff; - o[17] = x4 >>> 8 & 0xff; - o[18] = x4 >>> 16 & 0xff; - o[19] = x4 >>> 24 & 0xff; + o[16] = x4 >>> 0 & 0xff; + o[17] = x4 >>> 8 & 0xff; + o[18] = x4 >>> 16 & 0xff; + o[19] = x4 >>> 24 & 0xff; - o[20] = x5 >>> 0 & 0xff; - o[21] = x5 >>> 8 & 0xff; - o[22] = x5 >>> 16 & 0xff; - o[23] = x5 >>> 24 & 0xff; + o[20] = x5 >>> 0 & 0xff; + o[21] = x5 >>> 8 & 0xff; + o[22] = x5 >>> 16 & 0xff; + o[23] = x5 >>> 24 & 0xff; - o[24] = x6 >>> 0 & 0xff; - o[25] = x6 >>> 8 & 0xff; - o[26] = x6 >>> 16 & 0xff; - o[27] = x6 >>> 24 & 0xff; + o[24] = x6 >>> 0 & 0xff; + o[25] = x6 >>> 8 & 0xff; + o[26] = x6 >>> 16 & 0xff; + o[27] = x6 >>> 24 & 0xff; - o[28] = x7 >>> 0 & 0xff; - o[29] = x7 >>> 8 & 0xff; - o[30] = x7 >>> 16 & 0xff; - o[31] = x7 >>> 24 & 0xff; + o[28] = x7 >>> 0 & 0xff; + o[29] = x7 >>> 8 & 0xff; + o[30] = x7 >>> 16 & 0xff; + o[31] = x7 >>> 24 & 0xff; - o[32] = x8 >>> 0 & 0xff; - o[33] = x8 >>> 8 & 0xff; - o[34] = x8 >>> 16 & 0xff; - o[35] = x8 >>> 24 & 0xff; + o[32] = x8 >>> 0 & 0xff; + o[33] = x8 >>> 8 & 0xff; + o[34] = x8 >>> 16 & 0xff; + o[35] = x8 >>> 24 & 0xff; - o[36] = x9 >>> 0 & 0xff; - o[37] = x9 >>> 8 & 0xff; - o[38] = x9 >>> 16 & 0xff; - o[39] = x9 >>> 24 & 0xff; + o[36] = x9 >>> 0 & 0xff; + o[37] = x9 >>> 8 & 0xff; + o[38] = x9 >>> 16 & 0xff; + o[39] = x9 >>> 24 & 0xff; - o[40] = x10 >>> 0 & 0xff; - o[41] = x10 >>> 8 & 0xff; - o[42] = x10 >>> 16 & 0xff; - o[43] = x10 >>> 24 & 0xff; + o[40] = x10 >>> 0 & 0xff; + o[41] = x10 >>> 8 & 0xff; + o[42] = x10 >>> 16 & 0xff; + o[43] = x10 >>> 24 & 0xff; - o[44] = x11 >>> 0 & 0xff; - o[45] = x11 >>> 8 & 0xff; - o[46] = x11 >>> 16 & 0xff; - o[47] = x11 >>> 24 & 0xff; + o[44] = x11 >>> 0 & 0xff; + o[45] = x11 >>> 8 & 0xff; + o[46] = x11 >>> 16 & 0xff; + o[47] = x11 >>> 24 & 0xff; - o[48] = x12 >>> 0 & 0xff; - o[49] = x12 >>> 8 & 0xff; - o[50] = x12 >>> 16 & 0xff; - o[51] = x12 >>> 24 & 0xff; + o[48] = x12 >>> 0 & 0xff; + o[49] = x12 >>> 8 & 0xff; + o[50] = x12 >>> 16 & 0xff; + o[51] = x12 >>> 24 & 0xff; - o[52] = x13 >>> 0 & 0xff; - o[53] = x13 >>> 8 & 0xff; - o[54] = x13 >>> 16 & 0xff; - o[55] = x13 >>> 24 & 0xff; + o[52] = x13 >>> 0 & 0xff; + o[53] = x13 >>> 8 & 0xff; + o[54] = x13 >>> 16 & 0xff; + o[55] = x13 >>> 24 & 0xff; - o[56] = x14 >>> 0 & 0xff; - o[57] = x14 >>> 8 & 0xff; - o[58] = x14 >>> 16 & 0xff; - o[59] = x14 >>> 24 & 0xff; + o[56] = x14 >>> 0 & 0xff; + o[57] = x14 >>> 8 & 0xff; + o[58] = x14 >>> 16 & 0xff; + o[59] = x14 >>> 24 & 0xff; - o[60] = x15 >>> 0 & 0xff; - o[61] = x15 >>> 8 & 0xff; - o[62] = x15 >>> 16 & 0xff; - o[63] = x15 >>> 24 & 0xff; + o[60] = x15 >>> 0 & 0xff; + o[61] = x15 >>> 8 & 0xff; + o[62] = x15 >>> 16 & 0xff; + o[63] = x15 >>> 24 & 0xff; } -function core_hsalsa20(o,p,k,c) { - var j0 = c[ 0] & 0xff | (c[ 1] & 0xff)<<8 | (c[ 2] & 0xff)<<16 | (c[ 3] & 0xff)<<24, - j1 = k[ 0] & 0xff | (k[ 1] & 0xff)<<8 | (k[ 2] & 0xff)<<16 | (k[ 3] & 0xff)<<24, - j2 = k[ 4] & 0xff | (k[ 5] & 0xff)<<8 | (k[ 6] & 0xff)<<16 | (k[ 7] & 0xff)<<24, - j3 = k[ 8] & 0xff | (k[ 9] & 0xff)<<8 | (k[10] & 0xff)<<16 | (k[11] & 0xff)<<24, - j4 = k[12] & 0xff | (k[13] & 0xff)<<8 | (k[14] & 0xff)<<16 | (k[15] & 0xff)<<24, - j5 = c[ 4] & 0xff | (c[ 5] & 0xff)<<8 | (c[ 6] & 0xff)<<16 | (c[ 7] & 0xff)<<24, - j6 = p[ 0] & 0xff | (p[ 1] & 0xff)<<8 | (p[ 2] & 0xff)<<16 | (p[ 3] & 0xff)<<24, - j7 = p[ 4] & 0xff | (p[ 5] & 0xff)<<8 | (p[ 6] & 0xff)<<16 | (p[ 7] & 0xff)<<24, - j8 = p[ 8] & 0xff | (p[ 9] & 0xff)<<8 | (p[10] & 0xff)<<16 | (p[11] & 0xff)<<24, - j9 = p[12] & 0xff | (p[13] & 0xff)<<8 | (p[14] & 0xff)<<16 | (p[15] & 0xff)<<24, - j10 = c[ 8] & 0xff | (c[ 9] & 0xff)<<8 | (c[10] & 0xff)<<16 | (c[11] & 0xff)<<24, - j11 = k[16] & 0xff | (k[17] & 0xff)<<8 | (k[18] & 0xff)<<16 | (k[19] & 0xff)<<24, - j12 = k[20] & 0xff | (k[21] & 0xff)<<8 | (k[22] & 0xff)<<16 | (k[23] & 0xff)<<24, - j13 = k[24] & 0xff | (k[25] & 0xff)<<8 | (k[26] & 0xff)<<16 | (k[27] & 0xff)<<24, - j14 = k[28] & 0xff | (k[29] & 0xff)<<8 | (k[30] & 0xff)<<16 | (k[31] & 0xff)<<24, - j15 = c[12] & 0xff | (c[13] & 0xff)<<8 | (c[14] & 0xff)<<16 | (c[15] & 0xff)<<24; +function core_hsalsa20(o, p, k, c) { + var j0 = c[0] & 0xff | (c[1] & 0xff) << 8 | (c[2] & 0xff) << 16 | (c[3] & 0xff) << 24, + j1 = k[0] & 0xff | (k[1] & 0xff) << 8 | (k[2] & 0xff) << 16 | (k[3] & 0xff) << 24, + j2 = k[4] & 0xff | (k[5] & 0xff) << 8 | (k[6] & 0xff) << 16 | (k[7] & 0xff) << 24, + j3 = k[8] & 0xff | (k[9] & 0xff) << 8 | (k[10] & 0xff) << 16 | (k[11] & 0xff) << 24, + j4 = k[12] & 0xff | (k[13] & 0xff) << 8 | (k[14] & 0xff) << 16 | (k[15] & 0xff) << 24, + j5 = c[4] & 0xff | (c[5] & 0xff) << 8 | (c[6] & 0xff) << 16 | (c[7] & 0xff) << 24, + j6 = p[0] & 0xff | (p[1] & 0xff) << 8 | (p[2] & 0xff) << 16 | (p[3] & 0xff) << 24, + j7 = p[4] & 0xff | (p[5] & 0xff) << 8 | (p[6] & 0xff) << 16 | (p[7] & 0xff) << 24, + j8 = p[8] & 0xff | (p[9] & 0xff) << 8 | (p[10] & 0xff) << 16 | (p[11] & 0xff) << 24, + j9 = p[12] & 0xff | (p[13] & 0xff) << 8 | (p[14] & 0xff) << 16 | (p[15] & 0xff) << 24, + j10 = c[8] & 0xff | (c[9] & 0xff) << 8 | (c[10] & 0xff) << 16 | (c[11] & 0xff) << 24, + j11 = k[16] & 0xff | (k[17] & 0xff) << 8 | (k[18] & 0xff) << 16 | (k[19] & 0xff) << 24, + j12 = k[20] & 0xff | (k[21] & 0xff) << 8 | (k[22] & 0xff) << 16 | (k[23] & 0xff) << 24, + j13 = k[24] & 0xff | (k[25] & 0xff) << 8 | (k[26] & 0xff) << 16 | (k[27] & 0xff) << 24, + j14 = k[28] & 0xff | (k[29] & 0xff) << 8 | (k[30] & 0xff) << 16 | (k[31] & 0xff) << 24, + j15 = c[12] & 0xff | (c[13] & 0xff) << 8 | (c[14] & 0xff) << 16 | (c[15] & 0xff) << 24; - var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7, - x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14, - x15 = j15, u; + var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7, + x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14, + x15 = j15, u; - for (var i = 0; i < 20; i += 2) { - u = x0 + x12 | 0; - x4 ^= u<<7 | u>>>(32-7); - u = x4 + x0 | 0; - x8 ^= u<<9 | u>>>(32-9); - u = x8 + x4 | 0; - x12 ^= u<<13 | u>>>(32-13); - u = x12 + x8 | 0; - x0 ^= u<<18 | u>>>(32-18); + for (var i = 0; i < 20; i += 2) { + u = x0 + x12 | 0; + x4 ^= u << 7 | u >>> (32 - 7); + u = x4 + x0 | 0; + x8 ^= u << 9 | u >>> (32 - 9); + u = x8 + x4 | 0; + x12 ^= u << 13 | u >>> (32 - 13); + u = x12 + x8 | 0; + x0 ^= u << 18 | u >>> (32 - 18); - u = x5 + x1 | 0; - x9 ^= u<<7 | u>>>(32-7); - u = x9 + x5 | 0; - x13 ^= u<<9 | u>>>(32-9); - u = x13 + x9 | 0; - x1 ^= u<<13 | u>>>(32-13); - u = x1 + x13 | 0; - x5 ^= u<<18 | u>>>(32-18); + u = x5 + x1 | 0; + x9 ^= u << 7 | u >>> (32 - 7); + u = x9 + x5 | 0; + x13 ^= u << 9 | u >>> (32 - 9); + u = x13 + x9 | 0; + x1 ^= u << 13 | u >>> (32 - 13); + u = x1 + x13 | 0; + x5 ^= u << 18 | u >>> (32 - 18); - u = x10 + x6 | 0; - x14 ^= u<<7 | u>>>(32-7); - u = x14 + x10 | 0; - x2 ^= u<<9 | u>>>(32-9); - u = x2 + x14 | 0; - x6 ^= u<<13 | u>>>(32-13); - u = x6 + x2 | 0; - x10 ^= u<<18 | u>>>(32-18); + u = x10 + x6 | 0; + x14 ^= u << 7 | u >>> (32 - 7); + u = x14 + x10 | 0; + x2 ^= u << 9 | u >>> (32 - 9); + u = x2 + x14 | 0; + x6 ^= u << 13 | u >>> (32 - 13); + u = x6 + x2 | 0; + x10 ^= u << 18 | u >>> (32 - 18); - u = x15 + x11 | 0; - x3 ^= u<<7 | u>>>(32-7); - u = x3 + x15 | 0; - x7 ^= u<<9 | u>>>(32-9); - u = x7 + x3 | 0; - x11 ^= u<<13 | u>>>(32-13); - u = x11 + x7 | 0; - x15 ^= u<<18 | u>>>(32-18); + u = x15 + x11 | 0; + x3 ^= u << 7 | u >>> (32 - 7); + u = x3 + x15 | 0; + x7 ^= u << 9 | u >>> (32 - 9); + u = x7 + x3 | 0; + x11 ^= u << 13 | u >>> (32 - 13); + u = x11 + x7 | 0; + x15 ^= u << 18 | u >>> (32 - 18); - u = x0 + x3 | 0; - x1 ^= u<<7 | u>>>(32-7); - u = x1 + x0 | 0; - x2 ^= u<<9 | u>>>(32-9); - u = x2 + x1 | 0; - x3 ^= u<<13 | u>>>(32-13); - u = x3 + x2 | 0; - x0 ^= u<<18 | u>>>(32-18); + u = x0 + x3 | 0; + x1 ^= u << 7 | u >>> (32 - 7); + u = x1 + x0 | 0; + x2 ^= u << 9 | u >>> (32 - 9); + u = x2 + x1 | 0; + x3 ^= u << 13 | u >>> (32 - 13); + u = x3 + x2 | 0; + x0 ^= u << 18 | u >>> (32 - 18); - u = x5 + x4 | 0; - x6 ^= u<<7 | u>>>(32-7); - u = x6 + x5 | 0; - x7 ^= u<<9 | u>>>(32-9); - u = x7 + x6 | 0; - x4 ^= u<<13 | u>>>(32-13); - u = x4 + x7 | 0; - x5 ^= u<<18 | u>>>(32-18); + u = x5 + x4 | 0; + x6 ^= u << 7 | u >>> (32 - 7); + u = x6 + x5 | 0; + x7 ^= u << 9 | u >>> (32 - 9); + u = x7 + x6 | 0; + x4 ^= u << 13 | u >>> (32 - 13); + u = x4 + x7 | 0; + x5 ^= u << 18 | u >>> (32 - 18); - u = x10 + x9 | 0; - x11 ^= u<<7 | u>>>(32-7); - u = x11 + x10 | 0; - x8 ^= u<<9 | u>>>(32-9); - u = x8 + x11 | 0; - x9 ^= u<<13 | u>>>(32-13); - u = x9 + x8 | 0; - x10 ^= u<<18 | u>>>(32-18); + u = x10 + x9 | 0; + x11 ^= u << 7 | u >>> (32 - 7); + u = x11 + x10 | 0; + x8 ^= u << 9 | u >>> (32 - 9); + u = x8 + x11 | 0; + x9 ^= u << 13 | u >>> (32 - 13); + u = x9 + x8 | 0; + x10 ^= u << 18 | u >>> (32 - 18); - u = x15 + x14 | 0; - x12 ^= u<<7 | u>>>(32-7); - u = x12 + x15 | 0; - x13 ^= u<<9 | u>>>(32-9); - u = x13 + x12 | 0; - x14 ^= u<<13 | u>>>(32-13); - u = x14 + x13 | 0; - x15 ^= u<<18 | u>>>(32-18); - } + u = x15 + x14 | 0; + x12 ^= u << 7 | u >>> (32 - 7); + u = x12 + x15 | 0; + x13 ^= u << 9 | u >>> (32 - 9); + u = x13 + x12 | 0; + x14 ^= u << 13 | u >>> (32 - 13); + u = x14 + x13 | 0; + x15 ^= u << 18 | u >>> (32 - 18); + } - o[ 0] = x0 >>> 0 & 0xff; - o[ 1] = x0 >>> 8 & 0xff; - o[ 2] = x0 >>> 16 & 0xff; - o[ 3] = x0 >>> 24 & 0xff; + o[0] = x0 >>> 0 & 0xff; + o[1] = x0 >>> 8 & 0xff; + o[2] = x0 >>> 16 & 0xff; + o[3] = x0 >>> 24 & 0xff; - o[ 4] = x5 >>> 0 & 0xff; - o[ 5] = x5 >>> 8 & 0xff; - o[ 6] = x5 >>> 16 & 0xff; - o[ 7] = x5 >>> 24 & 0xff; + o[4] = x5 >>> 0 & 0xff; + o[5] = x5 >>> 8 & 0xff; + o[6] = x5 >>> 16 & 0xff; + o[7] = x5 >>> 24 & 0xff; - o[ 8] = x10 >>> 0 & 0xff; - o[ 9] = x10 >>> 8 & 0xff; - o[10] = x10 >>> 16 & 0xff; - o[11] = x10 >>> 24 & 0xff; + o[8] = x10 >>> 0 & 0xff; + o[9] = x10 >>> 8 & 0xff; + o[10] = x10 >>> 16 & 0xff; + o[11] = x10 >>> 24 & 0xff; - o[12] = x15 >>> 0 & 0xff; - o[13] = x15 >>> 8 & 0xff; - o[14] = x15 >>> 16 & 0xff; - o[15] = x15 >>> 24 & 0xff; + o[12] = x15 >>> 0 & 0xff; + o[13] = x15 >>> 8 & 0xff; + o[14] = x15 >>> 16 & 0xff; + o[15] = x15 >>> 24 & 0xff; - o[16] = x6 >>> 0 & 0xff; - o[17] = x6 >>> 8 & 0xff; - o[18] = x6 >>> 16 & 0xff; - o[19] = x6 >>> 24 & 0xff; + o[16] = x6 >>> 0 & 0xff; + o[17] = x6 >>> 8 & 0xff; + o[18] = x6 >>> 16 & 0xff; + o[19] = x6 >>> 24 & 0xff; - o[20] = x7 >>> 0 & 0xff; - o[21] = x7 >>> 8 & 0xff; - o[22] = x7 >>> 16 & 0xff; - o[23] = x7 >>> 24 & 0xff; + o[20] = x7 >>> 0 & 0xff; + o[21] = x7 >>> 8 & 0xff; + o[22] = x7 >>> 16 & 0xff; + o[23] = x7 >>> 24 & 0xff; - o[24] = x8 >>> 0 & 0xff; - o[25] = x8 >>> 8 & 0xff; - o[26] = x8 >>> 16 & 0xff; - o[27] = x8 >>> 24 & 0xff; + o[24] = x8 >>> 0 & 0xff; + o[25] = x8 >>> 8 & 0xff; + o[26] = x8 >>> 16 & 0xff; + o[27] = x8 >>> 24 & 0xff; - o[28] = x9 >>> 0 & 0xff; - o[29] = x9 >>> 8 & 0xff; - o[30] = x9 >>> 16 & 0xff; - o[31] = x9 >>> 24 & 0xff; + o[28] = x9 >>> 0 & 0xff; + o[29] = x9 >>> 8 & 0xff; + o[30] = x9 >>> 16 & 0xff; + o[31] = x9 >>> 24 & 0xff; } -function crypto_core_salsa20(out,inp,k,c) { - core_salsa20(out,inp,k,c); +function crypto_core_salsa20(out, inp, k, c) { + core_salsa20(out, inp, k, c); } -function crypto_core_hsalsa20(out,inp,k,c) { - core_hsalsa20(out,inp,k,c); +function crypto_core_hsalsa20(out, inp, k, c) { + core_hsalsa20(out, inp, k, c); } var sigma = new Uint8Array([101, 120, 112, 97, 110, 100, 32, 51, 50, 45, 98, 121, 116, 101, 32, 107]); - // "expand 32-byte k" +// "expand 32-byte k" -function crypto_stream_salsa20_xor(c,cpos,m,mpos,b,n,k) { - var z = new Uint8Array(16), x = new Uint8Array(64); - var u, i; - for (i = 0; i < 16; i++) z[i] = 0; - for (i = 0; i < 8; i++) z[i] = n[i]; - while (b >= 64) { - crypto_core_salsa20(x,z,k,sigma); - for (i = 0; i < 64; i++) c[cpos+i] = m[mpos+i] ^ x[i]; - u = 1; - for (i = 8; i < 16; i++) { - u = u + (z[i] & 0xff) | 0; - z[i] = u & 0xff; - u >>>= 8; - } - b -= 64; - cpos += 64; - mpos += 64; - } - if (b > 0) { - crypto_core_salsa20(x,z,k,sigma); - for (i = 0; i < b; i++) c[cpos+i] = m[mpos+i] ^ x[i]; - } - return 0; +function crypto_stream_salsa20_xor(c, cpos, m, mpos, b, n, k) { + var z = new Uint8Array(16), x = new Uint8Array(64); + var u, i; + for (i = 0; i < 16; i++) z[i] = 0; + for (i = 0; i < 8; i++) z[i] = n[i]; + while (b >= 64) { + crypto_core_salsa20(x, z, k, sigma); + for (i = 0; i < 64; i++) c[cpos + i] = m[mpos + i] ^ x[i]; + u = 1; + for (i = 8; i < 16; i++) { + u = u + (z[i] & 0xff) | 0; + z[i] = u & 0xff; + u >>>= 8; + } + b -= 64; + cpos += 64; + mpos += 64; + } + if (b > 0) { + crypto_core_salsa20(x, z, k, sigma); + for (i = 0; i < b; i++) c[cpos + i] = m[mpos + i] ^ x[i]; + } + return 0; } -function crypto_stream_salsa20(c,cpos,b,n,k) { - var z = new Uint8Array(16), x = new Uint8Array(64); - var u, i; - for (i = 0; i < 16; i++) z[i] = 0; - for (i = 0; i < 8; i++) z[i] = n[i]; - while (b >= 64) { - crypto_core_salsa20(x,z,k,sigma); - for (i = 0; i < 64; i++) c[cpos+i] = x[i]; - u = 1; - for (i = 8; i < 16; i++) { - u = u + (z[i] & 0xff) | 0; - z[i] = u & 0xff; - u >>>= 8; - } - b -= 64; - cpos += 64; - } - if (b > 0) { - crypto_core_salsa20(x,z,k,sigma); - for (i = 0; i < b; i++) c[cpos+i] = x[i]; - } - return 0; +function crypto_stream_salsa20(c, cpos, b, n, k) { + var z = new Uint8Array(16), x = new Uint8Array(64); + var u, i; + for (i = 0; i < 16; i++) z[i] = 0; + for (i = 0; i < 8; i++) z[i] = n[i]; + while (b >= 64) { + crypto_core_salsa20(x, z, k, sigma); + for (i = 0; i < 64; i++) c[cpos + i] = x[i]; + u = 1; + for (i = 8; i < 16; i++) { + u = u + (z[i] & 0xff) | 0; + z[i] = u & 0xff; + u >>>= 8; + } + b -= 64; + cpos += 64; + } + if (b > 0) { + crypto_core_salsa20(x, z, k, sigma); + for (i = 0; i < b; i++) c[cpos + i] = x[i]; + } + return 0; } -function crypto_stream(c,cpos,d,n,k) { - var s = new Uint8Array(32); - crypto_core_hsalsa20(s,n,k,sigma); - var sn = new Uint8Array(8); - for (var i = 0; i < 8; i++) sn[i] = n[i+16]; - return crypto_stream_salsa20(c,cpos,d,sn,s); +function crypto_stream(c, cpos, d, n, k) { + var s = new Uint8Array(32); + crypto_core_hsalsa20(s, n, k, sigma); + var sn = new Uint8Array(8); + for (var i = 0; i < 8; i++) sn[i] = n[i + 16]; + return crypto_stream_salsa20(c, cpos, d, sn, s); } -function crypto_stream_xor(c,cpos,m,mpos,d,n,k) { - var s = new Uint8Array(32); - crypto_core_hsalsa20(s,n,k,sigma); - var sn = new Uint8Array(8); - for (var i = 0; i < 8; i++) sn[i] = n[i+16]; - return crypto_stream_salsa20_xor(c,cpos,m,mpos,d,sn,s); +function crypto_stream_xor(c, cpos, m, mpos, d, n, k) { + var s = new Uint8Array(32); + crypto_core_hsalsa20(s, n, k, sigma); + var sn = new Uint8Array(8); + for (var i = 0; i < 8; i++) sn[i] = n[i + 16]; + return crypto_stream_salsa20_xor(c, cpos, m, mpos, d, sn, s); } /* @@ -466,1820 +464,1820 @@ function crypto_stream_xor(c,cpos,m,mpos,d,n,k) { * https://github.com/floodyberry/poly1305-donna */ -var poly1305 = function(key) { - this.buffer = new Uint8Array(16); - this.r = new Uint16Array(10); - this.h = new Uint16Array(10); - this.pad = new Uint16Array(8); - this.leftover = 0; - this.fin = 0; +var poly1305 = function (key) { + this.buffer = new Uint8Array(16); + this.r = new Uint16Array(10); + this.h = new Uint16Array(10); + this.pad = new Uint16Array(8); + this.leftover = 0; + this.fin = 0; - var t0, t1, t2, t3, t4, t5, t6, t7; + var t0, t1, t2, t3, t4, t5, t6, t7; - t0 = key[ 0] & 0xff | (key[ 1] & 0xff) << 8; this.r[0] = ( t0 ) & 0x1fff; - t1 = key[ 2] & 0xff | (key[ 3] & 0xff) << 8; this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff; - t2 = key[ 4] & 0xff | (key[ 5] & 0xff) << 8; this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03; - t3 = key[ 6] & 0xff | (key[ 7] & 0xff) << 8; this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff; - t4 = key[ 8] & 0xff | (key[ 9] & 0xff) << 8; this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff; - this.r[5] = ((t4 >>> 1)) & 0x1ffe; - t5 = key[10] & 0xff | (key[11] & 0xff) << 8; this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff; - t6 = key[12] & 0xff | (key[13] & 0xff) << 8; this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81; - t7 = key[14] & 0xff | (key[15] & 0xff) << 8; this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff; - this.r[9] = ((t7 >>> 5)) & 0x007f; + t0 = key[0] & 0xff | (key[1] & 0xff) << 8; this.r[0] = (t0) & 0x1fff; + t1 = key[2] & 0xff | (key[3] & 0xff) << 8; this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff; + t2 = key[4] & 0xff | (key[5] & 0xff) << 8; this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03; + t3 = key[6] & 0xff | (key[7] & 0xff) << 8; this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff; + t4 = key[8] & 0xff | (key[9] & 0xff) << 8; this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff; + this.r[5] = ((t4 >>> 1)) & 0x1ffe; + t5 = key[10] & 0xff | (key[11] & 0xff) << 8; this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff; + t6 = key[12] & 0xff | (key[13] & 0xff) << 8; this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81; + t7 = key[14] & 0xff | (key[15] & 0xff) << 8; this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff; + this.r[9] = ((t7 >>> 5)) & 0x007f; - this.pad[0] = key[16] & 0xff | (key[17] & 0xff) << 8; - this.pad[1] = key[18] & 0xff | (key[19] & 0xff) << 8; - this.pad[2] = key[20] & 0xff | (key[21] & 0xff) << 8; - this.pad[3] = key[22] & 0xff | (key[23] & 0xff) << 8; - this.pad[4] = key[24] & 0xff | (key[25] & 0xff) << 8; - this.pad[5] = key[26] & 0xff | (key[27] & 0xff) << 8; - this.pad[6] = key[28] & 0xff | (key[29] & 0xff) << 8; - this.pad[7] = key[30] & 0xff | (key[31] & 0xff) << 8; + this.pad[0] = key[16] & 0xff | (key[17] & 0xff) << 8; + this.pad[1] = key[18] & 0xff | (key[19] & 0xff) << 8; + this.pad[2] = key[20] & 0xff | (key[21] & 0xff) << 8; + this.pad[3] = key[22] & 0xff | (key[23] & 0xff) << 8; + this.pad[4] = key[24] & 0xff | (key[25] & 0xff) << 8; + this.pad[5] = key[26] & 0xff | (key[27] & 0xff) << 8; + this.pad[6] = key[28] & 0xff | (key[29] & 0xff) << 8; + this.pad[7] = key[30] & 0xff | (key[31] & 0xff) << 8; }; -poly1305.prototype.blocks = function(m, mpos, bytes) { - var hibit = this.fin ? 0 : (1 << 11); - var t0, t1, t2, t3, t4, t5, t6, t7, c; - var d0, d1, d2, d3, d4, d5, d6, d7, d8, d9; +poly1305.prototype.blocks = function (m, mpos, bytes) { + var hibit = this.fin ? 0 : (1 << 11); + var t0, t1, t2, t3, t4, t5, t6, t7, c; + var d0, d1, d2, d3, d4, d5, d6, d7, d8, d9; - var h0 = this.h[0], - h1 = this.h[1], - h2 = this.h[2], - h3 = this.h[3], - h4 = this.h[4], - h5 = this.h[5], - h6 = this.h[6], - h7 = this.h[7], - h8 = this.h[8], - h9 = this.h[9]; + var h0 = this.h[0], + h1 = this.h[1], + h2 = this.h[2], + h3 = this.h[3], + h4 = this.h[4], + h5 = this.h[5], + h6 = this.h[6], + h7 = this.h[7], + h8 = this.h[8], + h9 = this.h[9]; - var r0 = this.r[0], - r1 = this.r[1], - r2 = this.r[2], - r3 = this.r[3], - r4 = this.r[4], - r5 = this.r[5], - r6 = this.r[6], - r7 = this.r[7], - r8 = this.r[8], - r9 = this.r[9]; + var r0 = this.r[0], + r1 = this.r[1], + r2 = this.r[2], + r3 = this.r[3], + r4 = this.r[4], + r5 = this.r[5], + r6 = this.r[6], + r7 = this.r[7], + r8 = this.r[8], + r9 = this.r[9]; - while (bytes >= 16) { - t0 = m[mpos+ 0] & 0xff | (m[mpos+ 1] & 0xff) << 8; h0 += ( t0 ) & 0x1fff; - t1 = m[mpos+ 2] & 0xff | (m[mpos+ 3] & 0xff) << 8; h1 += ((t0 >>> 13) | (t1 << 3)) & 0x1fff; - t2 = m[mpos+ 4] & 0xff | (m[mpos+ 5] & 0xff) << 8; h2 += ((t1 >>> 10) | (t2 << 6)) & 0x1fff; - t3 = m[mpos+ 6] & 0xff | (m[mpos+ 7] & 0xff) << 8; h3 += ((t2 >>> 7) | (t3 << 9)) & 0x1fff; - t4 = m[mpos+ 8] & 0xff | (m[mpos+ 9] & 0xff) << 8; h4 += ((t3 >>> 4) | (t4 << 12)) & 0x1fff; - h5 += ((t4 >>> 1)) & 0x1fff; - t5 = m[mpos+10] & 0xff | (m[mpos+11] & 0xff) << 8; h6 += ((t4 >>> 14) | (t5 << 2)) & 0x1fff; - t6 = m[mpos+12] & 0xff | (m[mpos+13] & 0xff) << 8; h7 += ((t5 >>> 11) | (t6 << 5)) & 0x1fff; - t7 = m[mpos+14] & 0xff | (m[mpos+15] & 0xff) << 8; h8 += ((t6 >>> 8) | (t7 << 8)) & 0x1fff; - h9 += ((t7 >>> 5)) | hibit; + while (bytes >= 16) { + t0 = m[mpos + 0] & 0xff | (m[mpos + 1] & 0xff) << 8; h0 += (t0) & 0x1fff; + t1 = m[mpos + 2] & 0xff | (m[mpos + 3] & 0xff) << 8; h1 += ((t0 >>> 13) | (t1 << 3)) & 0x1fff; + t2 = m[mpos + 4] & 0xff | (m[mpos + 5] & 0xff) << 8; h2 += ((t1 >>> 10) | (t2 << 6)) & 0x1fff; + t3 = m[mpos + 6] & 0xff | (m[mpos + 7] & 0xff) << 8; h3 += ((t2 >>> 7) | (t3 << 9)) & 0x1fff; + t4 = m[mpos + 8] & 0xff | (m[mpos + 9] & 0xff) << 8; h4 += ((t3 >>> 4) | (t4 << 12)) & 0x1fff; + h5 += ((t4 >>> 1)) & 0x1fff; + t5 = m[mpos + 10] & 0xff | (m[mpos + 11] & 0xff) << 8; h6 += ((t4 >>> 14) | (t5 << 2)) & 0x1fff; + t6 = m[mpos + 12] & 0xff | (m[mpos + 13] & 0xff) << 8; h7 += ((t5 >>> 11) | (t6 << 5)) & 0x1fff; + t7 = m[mpos + 14] & 0xff | (m[mpos + 15] & 0xff) << 8; h8 += ((t6 >>> 8) | (t7 << 8)) & 0x1fff; + h9 += ((t7 >>> 5)) | hibit; - c = 0; + c = 0; - d0 = c; - d0 += h0 * r0; - d0 += h1 * (5 * r9); - d0 += h2 * (5 * r8); - d0 += h3 * (5 * r7); - d0 += h4 * (5 * r6); - c = (d0 >>> 13); d0 &= 0x1fff; - d0 += h5 * (5 * r5); - d0 += h6 * (5 * r4); - d0 += h7 * (5 * r3); - d0 += h8 * (5 * r2); - d0 += h9 * (5 * r1); - c += (d0 >>> 13); d0 &= 0x1fff; + d0 = c; + d0 += h0 * r0; + d0 += h1 * (5 * r9); + d0 += h2 * (5 * r8); + d0 += h3 * (5 * r7); + d0 += h4 * (5 * r6); + c = (d0 >>> 13); d0 &= 0x1fff; + d0 += h5 * (5 * r5); + d0 += h6 * (5 * r4); + d0 += h7 * (5 * r3); + d0 += h8 * (5 * r2); + d0 += h9 * (5 * r1); + c += (d0 >>> 13); d0 &= 0x1fff; - d1 = c; - d1 += h0 * r1; - d1 += h1 * r0; - d1 += h2 * (5 * r9); - d1 += h3 * (5 * r8); - d1 += h4 * (5 * r7); - c = (d1 >>> 13); d1 &= 0x1fff; - d1 += h5 * (5 * r6); - d1 += h6 * (5 * r5); - d1 += h7 * (5 * r4); - d1 += h8 * (5 * r3); - d1 += h9 * (5 * r2); - c += (d1 >>> 13); d1 &= 0x1fff; + d1 = c; + d1 += h0 * r1; + d1 += h1 * r0; + d1 += h2 * (5 * r9); + d1 += h3 * (5 * r8); + d1 += h4 * (5 * r7); + c = (d1 >>> 13); d1 &= 0x1fff; + d1 += h5 * (5 * r6); + d1 += h6 * (5 * r5); + d1 += h7 * (5 * r4); + d1 += h8 * (5 * r3); + d1 += h9 * (5 * r2); + c += (d1 >>> 13); d1 &= 0x1fff; - d2 = c; - d2 += h0 * r2; - d2 += h1 * r1; - d2 += h2 * r0; - d2 += h3 * (5 * r9); - d2 += h4 * (5 * r8); - c = (d2 >>> 13); d2 &= 0x1fff; - d2 += h5 * (5 * r7); - d2 += h6 * (5 * r6); - d2 += h7 * (5 * r5); - d2 += h8 * (5 * r4); - d2 += h9 * (5 * r3); - c += (d2 >>> 13); d2 &= 0x1fff; + d2 = c; + d2 += h0 * r2; + d2 += h1 * r1; + d2 += h2 * r0; + d2 += h3 * (5 * r9); + d2 += h4 * (5 * r8); + c = (d2 >>> 13); d2 &= 0x1fff; + d2 += h5 * (5 * r7); + d2 += h6 * (5 * r6); + d2 += h7 * (5 * r5); + d2 += h8 * (5 * r4); + d2 += h9 * (5 * r3); + c += (d2 >>> 13); d2 &= 0x1fff; - d3 = c; - d3 += h0 * r3; - d3 += h1 * r2; - d3 += h2 * r1; - d3 += h3 * r0; - d3 += h4 * (5 * r9); - c = (d3 >>> 13); d3 &= 0x1fff; - d3 += h5 * (5 * r8); - d3 += h6 * (5 * r7); - d3 += h7 * (5 * r6); - d3 += h8 * (5 * r5); - d3 += h9 * (5 * r4); - c += (d3 >>> 13); d3 &= 0x1fff; + d3 = c; + d3 += h0 * r3; + d3 += h1 * r2; + d3 += h2 * r1; + d3 += h3 * r0; + d3 += h4 * (5 * r9); + c = (d3 >>> 13); d3 &= 0x1fff; + d3 += h5 * (5 * r8); + d3 += h6 * (5 * r7); + d3 += h7 * (5 * r6); + d3 += h8 * (5 * r5); + d3 += h9 * (5 * r4); + c += (d3 >>> 13); d3 &= 0x1fff; - d4 = c; - d4 += h0 * r4; - d4 += h1 * r3; - d4 += h2 * r2; - d4 += h3 * r1; - d4 += h4 * r0; - c = (d4 >>> 13); d4 &= 0x1fff; - d4 += h5 * (5 * r9); - d4 += h6 * (5 * r8); - d4 += h7 * (5 * r7); - d4 += h8 * (5 * r6); - d4 += h9 * (5 * r5); - c += (d4 >>> 13); d4 &= 0x1fff; + d4 = c; + d4 += h0 * r4; + d4 += h1 * r3; + d4 += h2 * r2; + d4 += h3 * r1; + d4 += h4 * r0; + c = (d4 >>> 13); d4 &= 0x1fff; + d4 += h5 * (5 * r9); + d4 += h6 * (5 * r8); + d4 += h7 * (5 * r7); + d4 += h8 * (5 * r6); + d4 += h9 * (5 * r5); + c += (d4 >>> 13); d4 &= 0x1fff; - d5 = c; - d5 += h0 * r5; - d5 += h1 * r4; - d5 += h2 * r3; - d5 += h3 * r2; - d5 += h4 * r1; - c = (d5 >>> 13); d5 &= 0x1fff; - d5 += h5 * r0; - d5 += h6 * (5 * r9); - d5 += h7 * (5 * r8); - d5 += h8 * (5 * r7); - d5 += h9 * (5 * r6); - c += (d5 >>> 13); d5 &= 0x1fff; + d5 = c; + d5 += h0 * r5; + d5 += h1 * r4; + d5 += h2 * r3; + d5 += h3 * r2; + d5 += h4 * r1; + c = (d5 >>> 13); d5 &= 0x1fff; + d5 += h5 * r0; + d5 += h6 * (5 * r9); + d5 += h7 * (5 * r8); + d5 += h8 * (5 * r7); + d5 += h9 * (5 * r6); + c += (d5 >>> 13); d5 &= 0x1fff; - d6 = c; - d6 += h0 * r6; - d6 += h1 * r5; - d6 += h2 * r4; - d6 += h3 * r3; - d6 += h4 * r2; - c = (d6 >>> 13); d6 &= 0x1fff; - d6 += h5 * r1; - d6 += h6 * r0; - d6 += h7 * (5 * r9); - d6 += h8 * (5 * r8); - d6 += h9 * (5 * r7); - c += (d6 >>> 13); d6 &= 0x1fff; + d6 = c; + d6 += h0 * r6; + d6 += h1 * r5; + d6 += h2 * r4; + d6 += h3 * r3; + d6 += h4 * r2; + c = (d6 >>> 13); d6 &= 0x1fff; + d6 += h5 * r1; + d6 += h6 * r0; + d6 += h7 * (5 * r9); + d6 += h8 * (5 * r8); + d6 += h9 * (5 * r7); + c += (d6 >>> 13); d6 &= 0x1fff; - d7 = c; - d7 += h0 * r7; - d7 += h1 * r6; - d7 += h2 * r5; - d7 += h3 * r4; - d7 += h4 * r3; - c = (d7 >>> 13); d7 &= 0x1fff; - d7 += h5 * r2; - d7 += h6 * r1; - d7 += h7 * r0; - d7 += h8 * (5 * r9); - d7 += h9 * (5 * r8); - c += (d7 >>> 13); d7 &= 0x1fff; + d7 = c; + d7 += h0 * r7; + d7 += h1 * r6; + d7 += h2 * r5; + d7 += h3 * r4; + d7 += h4 * r3; + c = (d7 >>> 13); d7 &= 0x1fff; + d7 += h5 * r2; + d7 += h6 * r1; + d7 += h7 * r0; + d7 += h8 * (5 * r9); + d7 += h9 * (5 * r8); + c += (d7 >>> 13); d7 &= 0x1fff; - d8 = c; - d8 += h0 * r8; - d8 += h1 * r7; - d8 += h2 * r6; - d8 += h3 * r5; - d8 += h4 * r4; - c = (d8 >>> 13); d8 &= 0x1fff; - d8 += h5 * r3; - d8 += h6 * r2; - d8 += h7 * r1; - d8 += h8 * r0; - d8 += h9 * (5 * r9); - c += (d8 >>> 13); d8 &= 0x1fff; + d8 = c; + d8 += h0 * r8; + d8 += h1 * r7; + d8 += h2 * r6; + d8 += h3 * r5; + d8 += h4 * r4; + c = (d8 >>> 13); d8 &= 0x1fff; + d8 += h5 * r3; + d8 += h6 * r2; + d8 += h7 * r1; + d8 += h8 * r0; + d8 += h9 * (5 * r9); + c += (d8 >>> 13); d8 &= 0x1fff; - d9 = c; - d9 += h0 * r9; - d9 += h1 * r8; - d9 += h2 * r7; - d9 += h3 * r6; - d9 += h4 * r5; - c = (d9 >>> 13); d9 &= 0x1fff; - d9 += h5 * r4; - d9 += h6 * r3; - d9 += h7 * r2; - d9 += h8 * r1; - d9 += h9 * r0; - c += (d9 >>> 13); d9 &= 0x1fff; + d9 = c; + d9 += h0 * r9; + d9 += h1 * r8; + d9 += h2 * r7; + d9 += h3 * r6; + d9 += h4 * r5; + c = (d9 >>> 13); d9 &= 0x1fff; + d9 += h5 * r4; + d9 += h6 * r3; + d9 += h7 * r2; + d9 += h8 * r1; + d9 += h9 * r0; + c += (d9 >>> 13); d9 &= 0x1fff; - c = (((c << 2) + c)) | 0; - c = (c + d0) | 0; - d0 = c & 0x1fff; - c = (c >>> 13); - d1 += c; + c = (((c << 2) + c)) | 0; + c = (c + d0) | 0; + d0 = c & 0x1fff; + c = (c >>> 13); + d1 += c; - h0 = d0; - h1 = d1; - h2 = d2; - h3 = d3; - h4 = d4; - h5 = d5; - h6 = d6; - h7 = d7; - h8 = d8; - h9 = d9; + h0 = d0; + h1 = d1; + h2 = d2; + h3 = d3; + h4 = d4; + h5 = d5; + h6 = d6; + h7 = d7; + h8 = d8; + h9 = d9; - mpos += 16; - bytes -= 16; - } - this.h[0] = h0; - this.h[1] = h1; - this.h[2] = h2; - this.h[3] = h3; - this.h[4] = h4; - this.h[5] = h5; - this.h[6] = h6; - this.h[7] = h7; - this.h[8] = h8; - this.h[9] = h9; + mpos += 16; + bytes -= 16; + } + this.h[0] = h0; + this.h[1] = h1; + this.h[2] = h2; + this.h[3] = h3; + this.h[4] = h4; + this.h[5] = h5; + this.h[6] = h6; + this.h[7] = h7; + this.h[8] = h8; + this.h[9] = h9; }; -poly1305.prototype.finish = function(mac, macpos) { - var g = new Uint16Array(10); - var c, mask, f, i; +poly1305.prototype.finish = function (mac, macpos) { + var g = new Uint16Array(10); + var c, mask, f, i; - if (this.leftover) { - i = this.leftover; - this.buffer[i++] = 1; - for (; i < 16; i++) this.buffer[i] = 0; - this.fin = 1; - this.blocks(this.buffer, 0, 16); - } + if (this.leftover) { + i = this.leftover; + this.buffer[i++] = 1; + for (; i < 16; i++) this.buffer[i] = 0; + this.fin = 1; + this.blocks(this.buffer, 0, 16); + } - c = this.h[1] >>> 13; - this.h[1] &= 0x1fff; - for (i = 2; i < 10; i++) { - this.h[i] += c; - c = this.h[i] >>> 13; - this.h[i] &= 0x1fff; - } - this.h[0] += (c * 5); - c = this.h[0] >>> 13; - this.h[0] &= 0x1fff; - this.h[1] += c; - c = this.h[1] >>> 13; - this.h[1] &= 0x1fff; - this.h[2] += c; + c = this.h[1] >>> 13; + this.h[1] &= 0x1fff; + for (i = 2; i < 10; i++) { + this.h[i] += c; + c = this.h[i] >>> 13; + this.h[i] &= 0x1fff; + } + this.h[0] += (c * 5); + c = this.h[0] >>> 13; + this.h[0] &= 0x1fff; + this.h[1] += c; + c = this.h[1] >>> 13; + this.h[1] &= 0x1fff; + this.h[2] += c; - g[0] = this.h[0] + 5; - c = g[0] >>> 13; - g[0] &= 0x1fff; - for (i = 1; i < 10; i++) { - g[i] = this.h[i] + c; - c = g[i] >>> 13; - g[i] &= 0x1fff; - } - g[9] -= (1 << 13); + g[0] = this.h[0] + 5; + c = g[0] >>> 13; + g[0] &= 0x1fff; + for (i = 1; i < 10; i++) { + g[i] = this.h[i] + c; + c = g[i] >>> 13; + g[i] &= 0x1fff; + } + g[9] -= (1 << 13); - mask = (g[9] >>> ((2 * 8) - 1)) - 1; - for (i = 0; i < 10; i++) g[i] &= mask; - mask = ~mask; - for (i = 0; i < 10; i++) this.h[i] = (this.h[i] & mask) | g[i]; + mask = (g[9] >>> ((2 * 8) - 1)) - 1; + for (i = 0; i < 10; i++) g[i] &= mask; + mask = ~mask; + for (i = 0; i < 10; i++) this.h[i] = (this.h[i] & mask) | g[i]; - this.h[0] = ((this.h[0] ) | (this.h[1] << 13) ) & 0xffff; - this.h[1] = ((this.h[1] >>> 3) | (this.h[2] << 10) ) & 0xffff; - this.h[2] = ((this.h[2] >>> 6) | (this.h[3] << 7) ) & 0xffff; - this.h[3] = ((this.h[3] >>> 9) | (this.h[4] << 4) ) & 0xffff; - this.h[4] = ((this.h[4] >>> 12) | (this.h[5] << 1) | (this.h[6] << 14)) & 0xffff; - this.h[5] = ((this.h[6] >>> 2) | (this.h[7] << 11) ) & 0xffff; - this.h[6] = ((this.h[7] >>> 5) | (this.h[8] << 8) ) & 0xffff; - this.h[7] = ((this.h[8] >>> 8) | (this.h[9] << 5) ) & 0xffff; + this.h[0] = ((this.h[0]) | (this.h[1] << 13)) & 0xffff; + this.h[1] = ((this.h[1] >>> 3) | (this.h[2] << 10)) & 0xffff; + this.h[2] = ((this.h[2] >>> 6) | (this.h[3] << 7)) & 0xffff; + this.h[3] = ((this.h[3] >>> 9) | (this.h[4] << 4)) & 0xffff; + this.h[4] = ((this.h[4] >>> 12) | (this.h[5] << 1) | (this.h[6] << 14)) & 0xffff; + this.h[5] = ((this.h[6] >>> 2) | (this.h[7] << 11)) & 0xffff; + this.h[6] = ((this.h[7] >>> 5) | (this.h[8] << 8)) & 0xffff; + this.h[7] = ((this.h[8] >>> 8) | (this.h[9] << 5)) & 0xffff; - f = this.h[0] + this.pad[0]; - this.h[0] = f & 0xffff; - for (i = 1; i < 8; i++) { - f = (((this.h[i] + this.pad[i]) | 0) + (f >>> 16)) | 0; - this.h[i] = f & 0xffff; - } + f = this.h[0] + this.pad[0]; + this.h[0] = f & 0xffff; + for (i = 1; i < 8; i++) { + f = (((this.h[i] + this.pad[i]) | 0) + (f >>> 16)) | 0; + this.h[i] = f & 0xffff; + } - mac[macpos+ 0] = (this.h[0] >>> 0) & 0xff; - mac[macpos+ 1] = (this.h[0] >>> 8) & 0xff; - mac[macpos+ 2] = (this.h[1] >>> 0) & 0xff; - mac[macpos+ 3] = (this.h[1] >>> 8) & 0xff; - mac[macpos+ 4] = (this.h[2] >>> 0) & 0xff; - mac[macpos+ 5] = (this.h[2] >>> 8) & 0xff; - mac[macpos+ 6] = (this.h[3] >>> 0) & 0xff; - mac[macpos+ 7] = (this.h[3] >>> 8) & 0xff; - mac[macpos+ 8] = (this.h[4] >>> 0) & 0xff; - mac[macpos+ 9] = (this.h[4] >>> 8) & 0xff; - mac[macpos+10] = (this.h[5] >>> 0) & 0xff; - mac[macpos+11] = (this.h[5] >>> 8) & 0xff; - mac[macpos+12] = (this.h[6] >>> 0) & 0xff; - mac[macpos+13] = (this.h[6] >>> 8) & 0xff; - mac[macpos+14] = (this.h[7] >>> 0) & 0xff; - mac[macpos+15] = (this.h[7] >>> 8) & 0xff; + mac[macpos + 0] = (this.h[0] >>> 0) & 0xff; + mac[macpos + 1] = (this.h[0] >>> 8) & 0xff; + mac[macpos + 2] = (this.h[1] >>> 0) & 0xff; + mac[macpos + 3] = (this.h[1] >>> 8) & 0xff; + mac[macpos + 4] = (this.h[2] >>> 0) & 0xff; + mac[macpos + 5] = (this.h[2] >>> 8) & 0xff; + mac[macpos + 6] = (this.h[3] >>> 0) & 0xff; + mac[macpos + 7] = (this.h[3] >>> 8) & 0xff; + mac[macpos + 8] = (this.h[4] >>> 0) & 0xff; + mac[macpos + 9] = (this.h[4] >>> 8) & 0xff; + mac[macpos + 10] = (this.h[5] >>> 0) & 0xff; + mac[macpos + 11] = (this.h[5] >>> 8) & 0xff; + mac[macpos + 12] = (this.h[6] >>> 0) & 0xff; + mac[macpos + 13] = (this.h[6] >>> 8) & 0xff; + mac[macpos + 14] = (this.h[7] >>> 0) & 0xff; + mac[macpos + 15] = (this.h[7] >>> 8) & 0xff; }; -poly1305.prototype.update = function(m, mpos, bytes) { - var i, want; +poly1305.prototype.update = function (m, mpos, bytes) { + var i, want; - if (this.leftover) { - want = (16 - this.leftover); - if (want > bytes) - want = bytes; - for (i = 0; i < want; i++) - this.buffer[this.leftover + i] = m[mpos+i]; - bytes -= want; - mpos += want; - this.leftover += want; - if (this.leftover < 16) - return; - this.blocks(this.buffer, 0, 16); - this.leftover = 0; - } + if (this.leftover) { + want = (16 - this.leftover); + if (want > bytes) + want = bytes; + for (i = 0; i < want; i++) + this.buffer[this.leftover + i] = m[mpos + i]; + bytes -= want; + mpos += want; + this.leftover += want; + if (this.leftover < 16) + return; + this.blocks(this.buffer, 0, 16); + this.leftover = 0; + } - if (bytes >= 16) { - want = bytes - (bytes % 16); - this.blocks(m, mpos, want); - mpos += want; - bytes -= want; - } + if (bytes >= 16) { + want = bytes - (bytes % 16); + this.blocks(m, mpos, want); + mpos += want; + bytes -= want; + } - if (bytes) { - for (i = 0; i < bytes; i++) - this.buffer[this.leftover + i] = m[mpos+i]; - this.leftover += bytes; - } + if (bytes) { + for (i = 0; i < bytes; i++) + this.buffer[this.leftover + i] = m[mpos + i]; + this.leftover += bytes; + } }; function crypto_onetimeauth(out, outpos, m, mpos, n, k) { - var s = new poly1305(k); - s.update(m, mpos, n); - s.finish(out, outpos); - return 0; + var s = new poly1305(k); + s.update(m, mpos, n); + s.finish(out, outpos); + return 0; } function crypto_onetimeauth_verify(h, hpos, m, mpos, n, k) { - var x = new Uint8Array(16); - crypto_onetimeauth(x,0,m,mpos,n,k); - return crypto_verify_16(h,hpos,x,0); + var x = new Uint8Array(16); + crypto_onetimeauth(x, 0, m, mpos, n, k); + return crypto_verify_16(h, hpos, x, 0); } -function crypto_secretbox(c,m,d,n,k) { - var i; - if (d < 32) return -1; - crypto_stream_xor(c,0,m,0,d,n,k); - crypto_onetimeauth(c, 16, c, 32, d - 32, c); - for (i = 0; i < 16; i++) c[i] = 0; - return 0; +function crypto_secretbox(c, m, d, n, k) { + var i; + if (d < 32) return -1; + crypto_stream_xor(c, 0, m, 0, d, n, k); + crypto_onetimeauth(c, 16, c, 32, d - 32, c); + for (i = 0; i < 16; i++) c[i] = 0; + return 0; } -function crypto_secretbox_open(m,c,d,n,k) { - var i; - var x = new Uint8Array(32); - if (d < 32) return -1; - crypto_stream(x,0,32,n,k); - if (crypto_onetimeauth_verify(c, 16,c, 32,d - 32,x) !== 0) return -1; - crypto_stream_xor(m,0,c,0,d,n,k); - for (i = 0; i < 32; i++) m[i] = 0; - return 0; +function crypto_secretbox_open(m, c, d, n, k) { + var i; + var x = new Uint8Array(32); + if (d < 32) return -1; + crypto_stream(x, 0, 32, n, k); + if (crypto_onetimeauth_verify(c, 16, c, 32, d - 32, x) !== 0) return -1; + crypto_stream_xor(m, 0, c, 0, d, n, k); + for (i = 0; i < 32; i++) m[i] = 0; + return 0; } function set25519(r, a) { - var i; - for (i = 0; i < 16; i++) r[i] = a[i]|0; + var i; + for (i = 0; i < 16; i++) r[i] = a[i] | 0; } function car25519(o) { - var i, v, c = 1; - for (i = 0; i < 16; i++) { - v = o[i] + c + 65535; - c = Math.floor(v / 65536); - o[i] = v - c * 65536; - } - o[0] += c-1 + 37 * (c-1); + var i, v, c = 1; + for (i = 0; i < 16; i++) { + v = o[i] + c + 65535; + c = Math.floor(v / 65536); + o[i] = v - c * 65536; + } + o[0] += c - 1 + 37 * (c - 1); } function sel25519(p, q, b) { - var t, c = ~(b-1); - for (var i = 0; i < 16; i++) { - t = c & (p[i] ^ q[i]); - p[i] ^= t; - q[i] ^= t; - } + var t, c = ~(b - 1); + for (var i = 0; i < 16; i++) { + t = c & (p[i] ^ q[i]); + p[i] ^= t; + q[i] ^= t; + } } function pack25519(o, n) { - var i, j, b; - var m = gf(), t = gf(); - for (i = 0; i < 16; i++) t[i] = n[i]; - car25519(t); - car25519(t); - car25519(t); - for (j = 0; j < 2; j++) { - m[0] = t[0] - 0xffed; - for (i = 1; i < 15; i++) { - m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1); - m[i-1] &= 0xffff; - } - m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1); - b = (m[15]>>16) & 1; - m[14] &= 0xffff; - sel25519(t, m, 1-b); - } - for (i = 0; i < 16; i++) { - o[2*i] = t[i] & 0xff; - o[2*i+1] = t[i]>>8; - } + var i, j, b; + var m = gf(), t = gf(); + for (i = 0; i < 16; i++) t[i] = n[i]; + car25519(t); + car25519(t); + car25519(t); + for (j = 0; j < 2; j++) { + m[0] = t[0] - 0xffed; + for (i = 1; i < 15; i++) { + m[i] = t[i] - 0xffff - ((m[i - 1] >> 16) & 1); + m[i - 1] &= 0xffff; + } + m[15] = t[15] - 0x7fff - ((m[14] >> 16) & 1); + b = (m[15] >> 16) & 1; + m[14] &= 0xffff; + sel25519(t, m, 1 - b); + } + for (i = 0; i < 16; i++) { + o[2 * i] = t[i] & 0xff; + o[2 * i + 1] = t[i] >> 8; + } } function neq25519(a, b) { - var c = new Uint8Array(32), d = new Uint8Array(32); - pack25519(c, a); - pack25519(d, b); - return crypto_verify_32(c, 0, d, 0); + var c = new Uint8Array(32), d = new Uint8Array(32); + pack25519(c, a); + pack25519(d, b); + return crypto_verify_32(c, 0, d, 0); } function par25519(a) { - var d = new Uint8Array(32); - pack25519(d, a); - return d[0] & 1; + var d = new Uint8Array(32); + pack25519(d, a); + return d[0] & 1; } function unpack25519(o, n) { - var i; - for (i = 0; i < 16; i++) o[i] = n[2*i] + (n[2*i+1] << 8); - o[15] &= 0x7fff; + var i; + for (i = 0; i < 16; i++) o[i] = n[2 * i] + (n[2 * i + 1] << 8); + o[15] &= 0x7fff; } function A(o, a, b) { - for (var i = 0; i < 16; i++) o[i] = a[i] + b[i]; + for (var i = 0; i < 16; i++) o[i] = a[i] + b[i]; } function Z(o, a, b) { - for (var i = 0; i < 16; i++) o[i] = a[i] - b[i]; + for (var i = 0; i < 16; i++) o[i] = a[i] - b[i]; } function M(o, a, b) { - var v, c, - t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, - t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0, - t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0, - t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0, - b0 = b[0], - b1 = b[1], - b2 = b[2], - b3 = b[3], - b4 = b[4], - b5 = b[5], - b6 = b[6], - b7 = b[7], - b8 = b[8], - b9 = b[9], - b10 = b[10], - b11 = b[11], - b12 = b[12], - b13 = b[13], - b14 = b[14], - b15 = b[15]; + var v, c, + t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, + t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0, + t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0, + t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0, + b0 = b[0], + b1 = b[1], + b2 = b[2], + b3 = b[3], + b4 = b[4], + b5 = b[5], + b6 = b[6], + b7 = b[7], + b8 = b[8], + b9 = b[9], + b10 = b[10], + b11 = b[11], + b12 = b[12], + b13 = b[13], + b14 = b[14], + b15 = b[15]; - v = a[0]; - t0 += v * b0; - t1 += v * b1; - t2 += v * b2; - t3 += v * b3; - t4 += v * b4; - t5 += v * b5; - t6 += v * b6; - t7 += v * b7; - t8 += v * b8; - t9 += v * b9; - t10 += v * b10; - t11 += v * b11; - t12 += v * b12; - t13 += v * b13; - t14 += v * b14; - t15 += v * b15; - v = a[1]; - t1 += v * b0; - t2 += v * b1; - t3 += v * b2; - t4 += v * b3; - t5 += v * b4; - t6 += v * b5; - t7 += v * b6; - t8 += v * b7; - t9 += v * b8; - t10 += v * b9; - t11 += v * b10; - t12 += v * b11; - t13 += v * b12; - t14 += v * b13; - t15 += v * b14; - t16 += v * b15; - v = a[2]; - t2 += v * b0; - t3 += v * b1; - t4 += v * b2; - t5 += v * b3; - t6 += v * b4; - t7 += v * b5; - t8 += v * b6; - t9 += v * b7; - t10 += v * b8; - t11 += v * b9; - t12 += v * b10; - t13 += v * b11; - t14 += v * b12; - t15 += v * b13; - t16 += v * b14; - t17 += v * b15; - v = a[3]; - t3 += v * b0; - t4 += v * b1; - t5 += v * b2; - t6 += v * b3; - t7 += v * b4; - t8 += v * b5; - t9 += v * b6; - t10 += v * b7; - t11 += v * b8; - t12 += v * b9; - t13 += v * b10; - t14 += v * b11; - t15 += v * b12; - t16 += v * b13; - t17 += v * b14; - t18 += v * b15; - v = a[4]; - t4 += v * b0; - t5 += v * b1; - t6 += v * b2; - t7 += v * b3; - t8 += v * b4; - t9 += v * b5; - t10 += v * b6; - t11 += v * b7; - t12 += v * b8; - t13 += v * b9; - t14 += v * b10; - t15 += v * b11; - t16 += v * b12; - t17 += v * b13; - t18 += v * b14; - t19 += v * b15; - v = a[5]; - t5 += v * b0; - t6 += v * b1; - t7 += v * b2; - t8 += v * b3; - t9 += v * b4; - t10 += v * b5; - t11 += v * b6; - t12 += v * b7; - t13 += v * b8; - t14 += v * b9; - t15 += v * b10; - t16 += v * b11; - t17 += v * b12; - t18 += v * b13; - t19 += v * b14; - t20 += v * b15; - v = a[6]; - t6 += v * b0; - t7 += v * b1; - t8 += v * b2; - t9 += v * b3; - t10 += v * b4; - t11 += v * b5; - t12 += v * b6; - t13 += v * b7; - t14 += v * b8; - t15 += v * b9; - t16 += v * b10; - t17 += v * b11; - t18 += v * b12; - t19 += v * b13; - t20 += v * b14; - t21 += v * b15; - v = a[7]; - t7 += v * b0; - t8 += v * b1; - t9 += v * b2; - t10 += v * b3; - t11 += v * b4; - t12 += v * b5; - t13 += v * b6; - t14 += v * b7; - t15 += v * b8; - t16 += v * b9; - t17 += v * b10; - t18 += v * b11; - t19 += v * b12; - t20 += v * b13; - t21 += v * b14; - t22 += v * b15; - v = a[8]; - t8 += v * b0; - t9 += v * b1; - t10 += v * b2; - t11 += v * b3; - t12 += v * b4; - t13 += v * b5; - t14 += v * b6; - t15 += v * b7; - t16 += v * b8; - t17 += v * b9; - t18 += v * b10; - t19 += v * b11; - t20 += v * b12; - t21 += v * b13; - t22 += v * b14; - t23 += v * b15; - v = a[9]; - t9 += v * b0; - t10 += v * b1; - t11 += v * b2; - t12 += v * b3; - t13 += v * b4; - t14 += v * b5; - t15 += v * b6; - t16 += v * b7; - t17 += v * b8; - t18 += v * b9; - t19 += v * b10; - t20 += v * b11; - t21 += v * b12; - t22 += v * b13; - t23 += v * b14; - t24 += v * b15; - v = a[10]; - t10 += v * b0; - t11 += v * b1; - t12 += v * b2; - t13 += v * b3; - t14 += v * b4; - t15 += v * b5; - t16 += v * b6; - t17 += v * b7; - t18 += v * b8; - t19 += v * b9; - t20 += v * b10; - t21 += v * b11; - t22 += v * b12; - t23 += v * b13; - t24 += v * b14; - t25 += v * b15; - v = a[11]; - t11 += v * b0; - t12 += v * b1; - t13 += v * b2; - t14 += v * b3; - t15 += v * b4; - t16 += v * b5; - t17 += v * b6; - t18 += v * b7; - t19 += v * b8; - t20 += v * b9; - t21 += v * b10; - t22 += v * b11; - t23 += v * b12; - t24 += v * b13; - t25 += v * b14; - t26 += v * b15; - v = a[12]; - t12 += v * b0; - t13 += v * b1; - t14 += v * b2; - t15 += v * b3; - t16 += v * b4; - t17 += v * b5; - t18 += v * b6; - t19 += v * b7; - t20 += v * b8; - t21 += v * b9; - t22 += v * b10; - t23 += v * b11; - t24 += v * b12; - t25 += v * b13; - t26 += v * b14; - t27 += v * b15; - v = a[13]; - t13 += v * b0; - t14 += v * b1; - t15 += v * b2; - t16 += v * b3; - t17 += v * b4; - t18 += v * b5; - t19 += v * b6; - t20 += v * b7; - t21 += v * b8; - t22 += v * b9; - t23 += v * b10; - t24 += v * b11; - t25 += v * b12; - t26 += v * b13; - t27 += v * b14; - t28 += v * b15; - v = a[14]; - t14 += v * b0; - t15 += v * b1; - t16 += v * b2; - t17 += v * b3; - t18 += v * b4; - t19 += v * b5; - t20 += v * b6; - t21 += v * b7; - t22 += v * b8; - t23 += v * b9; - t24 += v * b10; - t25 += v * b11; - t26 += v * b12; - t27 += v * b13; - t28 += v * b14; - t29 += v * b15; - v = a[15]; - t15 += v * b0; - t16 += v * b1; - t17 += v * b2; - t18 += v * b3; - t19 += v * b4; - t20 += v * b5; - t21 += v * b6; - t22 += v * b7; - t23 += v * b8; - t24 += v * b9; - t25 += v * b10; - t26 += v * b11; - t27 += v * b12; - t28 += v * b13; - t29 += v * b14; - t30 += v * b15; + v = a[0]; + t0 += v * b0; + t1 += v * b1; + t2 += v * b2; + t3 += v * b3; + t4 += v * b4; + t5 += v * b5; + t6 += v * b6; + t7 += v * b7; + t8 += v * b8; + t9 += v * b9; + t10 += v * b10; + t11 += v * b11; + t12 += v * b12; + t13 += v * b13; + t14 += v * b14; + t15 += v * b15; + v = a[1]; + t1 += v * b0; + t2 += v * b1; + t3 += v * b2; + t4 += v * b3; + t5 += v * b4; + t6 += v * b5; + t7 += v * b6; + t8 += v * b7; + t9 += v * b8; + t10 += v * b9; + t11 += v * b10; + t12 += v * b11; + t13 += v * b12; + t14 += v * b13; + t15 += v * b14; + t16 += v * b15; + v = a[2]; + t2 += v * b0; + t3 += v * b1; + t4 += v * b2; + t5 += v * b3; + t6 += v * b4; + t7 += v * b5; + t8 += v * b6; + t9 += v * b7; + t10 += v * b8; + t11 += v * b9; + t12 += v * b10; + t13 += v * b11; + t14 += v * b12; + t15 += v * b13; + t16 += v * b14; + t17 += v * b15; + v = a[3]; + t3 += v * b0; + t4 += v * b1; + t5 += v * b2; + t6 += v * b3; + t7 += v * b4; + t8 += v * b5; + t9 += v * b6; + t10 += v * b7; + t11 += v * b8; + t12 += v * b9; + t13 += v * b10; + t14 += v * b11; + t15 += v * b12; + t16 += v * b13; + t17 += v * b14; + t18 += v * b15; + v = a[4]; + t4 += v * b0; + t5 += v * b1; + t6 += v * b2; + t7 += v * b3; + t8 += v * b4; + t9 += v * b5; + t10 += v * b6; + t11 += v * b7; + t12 += v * b8; + t13 += v * b9; + t14 += v * b10; + t15 += v * b11; + t16 += v * b12; + t17 += v * b13; + t18 += v * b14; + t19 += v * b15; + v = a[5]; + t5 += v * b0; + t6 += v * b1; + t7 += v * b2; + t8 += v * b3; + t9 += v * b4; + t10 += v * b5; + t11 += v * b6; + t12 += v * b7; + t13 += v * b8; + t14 += v * b9; + t15 += v * b10; + t16 += v * b11; + t17 += v * b12; + t18 += v * b13; + t19 += v * b14; + t20 += v * b15; + v = a[6]; + t6 += v * b0; + t7 += v * b1; + t8 += v * b2; + t9 += v * b3; + t10 += v * b4; + t11 += v * b5; + t12 += v * b6; + t13 += v * b7; + t14 += v * b8; + t15 += v * b9; + t16 += v * b10; + t17 += v * b11; + t18 += v * b12; + t19 += v * b13; + t20 += v * b14; + t21 += v * b15; + v = a[7]; + t7 += v * b0; + t8 += v * b1; + t9 += v * b2; + t10 += v * b3; + t11 += v * b4; + t12 += v * b5; + t13 += v * b6; + t14 += v * b7; + t15 += v * b8; + t16 += v * b9; + t17 += v * b10; + t18 += v * b11; + t19 += v * b12; + t20 += v * b13; + t21 += v * b14; + t22 += v * b15; + v = a[8]; + t8 += v * b0; + t9 += v * b1; + t10 += v * b2; + t11 += v * b3; + t12 += v * b4; + t13 += v * b5; + t14 += v * b6; + t15 += v * b7; + t16 += v * b8; + t17 += v * b9; + t18 += v * b10; + t19 += v * b11; + t20 += v * b12; + t21 += v * b13; + t22 += v * b14; + t23 += v * b15; + v = a[9]; + t9 += v * b0; + t10 += v * b1; + t11 += v * b2; + t12 += v * b3; + t13 += v * b4; + t14 += v * b5; + t15 += v * b6; + t16 += v * b7; + t17 += v * b8; + t18 += v * b9; + t19 += v * b10; + t20 += v * b11; + t21 += v * b12; + t22 += v * b13; + t23 += v * b14; + t24 += v * b15; + v = a[10]; + t10 += v * b0; + t11 += v * b1; + t12 += v * b2; + t13 += v * b3; + t14 += v * b4; + t15 += v * b5; + t16 += v * b6; + t17 += v * b7; + t18 += v * b8; + t19 += v * b9; + t20 += v * b10; + t21 += v * b11; + t22 += v * b12; + t23 += v * b13; + t24 += v * b14; + t25 += v * b15; + v = a[11]; + t11 += v * b0; + t12 += v * b1; + t13 += v * b2; + t14 += v * b3; + t15 += v * b4; + t16 += v * b5; + t17 += v * b6; + t18 += v * b7; + t19 += v * b8; + t20 += v * b9; + t21 += v * b10; + t22 += v * b11; + t23 += v * b12; + t24 += v * b13; + t25 += v * b14; + t26 += v * b15; + v = a[12]; + t12 += v * b0; + t13 += v * b1; + t14 += v * b2; + t15 += v * b3; + t16 += v * b4; + t17 += v * b5; + t18 += v * b6; + t19 += v * b7; + t20 += v * b8; + t21 += v * b9; + t22 += v * b10; + t23 += v * b11; + t24 += v * b12; + t25 += v * b13; + t26 += v * b14; + t27 += v * b15; + v = a[13]; + t13 += v * b0; + t14 += v * b1; + t15 += v * b2; + t16 += v * b3; + t17 += v * b4; + t18 += v * b5; + t19 += v * b6; + t20 += v * b7; + t21 += v * b8; + t22 += v * b9; + t23 += v * b10; + t24 += v * b11; + t25 += v * b12; + t26 += v * b13; + t27 += v * b14; + t28 += v * b15; + v = a[14]; + t14 += v * b0; + t15 += v * b1; + t16 += v * b2; + t17 += v * b3; + t18 += v * b4; + t19 += v * b5; + t20 += v * b6; + t21 += v * b7; + t22 += v * b8; + t23 += v * b9; + t24 += v * b10; + t25 += v * b11; + t26 += v * b12; + t27 += v * b13; + t28 += v * b14; + t29 += v * b15; + v = a[15]; + t15 += v * b0; + t16 += v * b1; + t17 += v * b2; + t18 += v * b3; + t19 += v * b4; + t20 += v * b5; + t21 += v * b6; + t22 += v * b7; + t23 += v * b8; + t24 += v * b9; + t25 += v * b10; + t26 += v * b11; + t27 += v * b12; + t28 += v * b13; + t29 += v * b14; + t30 += v * b15; - t0 += 38 * t16; - t1 += 38 * t17; - t2 += 38 * t18; - t3 += 38 * t19; - t4 += 38 * t20; - t5 += 38 * t21; - t6 += 38 * t22; - t7 += 38 * t23; - t8 += 38 * t24; - t9 += 38 * t25; - t10 += 38 * t26; - t11 += 38 * t27; - t12 += 38 * t28; - t13 += 38 * t29; - t14 += 38 * t30; - // t15 left as is + t0 += 38 * t16; + t1 += 38 * t17; + t2 += 38 * t18; + t3 += 38 * t19; + t4 += 38 * t20; + t5 += 38 * t21; + t6 += 38 * t22; + t7 += 38 * t23; + t8 += 38 * t24; + t9 += 38 * t25; + t10 += 38 * t26; + t11 += 38 * t27; + t12 += 38 * t28; + t13 += 38 * t29; + t14 += 38 * t30; + // t15 left as is - // first car - c = 1; - v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; - v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; - v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; - v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; - v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; - v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; - v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; - v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; - v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; - v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; - v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; - v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; - v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; - v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; - v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; - v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; - t0 += c-1 + 37 * (c-1); + // first car + c = 1; + v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; + v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; + v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; + v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; + v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; + v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; + v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; + v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; + v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; + v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; + v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; + v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; + v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; + v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; + v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; + v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; + t0 += c - 1 + 37 * (c - 1); - // second car - c = 1; - v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; - v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; - v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; - v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; - v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; - v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; - v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; - v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; - v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; - v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; - v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; - v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; - v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; - v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; - v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; - v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; - t0 += c-1 + 37 * (c-1); + // second car + c = 1; + v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; + v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; + v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; + v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; + v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; + v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; + v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; + v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; + v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; + v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; + v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; + v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; + v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; + v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; + v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; + v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; + t0 += c - 1 + 37 * (c - 1); - o[ 0] = t0; - o[ 1] = t1; - o[ 2] = t2; - o[ 3] = t3; - o[ 4] = t4; - o[ 5] = t5; - o[ 6] = t6; - o[ 7] = t7; - o[ 8] = t8; - o[ 9] = t9; - o[10] = t10; - o[11] = t11; - o[12] = t12; - o[13] = t13; - o[14] = t14; - o[15] = t15; + o[0] = t0; + o[1] = t1; + o[2] = t2; + o[3] = t3; + o[4] = t4; + o[5] = t5; + o[6] = t6; + o[7] = t7; + o[8] = t8; + o[9] = t9; + o[10] = t10; + o[11] = t11; + o[12] = t12; + o[13] = t13; + o[14] = t14; + o[15] = t15; } function S(o, a) { - M(o, a, a); + M(o, a, a); } function inv25519(o, i) { - var c = gf(); - var a; - for (a = 0; a < 16; a++) c[a] = i[a]; - for (a = 253; a >= 0; a--) { - S(c, c); - if(a !== 2 && a !== 4) M(c, c, i); - } - for (a = 0; a < 16; a++) o[a] = c[a]; + var c = gf(); + var a; + for (a = 0; a < 16; a++) c[a] = i[a]; + for (a = 253; a >= 0; a--) { + S(c, c); + if (a !== 2 && a !== 4) M(c, c, i); + } + for (a = 0; a < 16; a++) o[a] = c[a]; } function pow2523(o, i) { - var c = gf(); - var a; - for (a = 0; a < 16; a++) c[a] = i[a]; - for (a = 250; a >= 0; a--) { - S(c, c); - if(a !== 1) M(c, c, i); - } - for (a = 0; a < 16; a++) o[a] = c[a]; + var c = gf(); + var a; + for (a = 0; a < 16; a++) c[a] = i[a]; + for (a = 250; a >= 0; a--) { + S(c, c); + if (a !== 1) M(c, c, i); + } + for (a = 0; a < 16; a++) o[a] = c[a]; } function crypto_scalarmult(q, n, p) { - var z = new Uint8Array(32); - var x = new Float64Array(80), r, i; - var a = gf(), b = gf(), c = gf(), - d = gf(), e = gf(), f = gf(); - for (i = 0; i < 31; i++) z[i] = n[i]; - z[31]=(n[31]&127)|64; - z[0]&=248; - unpack25519(x,p); - for (i = 0; i < 16; i++) { - b[i]=x[i]; - d[i]=a[i]=c[i]=0; - } - a[0]=d[0]=1; - for (i=254; i>=0; --i) { - r=(z[i>>>3]>>>(i&7))&1; - sel25519(a,b,r); - sel25519(c,d,r); - A(e,a,c); - Z(a,a,c); - A(c,b,d); - Z(b,b,d); - S(d,e); - S(f,a); - M(a,c,a); - M(c,b,e); - A(e,a,c); - Z(a,a,c); - S(b,a); - Z(c,d,f); - M(a,c,_121665); - A(a,a,d); - M(c,c,a); - M(a,d,f); - M(d,b,x); - S(b,e); - sel25519(a,b,r); - sel25519(c,d,r); - } - for (i = 0; i < 16; i++) { - x[i+16]=a[i]; - x[i+32]=c[i]; - x[i+48]=b[i]; - x[i+64]=d[i]; - } - var x32 = x.subarray(32); - var x16 = x.subarray(16); - inv25519(x32,x32); - M(x16,x16,x32); - pack25519(q,x16); - return 0; + var z = new Uint8Array(32); + var x = new Float64Array(80), r, i; + var a = gf(), b = gf(), c = gf(), + d = gf(), e = gf(), f = gf(); + for (i = 0; i < 31; i++) z[i] = n[i]; + z[31] = (n[31] & 127) | 64; + z[0] &= 248; + unpack25519(x, p); + for (i = 0; i < 16; i++) { + b[i] = x[i]; + d[i] = a[i] = c[i] = 0; + } + a[0] = d[0] = 1; + for (i = 254; i >= 0; --i) { + r = (z[i >>> 3] >>> (i & 7)) & 1; + sel25519(a, b, r); + sel25519(c, d, r); + A(e, a, c); + Z(a, a, c); + A(c, b, d); + Z(b, b, d); + S(d, e); + S(f, a); + M(a, c, a); + M(c, b, e); + A(e, a, c); + Z(a, a, c); + S(b, a); + Z(c, d, f); + M(a, c, _121665); + A(a, a, d); + M(c, c, a); + M(a, d, f); + M(d, b, x); + S(b, e); + sel25519(a, b, r); + sel25519(c, d, r); + } + for (i = 0; i < 16; i++) { + x[i + 16] = a[i]; + x[i + 32] = c[i]; + x[i + 48] = b[i]; + x[i + 64] = d[i]; + } + var x32 = x.subarray(32); + var x16 = x.subarray(16); + inv25519(x32, x32); + M(x16, x16, x32); + pack25519(q, x16); + return 0; } function crypto_scalarmult_base(q, n) { - return crypto_scalarmult(q, n, _9); + return crypto_scalarmult(q, n, _9); } function crypto_box_keypair(y, x) { - randombytes(x, 32); - return crypto_scalarmult_base(y, x); + randombytes(x, 32); + return crypto_scalarmult_base(y, x); } function crypto_box_beforenm(k, y, x) { - var s = new Uint8Array(32); - crypto_scalarmult(s, x, y); - return crypto_core_hsalsa20(k, _0, s, sigma); + var s = new Uint8Array(32); + crypto_scalarmult(s, x, y); + return crypto_core_hsalsa20(k, _0, s, sigma); } var crypto_box_afternm = crypto_secretbox; var crypto_box_open_afternm = crypto_secretbox_open; function crypto_box(c, m, d, n, y, x) { - var k = new Uint8Array(32); - crypto_box_beforenm(k, y, x); - return crypto_box_afternm(c, m, d, n, k); + var k = new Uint8Array(32); + crypto_box_beforenm(k, y, x); + return crypto_box_afternm(c, m, d, n, k); } function crypto_box_open(m, c, d, n, y, x) { - var k = new Uint8Array(32); - crypto_box_beforenm(k, y, x); - return crypto_box_open_afternm(m, c, d, n, k); + var k = new Uint8Array(32); + crypto_box_beforenm(k, y, x); + return crypto_box_open_afternm(m, c, d, n, k); } var K = [ - 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, - 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, - 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, - 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, - 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, - 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, - 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, - 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, - 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, - 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, - 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, - 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, - 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, - 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, - 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, - 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, - 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, - 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, - 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, - 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, - 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, - 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, - 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, - 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, - 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, - 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, - 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, - 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, - 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, - 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, - 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, - 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, - 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, - 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, - 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, - 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, - 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, - 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, - 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, - 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 + 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, + 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, + 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, + 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, + 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, + 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, + 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, + 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, + 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, + 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, + 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, + 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, + 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, + 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, + 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, + 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, + 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, + 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, + 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, + 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, + 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, + 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, + 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, + 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, + 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, + 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, + 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, + 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, + 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, + 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, + 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, + 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, + 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, + 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, + 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, + 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, + 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, + 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, + 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, + 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 ]; function crypto_hashblocks_hl(hh, hl, m, n) { - var wh = new Int32Array(16), wl = new Int32Array(16), - bh0, bh1, bh2, bh3, bh4, bh5, bh6, bh7, - bl0, bl1, bl2, bl3, bl4, bl5, bl6, bl7, - th, tl, i, j, h, l, a, b, c, d; - - var ah0 = hh[0], - ah1 = hh[1], - ah2 = hh[2], - ah3 = hh[3], - ah4 = hh[4], - ah5 = hh[5], - ah6 = hh[6], - ah7 = hh[7], - - al0 = hl[0], - al1 = hl[1], - al2 = hl[2], - al3 = hl[3], - al4 = hl[4], - al5 = hl[5], - al6 = hl[6], - al7 = hl[7]; - - var pos = 0; - while (n >= 128) { - for (i = 0; i < 16; i++) { - j = 8 * i + pos; - wh[i] = (m[j+0] << 24) | (m[j+1] << 16) | (m[j+2] << 8) | m[j+3]; - wl[i] = (m[j+4] << 24) | (m[j+5] << 16) | (m[j+6] << 8) | m[j+7]; - } - for (i = 0; i < 80; i++) { - bh0 = ah0; - bh1 = ah1; - bh2 = ah2; - bh3 = ah3; - bh4 = ah4; - bh5 = ah5; - bh6 = ah6; - bh7 = ah7; - - bl0 = al0; - bl1 = al1; - bl2 = al2; - bl3 = al3; - bl4 = al4; - bl5 = al5; - bl6 = al6; - bl7 = al7; - - // add - h = ah7; - l = al7; - - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; - - // Sigma1 - h = ((ah4 >>> 14) | (al4 << (32-14))) ^ ((ah4 >>> 18) | (al4 << (32-18))) ^ ((al4 >>> (41-32)) | (ah4 << (32-(41-32)))); - l = ((al4 >>> 14) | (ah4 << (32-14))) ^ ((al4 >>> 18) | (ah4 << (32-18))) ^ ((ah4 >>> (41-32)) | (al4 << (32-(41-32)))); - - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; - - // Ch - h = (ah4 & ah5) ^ (~ah4 & ah6); - l = (al4 & al5) ^ (~al4 & al6); - - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; - - // K - h = K[i*2]; - l = K[i*2+1]; - - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; - - // w - h = wh[i%16]; - l = wl[i%16]; - - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; - - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; - - th = c & 0xffff | d << 16; - tl = a & 0xffff | b << 16; - - // add - h = th; - l = tl; - - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; - - // Sigma0 - h = ((ah0 >>> 28) | (al0 << (32-28))) ^ ((al0 >>> (34-32)) | (ah0 << (32-(34-32)))) ^ ((al0 >>> (39-32)) | (ah0 << (32-(39-32)))); - l = ((al0 >>> 28) | (ah0 << (32-28))) ^ ((ah0 >>> (34-32)) | (al0 << (32-(34-32)))) ^ ((ah0 >>> (39-32)) | (al0 << (32-(39-32)))); - - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; - - // Maj - h = (ah0 & ah1) ^ (ah0 & ah2) ^ (ah1 & ah2); - l = (al0 & al1) ^ (al0 & al2) ^ (al1 & al2); - - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; - - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; - - bh7 = (c & 0xffff) | (d << 16); - bl7 = (a & 0xffff) | (b << 16); - - // add - h = bh3; - l = bl3; - - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; - - h = th; - l = tl; - - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; + var wh = new Int32Array(16), wl = new Int32Array(16), + bh0, bh1, bh2, bh3, bh4, bh5, bh6, bh7, + bl0, bl1, bl2, bl3, bl4, bl5, bl6, bl7, + th, tl, i, j, h, l, a, b, c, d; + + var ah0 = hh[0], + ah1 = hh[1], + ah2 = hh[2], + ah3 = hh[3], + ah4 = hh[4], + ah5 = hh[5], + ah6 = hh[6], + ah7 = hh[7], + + al0 = hl[0], + al1 = hl[1], + al2 = hl[2], + al3 = hl[3], + al4 = hl[4], + al5 = hl[5], + al6 = hl[6], + al7 = hl[7]; + + var pos = 0; + while (n >= 128) { + for (i = 0; i < 16; i++) { + j = 8 * i + pos; + wh[i] = (m[j + 0] << 24) | (m[j + 1] << 16) | (m[j + 2] << 8) | m[j + 3]; + wl[i] = (m[j + 4] << 24) | (m[j + 5] << 16) | (m[j + 6] << 8) | m[j + 7]; + } + for (i = 0; i < 80; i++) { + bh0 = ah0; + bh1 = ah1; + bh2 = ah2; + bh3 = ah3; + bh4 = ah4; + bh5 = ah5; + bh6 = ah6; + bh7 = ah7; + + bl0 = al0; + bl1 = al1; + bl2 = al2; + bl3 = al3; + bl4 = al4; + bl5 = al5; + bl6 = al6; + bl7 = al7; + + // add + h = ah7; + l = al7; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + // Sigma1 + h = ((ah4 >>> 14) | (al4 << (32 - 14))) ^ ((ah4 >>> 18) | (al4 << (32 - 18))) ^ ((al4 >>> (41 - 32)) | (ah4 << (32 - (41 - 32)))); + l = ((al4 >>> 14) | (ah4 << (32 - 14))) ^ ((al4 >>> 18) | (ah4 << (32 - 18))) ^ ((ah4 >>> (41 - 32)) | (al4 << (32 - (41 - 32)))); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // Ch + h = (ah4 & ah5) ^ (~ah4 & ah6); + l = (al4 & al5) ^ (~al4 & al6); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // K + h = K[i * 2]; + l = K[i * 2 + 1]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // w + h = wh[i % 16]; + l = wl[i % 16]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + th = c & 0xffff | d << 16; + tl = a & 0xffff | b << 16; + + // add + h = th; + l = tl; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + // Sigma0 + h = ((ah0 >>> 28) | (al0 << (32 - 28))) ^ ((al0 >>> (34 - 32)) | (ah0 << (32 - (34 - 32)))) ^ ((al0 >>> (39 - 32)) | (ah0 << (32 - (39 - 32)))); + l = ((al0 >>> 28) | (ah0 << (32 - 28))) ^ ((ah0 >>> (34 - 32)) | (al0 << (32 - (34 - 32)))) ^ ((ah0 >>> (39 - 32)) | (al0 << (32 - (39 - 32)))); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // Maj + h = (ah0 & ah1) ^ (ah0 & ah2) ^ (ah1 & ah2); + l = (al0 & al1) ^ (al0 & al2) ^ (al1 & al2); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + bh7 = (c & 0xffff) | (d << 16); + bl7 = (a & 0xffff) | (b << 16); + + // add + h = bh3; + l = bl3; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = th; + l = tl; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; - bh3 = (c & 0xffff) | (d << 16); - bl3 = (a & 0xffff) | (b << 16); + bh3 = (c & 0xffff) | (d << 16); + bl3 = (a & 0xffff) | (b << 16); - ah1 = bh0; - ah2 = bh1; - ah3 = bh2; - ah4 = bh3; - ah5 = bh4; - ah6 = bh5; - ah7 = bh6; - ah0 = bh7; + ah1 = bh0; + ah2 = bh1; + ah3 = bh2; + ah4 = bh3; + ah5 = bh4; + ah6 = bh5; + ah7 = bh6; + ah0 = bh7; - al1 = bl0; - al2 = bl1; - al3 = bl2; - al4 = bl3; - al5 = bl4; - al6 = bl5; - al7 = bl6; - al0 = bl7; + al1 = bl0; + al2 = bl1; + al3 = bl2; + al4 = bl3; + al5 = bl4; + al6 = bl5; + al7 = bl6; + al0 = bl7; - if (i%16 === 15) { - for (j = 0; j < 16; j++) { - // add - h = wh[j]; - l = wl[j]; + if (i % 16 === 15) { + for (j = 0; j < 16; j++) { + // add + h = wh[j]; + l = wl[j]; - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; - h = wh[(j+9)%16]; - l = wl[(j+9)%16]; + h = wh[(j + 9) % 16]; + l = wl[(j + 9) % 16]; - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - // sigma0 - th = wh[(j+1)%16]; - tl = wl[(j+1)%16]; - h = ((th >>> 1) | (tl << (32-1))) ^ ((th >>> 8) | (tl << (32-8))) ^ (th >>> 7); - l = ((tl >>> 1) | (th << (32-1))) ^ ((tl >>> 8) | (th << (32-8))) ^ ((tl >>> 7) | (th << (32-7))); + // sigma0 + th = wh[(j + 1) % 16]; + tl = wl[(j + 1) % 16]; + h = ((th >>> 1) | (tl << (32 - 1))) ^ ((th >>> 8) | (tl << (32 - 8))) ^ (th >>> 7); + l = ((tl >>> 1) | (th << (32 - 1))) ^ ((tl >>> 8) | (th << (32 - 8))) ^ ((tl >>> 7) | (th << (32 - 7))); - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - // sigma1 - th = wh[(j+14)%16]; - tl = wl[(j+14)%16]; - h = ((th >>> 19) | (tl << (32-19))) ^ ((tl >>> (61-32)) | (th << (32-(61-32)))) ^ (th >>> 6); - l = ((tl >>> 19) | (th << (32-19))) ^ ((th >>> (61-32)) | (tl << (32-(61-32)))) ^ ((tl >>> 6) | (th << (32-6))); + // sigma1 + th = wh[(j + 14) % 16]; + tl = wl[(j + 14) % 16]; + h = ((th >>> 19) | (tl << (32 - 19))) ^ ((tl >>> (61 - 32)) | (th << (32 - (61 - 32)))) ^ (th >>> 6); + l = ((tl >>> 19) | (th << (32 - 19))) ^ ((th >>> (61 - 32)) | (tl << (32 - (61 - 32)))) ^ ((tl >>> 6) | (th << (32 - 6))); - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; - wh[j] = (c & 0xffff) | (d << 16); - wl[j] = (a & 0xffff) | (b << 16); - } - } - } + wh[j] = (c & 0xffff) | (d << 16); + wl[j] = (a & 0xffff) | (b << 16); + } + } + } - // add - h = ah0; - l = al0; + // add + h = ah0; + l = al0; - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; - h = hh[0]; - l = hl[0]; + h = hh[0]; + l = hl[0]; - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; - hh[0] = ah0 = (c & 0xffff) | (d << 16); - hl[0] = al0 = (a & 0xffff) | (b << 16); + hh[0] = ah0 = (c & 0xffff) | (d << 16); + hl[0] = al0 = (a & 0xffff) | (b << 16); - h = ah1; - l = al1; + h = ah1; + l = al1; - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; - h = hh[1]; - l = hl[1]; + h = hh[1]; + l = hl[1]; - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; - hh[1] = ah1 = (c & 0xffff) | (d << 16); - hl[1] = al1 = (a & 0xffff) | (b << 16); + hh[1] = ah1 = (c & 0xffff) | (d << 16); + hl[1] = al1 = (a & 0xffff) | (b << 16); - h = ah2; - l = al2; + h = ah2; + l = al2; - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; - h = hh[2]; - l = hl[2]; + h = hh[2]; + l = hl[2]; - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; - hh[2] = ah2 = (c & 0xffff) | (d << 16); - hl[2] = al2 = (a & 0xffff) | (b << 16); + hh[2] = ah2 = (c & 0xffff) | (d << 16); + hl[2] = al2 = (a & 0xffff) | (b << 16); - h = ah3; - l = al3; + h = ah3; + l = al3; - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; - h = hh[3]; - l = hl[3]; + h = hh[3]; + l = hl[3]; - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; - hh[3] = ah3 = (c & 0xffff) | (d << 16); - hl[3] = al3 = (a & 0xffff) | (b << 16); + hh[3] = ah3 = (c & 0xffff) | (d << 16); + hl[3] = al3 = (a & 0xffff) | (b << 16); - h = ah4; - l = al4; + h = ah4; + l = al4; - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; - h = hh[4]; - l = hl[4]; + h = hh[4]; + l = hl[4]; - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; - hh[4] = ah4 = (c & 0xffff) | (d << 16); - hl[4] = al4 = (a & 0xffff) | (b << 16); + hh[4] = ah4 = (c & 0xffff) | (d << 16); + hl[4] = al4 = (a & 0xffff) | (b << 16); - h = ah5; - l = al5; + h = ah5; + l = al5; - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; - h = hh[5]; - l = hl[5]; + h = hh[5]; + l = hl[5]; - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; - hh[5] = ah5 = (c & 0xffff) | (d << 16); - hl[5] = al5 = (a & 0xffff) | (b << 16); + hh[5] = ah5 = (c & 0xffff) | (d << 16); + hl[5] = al5 = (a & 0xffff) | (b << 16); - h = ah6; - l = al6; + h = ah6; + l = al6; - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; - h = hh[6]; - l = hl[6]; + h = hh[6]; + l = hl[6]; - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; - hh[6] = ah6 = (c & 0xffff) | (d << 16); - hl[6] = al6 = (a & 0xffff) | (b << 16); + hh[6] = ah6 = (c & 0xffff) | (d << 16); + hl[6] = al6 = (a & 0xffff) | (b << 16); - h = ah7; - l = al7; + h = ah7; + l = al7; - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; - h = hh[7]; - l = hl[7]; + h = hh[7]; + l = hl[7]; - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; - hh[7] = ah7 = (c & 0xffff) | (d << 16); - hl[7] = al7 = (a & 0xffff) | (b << 16); + hh[7] = ah7 = (c & 0xffff) | (d << 16); + hl[7] = al7 = (a & 0xffff) | (b << 16); - pos += 128; - n -= 128; - } + pos += 128; + n -= 128; + } - return n; + return n; } function crypto_hash(out, m, n) { - var hh = new Int32Array(8), - hl = new Int32Array(8), - x = new Uint8Array(256), - i, b = n; + var hh = new Int32Array(8), + hl = new Int32Array(8), + x = new Uint8Array(256), + i, b = n; - hh[0] = 0x6a09e667; - hh[1] = 0xbb67ae85; - hh[2] = 0x3c6ef372; - hh[3] = 0xa54ff53a; - hh[4] = 0x510e527f; - hh[5] = 0x9b05688c; - hh[6] = 0x1f83d9ab; - hh[7] = 0x5be0cd19; + hh[0] = 0x6a09e667; + hh[1] = 0xbb67ae85; + hh[2] = 0x3c6ef372; + hh[3] = 0xa54ff53a; + hh[4] = 0x510e527f; + hh[5] = 0x9b05688c; + hh[6] = 0x1f83d9ab; + hh[7] = 0x5be0cd19; - hl[0] = 0xf3bcc908; - hl[1] = 0x84caa73b; - hl[2] = 0xfe94f82b; - hl[3] = 0x5f1d36f1; - hl[4] = 0xade682d1; - hl[5] = 0x2b3e6c1f; - hl[6] = 0xfb41bd6b; - hl[7] = 0x137e2179; + hl[0] = 0xf3bcc908; + hl[1] = 0x84caa73b; + hl[2] = 0xfe94f82b; + hl[3] = 0x5f1d36f1; + hl[4] = 0xade682d1; + hl[5] = 0x2b3e6c1f; + hl[6] = 0xfb41bd6b; + hl[7] = 0x137e2179; - crypto_hashblocks_hl(hh, hl, m, n); - n %= 128; + crypto_hashblocks_hl(hh, hl, m, n); + n %= 128; - for (i = 0; i < n; i++) x[i] = m[b-n+i]; - x[n] = 128; + for (i = 0; i < n; i++) x[i] = m[b - n + i]; + x[n] = 128; - n = 256-128*(n<112?1:0); - x[n-9] = 0; - ts64(x, n-8, (b / 0x20000000) | 0, b << 3); - crypto_hashblocks_hl(hh, hl, x, n); + n = 256 - 128 * (n < 112 ? 1 : 0); + x[n - 9] = 0; + ts64(x, n - 8, (b / 0x20000000) | 0, b << 3); + crypto_hashblocks_hl(hh, hl, x, n); - for (i = 0; i < 8; i++) ts64(out, 8*i, hh[i], hl[i]); + for (i = 0; i < 8; i++) ts64(out, 8 * i, hh[i], hl[i]); - return 0; + return 0; } function add(p, q) { - var a = gf(), b = gf(), c = gf(), - d = gf(), e = gf(), f = gf(), - g = gf(), h = gf(), t = gf(); + var a = gf(), b = gf(), c = gf(), + d = gf(), e = gf(), f = gf(), + g = gf(), h = gf(), t = gf(); - Z(a, p[1], p[0]); - Z(t, q[1], q[0]); - M(a, a, t); - A(b, p[0], p[1]); - A(t, q[0], q[1]); - M(b, b, t); - M(c, p[3], q[3]); - M(c, c, D2); - M(d, p[2], q[2]); - A(d, d, d); - Z(e, b, a); - Z(f, d, c); - A(g, d, c); - A(h, b, a); + Z(a, p[1], p[0]); + Z(t, q[1], q[0]); + M(a, a, t); + A(b, p[0], p[1]); + A(t, q[0], q[1]); + M(b, b, t); + M(c, p[3], q[3]); + M(c, c, D2); + M(d, p[2], q[2]); + A(d, d, d); + Z(e, b, a); + Z(f, d, c); + A(g, d, c); + A(h, b, a); - M(p[0], e, f); - M(p[1], h, g); - M(p[2], g, f); - M(p[3], e, h); + M(p[0], e, f); + M(p[1], h, g); + M(p[2], g, f); + M(p[3], e, h); } function cswap(p, q, b) { - var i; - for (i = 0; i < 4; i++) { - sel25519(p[i], q[i], b); - } + var i; + for (i = 0; i < 4; i++) { + sel25519(p[i], q[i], b); + } } function pack(r, p) { - var tx = gf(), ty = gf(), zi = gf(); - inv25519(zi, p[2]); - M(tx, p[0], zi); - M(ty, p[1], zi); - pack25519(r, ty); - r[31] ^= par25519(tx) << 7; + var tx = gf(), ty = gf(), zi = gf(); + inv25519(zi, p[2]); + M(tx, p[0], zi); + M(ty, p[1], zi); + pack25519(r, ty); + r[31] ^= par25519(tx) << 7; } function scalarmult(p, q, s) { - var b, i; - set25519(p[0], gf0); - set25519(p[1], gf1); - set25519(p[2], gf1); - set25519(p[3], gf0); - for (i = 255; i >= 0; --i) { - b = (s[(i/8)|0] >> (i&7)) & 1; - cswap(p, q, b); - add(q, p); - add(p, p); - cswap(p, q, b); - } + var b, i; + set25519(p[0], gf0); + set25519(p[1], gf1); + set25519(p[2], gf1); + set25519(p[3], gf0); + for (i = 255; i >= 0; --i) { + b = (s[(i / 8) | 0] >> (i & 7)) & 1; + cswap(p, q, b); + add(q, p); + add(p, p); + cswap(p, q, b); + } } function scalarbase(p, s) { - var q = [gf(), gf(), gf(), gf()]; - set25519(q[0], X); - set25519(q[1], Y); - set25519(q[2], gf1); - M(q[3], X, Y); - scalarmult(p, q, s); + var q = [gf(), gf(), gf(), gf()]; + set25519(q[0], X); + set25519(q[1], Y); + set25519(q[2], gf1); + M(q[3], X, Y); + scalarmult(p, q, s); } function crypto_sign_keypair(pk, sk, seeded) { - var d = new Uint8Array(64); - var p = [gf(), gf(), gf(), gf()]; - var i; + var d = new Uint8Array(64); + var p = [gf(), gf(), gf(), gf()]; + var i; - if (!seeded) randombytes(sk, 32); - crypto_hash(d, sk, 32); - d[0] &= 248; - d[31] &= 127; - d[31] |= 64; + if (!seeded) randombytes(sk, 32); + crypto_hash(d, sk, 32); + d[0] &= 248; + d[31] &= 127; + d[31] |= 64; - scalarbase(p, d); - pack(pk, p); + scalarbase(p, d); + pack(pk, p); - for (i = 0; i < 32; i++) sk[i+32] = pk[i]; - return 0; + for (i = 0; i < 32; i++) sk[i + 32] = pk[i]; + return 0; } var L = new Float64Array([0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]); function modL(r, x) { - var carry, i, j, k; - for (i = 63; i >= 32; --i) { - carry = 0; - for (j = i - 32, k = i - 12; j < k; ++j) { - x[j] += carry - 16 * x[i] * L[j - (i - 32)]; - carry = (x[j] + 128) >> 8; - x[j] -= carry * 256; - } - x[j] += carry; - x[i] = 0; - } - carry = 0; - for (j = 0; j < 32; j++) { - x[j] += carry - (x[31] >> 4) * L[j]; - carry = x[j] >> 8; - x[j] &= 255; - } - for (j = 0; j < 32; j++) x[j] -= carry * L[j]; - for (i = 0; i < 32; i++) { - x[i+1] += x[i] >> 8; - r[i] = x[i] & 255; - } + var carry, i, j, k; + for (i = 63; i >= 32; --i) { + carry = 0; + for (j = i - 32, k = i - 12; j < k; ++j) { + x[j] += carry - 16 * x[i] * L[j - (i - 32)]; + carry = (x[j] + 128) >> 8; + x[j] -= carry * 256; + } + x[j] += carry; + x[i] = 0; + } + carry = 0; + for (j = 0; j < 32; j++) { + x[j] += carry - (x[31] >> 4) * L[j]; + carry = x[j] >> 8; + x[j] &= 255; + } + for (j = 0; j < 32; j++) x[j] -= carry * L[j]; + for (i = 0; i < 32; i++) { + x[i + 1] += x[i] >> 8; + r[i] = x[i] & 255; + } } function reduce(r) { - var x = new Float64Array(64), i; - for (i = 0; i < 64; i++) x[i] = r[i]; - for (i = 0; i < 64; i++) r[i] = 0; - modL(r, x); + var x = new Float64Array(64), i; + for (i = 0; i < 64; i++) x[i] = r[i]; + for (i = 0; i < 64; i++) r[i] = 0; + modL(r, x); } // Note: difference from C - smlen returned, not passed as argument. function crypto_sign(sm, m, n, sk) { - var d = new Uint8Array(64), h = new Uint8Array(64), r = new Uint8Array(64); - var i, j, x = new Float64Array(64); - var p = [gf(), gf(), gf(), gf()]; + var d = new Uint8Array(64), h = new Uint8Array(64), r = new Uint8Array(64); + var i, j, x = new Float64Array(64); + var p = [gf(), gf(), gf(), gf()]; - crypto_hash(d, sk, 32); - d[0] &= 248; - d[31] &= 127; - d[31] |= 64; + crypto_hash(d, sk, 32); + d[0] &= 248; + d[31] &= 127; + d[31] |= 64; - var smlen = n + 64; - for (i = 0; i < n; i++) sm[64 + i] = m[i]; - for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i]; + var smlen = n + 64; + for (i = 0; i < n; i++) sm[64 + i] = m[i]; + for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i]; - crypto_hash(r, sm.subarray(32), n+32); - reduce(r); - scalarbase(p, r); - pack(sm, p); + crypto_hash(r, sm.subarray(32), n + 32); + reduce(r); + scalarbase(p, r); + pack(sm, p); - for (i = 32; i < 64; i++) sm[i] = sk[i]; - crypto_hash(h, sm, n + 64); - reduce(h); + for (i = 32; i < 64; i++) sm[i] = sk[i]; + crypto_hash(h, sm, n + 64); + reduce(h); - for (i = 0; i < 64; i++) x[i] = 0; - for (i = 0; i < 32; i++) x[i] = r[i]; - for (i = 0; i < 32; i++) { - for (j = 0; j < 32; j++) { - x[i+j] += h[i] * d[j]; - } - } + for (i = 0; i < 64; i++) x[i] = 0; + for (i = 0; i < 32; i++) x[i] = r[i]; + for (i = 0; i < 32; i++) { + for (j = 0; j < 32; j++) { + x[i + j] += h[i] * d[j]; + } + } - modL(sm.subarray(32), x); - return smlen; + modL(sm.subarray(32), x); + return smlen; } function unpackneg(r, p) { - var t = gf(), chk = gf(), num = gf(), - den = gf(), den2 = gf(), den4 = gf(), - den6 = gf(); + var t = gf(), chk = gf(), num = gf(), + den = gf(), den2 = gf(), den4 = gf(), + den6 = gf(); - set25519(r[2], gf1); - unpack25519(r[1], p); - S(num, r[1]); - M(den, num, D); - Z(num, num, r[2]); - A(den, r[2], den); + set25519(r[2], gf1); + unpack25519(r[1], p); + S(num, r[1]); + M(den, num, D); + Z(num, num, r[2]); + A(den, r[2], den); - S(den2, den); - S(den4, den2); - M(den6, den4, den2); - M(t, den6, num); - M(t, t, den); + S(den2, den); + S(den4, den2); + M(den6, den4, den2); + M(t, den6, num); + M(t, t, den); - pow2523(t, t); - M(t, t, num); - M(t, t, den); - M(t, t, den); - M(r[0], t, den); + pow2523(t, t); + M(t, t, num); + M(t, t, den); + M(t, t, den); + M(r[0], t, den); - S(chk, r[0]); - M(chk, chk, den); - if (neq25519(chk, num)) M(r[0], r[0], I); + S(chk, r[0]); + M(chk, chk, den); + if (neq25519(chk, num)) M(r[0], r[0], I); - S(chk, r[0]); - M(chk, chk, den); - if (neq25519(chk, num)) return -1; + S(chk, r[0]); + M(chk, chk, den); + if (neq25519(chk, num)) return -1; - if (par25519(r[0]) === (p[31]>>7)) Z(r[0], gf0, r[0]); + if (par25519(r[0]) === (p[31] >> 7)) Z(r[0], gf0, r[0]); - M(r[3], r[0], r[1]); - return 0; + M(r[3], r[0], r[1]); + return 0; } function crypto_sign_open(m, sm, n, pk) { - var i, mlen; - var t = new Uint8Array(32), h = new Uint8Array(64); - var p = [gf(), gf(), gf(), gf()], - q = [gf(), gf(), gf(), gf()]; + var i, mlen; + var t = new Uint8Array(32), h = new Uint8Array(64); + var p = [gf(), gf(), gf(), gf()], + q = [gf(), gf(), gf(), gf()]; - mlen = -1; - if (n < 64) return -1; + mlen = -1; + if (n < 64) return -1; - if (unpackneg(q, pk)) return -1; + if (unpackneg(q, pk)) return -1; - for (i = 0; i < n; i++) m[i] = sm[i]; - for (i = 0; i < 32; i++) m[i+32] = pk[i]; - crypto_hash(h, m, n); - reduce(h); - scalarmult(p, q, h); + for (i = 0; i < n; i++) m[i] = sm[i]; + for (i = 0; i < 32; i++) m[i + 32] = pk[i]; + crypto_hash(h, m, n); + reduce(h); + scalarmult(p, q, h); - scalarbase(q, sm.subarray(32)); - add(p, q); - pack(t, p); + scalarbase(q, sm.subarray(32)); + add(p, q); + pack(t, p); - n -= 64; - if (crypto_verify_32(sm, 0, t, 0)) { - for (i = 0; i < n; i++) m[i] = 0; - return -1; - } + n -= 64; + if (crypto_verify_32(sm, 0, t, 0)) { + for (i = 0; i < n; i++) m[i] = 0; + return -1; + } - for (i = 0; i < n; i++) m[i] = sm[i + 64]; - mlen = n; - return mlen; + for (i = 0; i < n; i++) m[i] = sm[i + 64]; + mlen = n; + return mlen; } var crypto_secretbox_KEYBYTES = 32, - crypto_secretbox_NONCEBYTES = 24, - crypto_secretbox_ZEROBYTES = 32, - crypto_secretbox_BOXZEROBYTES = 16, - crypto_scalarmult_BYTES = 32, - crypto_scalarmult_SCALARBYTES = 32, - crypto_box_PUBLICKEYBYTES = 32, - crypto_box_SECRETKEYBYTES = 32, - crypto_box_BEFORENMBYTES = 32, - crypto_box_NONCEBYTES = crypto_secretbox_NONCEBYTES, - crypto_box_ZEROBYTES = crypto_secretbox_ZEROBYTES, - crypto_box_BOXZEROBYTES = crypto_secretbox_BOXZEROBYTES, - crypto_sign_BYTES = 64, - crypto_sign_PUBLICKEYBYTES = 32, - crypto_sign_SECRETKEYBYTES = 64, - crypto_sign_SEEDBYTES = 32, - crypto_hash_BYTES = 64; + crypto_secretbox_NONCEBYTES = 24, + crypto_secretbox_ZEROBYTES = 32, + crypto_secretbox_BOXZEROBYTES = 16, + crypto_scalarmult_BYTES = 32, + crypto_scalarmult_SCALARBYTES = 32, + crypto_box_PUBLICKEYBYTES = 32, + crypto_box_SECRETKEYBYTES = 32, + crypto_box_BEFORENMBYTES = 32, + crypto_box_NONCEBYTES = crypto_secretbox_NONCEBYTES, + crypto_box_ZEROBYTES = crypto_secretbox_ZEROBYTES, + crypto_box_BOXZEROBYTES = crypto_secretbox_BOXZEROBYTES, + crypto_sign_BYTES = 64, + crypto_sign_PUBLICKEYBYTES = 32, + crypto_sign_SECRETKEYBYTES = 64, + crypto_sign_SEEDBYTES = 32, + crypto_hash_BYTES = 64; nacl.lowlevel = { - crypto_core_hsalsa20: crypto_core_hsalsa20, - crypto_stream_xor: crypto_stream_xor, - crypto_stream: crypto_stream, - crypto_stream_salsa20_xor: crypto_stream_salsa20_xor, - crypto_stream_salsa20: crypto_stream_salsa20, - crypto_onetimeauth: crypto_onetimeauth, - crypto_onetimeauth_verify: crypto_onetimeauth_verify, - crypto_verify_16: crypto_verify_16, - crypto_verify_32: crypto_verify_32, - crypto_secretbox: crypto_secretbox, - crypto_secretbox_open: crypto_secretbox_open, - crypto_scalarmult: crypto_scalarmult, - crypto_scalarmult_base: crypto_scalarmult_base, - crypto_box_beforenm: crypto_box_beforenm, - crypto_box_afternm: crypto_box_afternm, - crypto_box: crypto_box, - crypto_box_open: crypto_box_open, - crypto_box_keypair: crypto_box_keypair, - crypto_hash: crypto_hash, - crypto_sign: crypto_sign, - crypto_sign_keypair: crypto_sign_keypair, - crypto_sign_open: crypto_sign_open, + crypto_core_hsalsa20: crypto_core_hsalsa20, + crypto_stream_xor: crypto_stream_xor, + crypto_stream: crypto_stream, + crypto_stream_salsa20_xor: crypto_stream_salsa20_xor, + crypto_stream_salsa20: crypto_stream_salsa20, + crypto_onetimeauth: crypto_onetimeauth, + crypto_onetimeauth_verify: crypto_onetimeauth_verify, + crypto_verify_16: crypto_verify_16, + crypto_verify_32: crypto_verify_32, + crypto_secretbox: crypto_secretbox, + crypto_secretbox_open: crypto_secretbox_open, + crypto_scalarmult: crypto_scalarmult, + crypto_scalarmult_base: crypto_scalarmult_base, + crypto_box_beforenm: crypto_box_beforenm, + crypto_box_afternm: crypto_box_afternm, + crypto_box: crypto_box, + crypto_box_open: crypto_box_open, + crypto_box_keypair: crypto_box_keypair, + crypto_hash: crypto_hash, + crypto_sign: crypto_sign, + crypto_sign_keypair: crypto_sign_keypair, + crypto_sign_open: crypto_sign_open, - crypto_secretbox_KEYBYTES: crypto_secretbox_KEYBYTES, - crypto_secretbox_NONCEBYTES: crypto_secretbox_NONCEBYTES, - crypto_secretbox_ZEROBYTES: crypto_secretbox_ZEROBYTES, - crypto_secretbox_BOXZEROBYTES: crypto_secretbox_BOXZEROBYTES, - crypto_scalarmult_BYTES: crypto_scalarmult_BYTES, - crypto_scalarmult_SCALARBYTES: crypto_scalarmult_SCALARBYTES, - crypto_box_PUBLICKEYBYTES: crypto_box_PUBLICKEYBYTES, - crypto_box_SECRETKEYBYTES: crypto_box_SECRETKEYBYTES, - crypto_box_BEFORENMBYTES: crypto_box_BEFORENMBYTES, - crypto_box_NONCEBYTES: crypto_box_NONCEBYTES, - crypto_box_ZEROBYTES: crypto_box_ZEROBYTES, - crypto_box_BOXZEROBYTES: crypto_box_BOXZEROBYTES, - crypto_sign_BYTES: crypto_sign_BYTES, - crypto_sign_PUBLICKEYBYTES: crypto_sign_PUBLICKEYBYTES, - crypto_sign_SECRETKEYBYTES: crypto_sign_SECRETKEYBYTES, - crypto_sign_SEEDBYTES: crypto_sign_SEEDBYTES, - crypto_hash_BYTES: crypto_hash_BYTES + crypto_secretbox_KEYBYTES: crypto_secretbox_KEYBYTES, + crypto_secretbox_NONCEBYTES: crypto_secretbox_NONCEBYTES, + crypto_secretbox_ZEROBYTES: crypto_secretbox_ZEROBYTES, + crypto_secretbox_BOXZEROBYTES: crypto_secretbox_BOXZEROBYTES, + crypto_scalarmult_BYTES: crypto_scalarmult_BYTES, + crypto_scalarmult_SCALARBYTES: crypto_scalarmult_SCALARBYTES, + crypto_box_PUBLICKEYBYTES: crypto_box_PUBLICKEYBYTES, + crypto_box_SECRETKEYBYTES: crypto_box_SECRETKEYBYTES, + crypto_box_BEFORENMBYTES: crypto_box_BEFORENMBYTES, + crypto_box_NONCEBYTES: crypto_box_NONCEBYTES, + crypto_box_ZEROBYTES: crypto_box_ZEROBYTES, + crypto_box_BOXZEROBYTES: crypto_box_BOXZEROBYTES, + crypto_sign_BYTES: crypto_sign_BYTES, + crypto_sign_PUBLICKEYBYTES: crypto_sign_PUBLICKEYBYTES, + crypto_sign_SECRETKEYBYTES: crypto_sign_SECRETKEYBYTES, + crypto_sign_SEEDBYTES: crypto_sign_SEEDBYTES, + crypto_hash_BYTES: crypto_hash_BYTES }; /* High-level API */ function checkLengths(k, n) { - if (k.length !== crypto_secretbox_KEYBYTES) throw new Error('bad key size'); - if (n.length !== crypto_secretbox_NONCEBYTES) throw new Error('bad nonce size'); + if (k.length !== crypto_secretbox_KEYBYTES) throw new Error('bad key size'); + if (n.length !== crypto_secretbox_NONCEBYTES) throw new Error('bad nonce size'); } function checkBoxLengths(pk, sk) { - if (pk.length !== crypto_box_PUBLICKEYBYTES) throw new Error('bad public key size'); - if (sk.length !== crypto_box_SECRETKEYBYTES) throw new Error('bad secret key size'); + if (pk.length !== crypto_box_PUBLICKEYBYTES) throw new Error('bad public key size'); + if (sk.length !== crypto_box_SECRETKEYBYTES) throw new Error('bad secret key size'); } function checkArrayTypes() { - var t, i; - for (i = 0; i < arguments.length; i++) { - if ((t = Object.prototype.toString.call(arguments[i])) !== '[object Uint8Array]') - throw new TypeError('unexpected type ' + t + ', use Uint8Array'); - } + var t, i; + for (i = 0; i < arguments.length; i++) { + if ((t = Object.prototype.toString.call(arguments[i])) !== '[object Uint8Array]') + throw new TypeError('unexpected type ' + t + ', use Uint8Array'); + } } function cleanup(arr) { - for (var i = 0; i < arr.length; i++) arr[i] = 0; + for (var i = 0; i < arr.length; i++) arr[i] = 0; } nacl.util = {}; -nacl.util.decodeUTF8 = function(s) { - var i, d = unescape(encodeURIComponent(s)), b = new Uint8Array(d.length); - for (i = 0; i < d.length; i++) b[i] = d.charCodeAt(i); - return b; +nacl.util.decodeUTF8 = function (s) { + var i, d = unescape(encodeURIComponent(s)), b = new Uint8Array(d.length); + for (i = 0; i < d.length; i++) b[i] = d.charCodeAt(i); + return b; }; -nacl.util.encodeUTF8 = function(arr) { - var i, s = []; - for (i = 0; i < arr.length; i++) s.push(String.fromCharCode(arr[i])); - return decodeURIComponent(escape(s.join(''))); +nacl.util.encodeUTF8 = function (arr) { + var i, s = []; + for (i = 0; i < arr.length; i++) s.push(String.fromCharCode(arr[i])); + return decodeURIComponent(escape(s.join(''))); }; -nacl.util.encodeBase64 = function(arr) { - if (typeof btoa === 'undefined') { - return (new Buffer(arr)).toString('base64'); - } else { - var i, s = [], len = arr.length; - for (i = 0; i < len; i++) s.push(String.fromCharCode(arr[i])); - return btoa(s.join('')); - } +nacl.util.encodeBase64 = function (arr) { + if (typeof btoa === 'undefined') { + return (new Buffer(arr)).toString('base64'); + } else { + var i, s = [], len = arr.length; + for (i = 0; i < len; i++) s.push(String.fromCharCode(arr[i])); + return btoa(s.join('')); + } }; -nacl.util.decodeBase64 = function(s) { - if (typeof atob === 'undefined') { - return new Uint8Array(Array.prototype.slice.call(new Buffer(s, 'base64'), 0)); - } else { - var i, d = atob(s), b = new Uint8Array(d.length); - for (i = 0; i < d.length; i++) b[i] = d.charCodeAt(i); - return b; - } +nacl.util.decodeBase64 = function (s) { + if (typeof atob === 'undefined') { + return new Uint8Array(Array.prototype.slice.call(new Buffer(s, 'base64'), 0)); + } else { + var i, d = atob(s), b = new Uint8Array(d.length); + for (i = 0; i < d.length; i++) b[i] = d.charCodeAt(i); + return b; + } }; -nacl.randomBytes = function(n) { - var b = new Uint8Array(n); - randombytes(b, n); - return b; +nacl.randomBytes = function (n) { + var b = new Uint8Array(n); + randombytes(b, n); + return b; }; -nacl.secretbox = function(msg, nonce, key) { - checkArrayTypes(msg, nonce, key); - checkLengths(key, nonce); - var m = new Uint8Array(crypto_secretbox_ZEROBYTES + msg.length); - var c = new Uint8Array(m.length); - for (var i = 0; i < msg.length; i++) m[i+crypto_secretbox_ZEROBYTES] = msg[i]; - crypto_secretbox(c, m, m.length, nonce, key); - return c.subarray(crypto_secretbox_BOXZEROBYTES); +nacl.secretbox = function (msg, nonce, key) { + checkArrayTypes(msg, nonce, key); + checkLengths(key, nonce); + var m = new Uint8Array(crypto_secretbox_ZEROBYTES + msg.length); + var c = new Uint8Array(m.length); + for (var i = 0; i < msg.length; i++) m[i + crypto_secretbox_ZEROBYTES] = msg[i]; + crypto_secretbox(c, m, m.length, nonce, key); + return c.subarray(crypto_secretbox_BOXZEROBYTES); }; -nacl.secretbox.open = function(box, nonce, key) { - checkArrayTypes(box, nonce, key); - checkLengths(key, nonce); - var c = new Uint8Array(crypto_secretbox_BOXZEROBYTES + box.length); - var m = new Uint8Array(c.length); - for (var i = 0; i < box.length; i++) c[i+crypto_secretbox_BOXZEROBYTES] = box[i]; - if (c.length < 32) return false; - if (crypto_secretbox_open(m, c, c.length, nonce, key) !== 0) return false; - return m.subarray(crypto_secretbox_ZEROBYTES); +nacl.secretbox.open = function (box, nonce, key) { + checkArrayTypes(box, nonce, key); + checkLengths(key, nonce); + var c = new Uint8Array(crypto_secretbox_BOXZEROBYTES + box.length); + var m = new Uint8Array(c.length); + for (var i = 0; i < box.length; i++) c[i + crypto_secretbox_BOXZEROBYTES] = box[i]; + if (c.length < 32) return false; + if (crypto_secretbox_open(m, c, c.length, nonce, key) !== 0) return false; + return m.subarray(crypto_secretbox_ZEROBYTES); }; nacl.secretbox.keyLength = crypto_secretbox_KEYBYTES; nacl.secretbox.nonceLength = crypto_secretbox_NONCEBYTES; nacl.secretbox.overheadLength = crypto_secretbox_BOXZEROBYTES; -nacl.scalarMult = function(n, p) { - checkArrayTypes(n, p); - if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size'); - if (p.length !== crypto_scalarmult_BYTES) throw new Error('bad p size'); - var q = new Uint8Array(crypto_scalarmult_BYTES); - crypto_scalarmult(q, n, p); - return q; +nacl.scalarMult = function (n, p) { + checkArrayTypes(n, p); + if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size'); + if (p.length !== crypto_scalarmult_BYTES) throw new Error('bad p size'); + var q = new Uint8Array(crypto_scalarmult_BYTES); + crypto_scalarmult(q, n, p); + return q; }; -nacl.scalarMult.base = function(n) { - checkArrayTypes(n); - if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size'); - var q = new Uint8Array(crypto_scalarmult_BYTES); - crypto_scalarmult_base(q, n); - return q; +nacl.scalarMult.base = function (n) { + checkArrayTypes(n); + if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size'); + var q = new Uint8Array(crypto_scalarmult_BYTES); + crypto_scalarmult_base(q, n); + return q; }; nacl.scalarMult.scalarLength = crypto_scalarmult_SCALARBYTES; nacl.scalarMult.groupElementLength = crypto_scalarmult_BYTES; -nacl.box = function(msg, nonce, publicKey, secretKey) { - var k = nacl.box.before(publicKey, secretKey); - return nacl.secretbox(msg, nonce, k); +nacl.box = function (msg, nonce, publicKey, secretKey) { + var k = nacl.box.before(publicKey, secretKey); + return nacl.secretbox(msg, nonce, k); }; -nacl.box.before = function(publicKey, secretKey) { - checkArrayTypes(publicKey, secretKey); - checkBoxLengths(publicKey, secretKey); - var k = new Uint8Array(crypto_box_BEFORENMBYTES); - crypto_box_beforenm(k, publicKey, secretKey); - return k; +nacl.box.before = function (publicKey, secretKey) { + checkArrayTypes(publicKey, secretKey); + checkBoxLengths(publicKey, secretKey); + var k = new Uint8Array(crypto_box_BEFORENMBYTES); + crypto_box_beforenm(k, publicKey, secretKey); + return k; }; nacl.box.after = nacl.secretbox; -nacl.box.open = function(msg, nonce, publicKey, secretKey) { - var k = nacl.box.before(publicKey, secretKey); - return nacl.secretbox.open(msg, nonce, k); +nacl.box.open = function (msg, nonce, publicKey, secretKey) { + var k = nacl.box.before(publicKey, secretKey); + return nacl.secretbox.open(msg, nonce, k); }; nacl.box.open.after = nacl.secretbox.open; -nacl.box.keyPair = function() { - var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); - var sk = new Uint8Array(crypto_box_SECRETKEYBYTES); - crypto_box_keypair(pk, sk); - return {publicKey: pk, secretKey: sk}; +nacl.box.keyPair = function () { + var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); + var sk = new Uint8Array(crypto_box_SECRETKEYBYTES); + crypto_box_keypair(pk, sk); + return { publicKey: pk, secretKey: sk }; }; -nacl.box.keyPair.fromSecretKey = function(secretKey) { - checkArrayTypes(secretKey); - if (secretKey.length !== crypto_box_SECRETKEYBYTES) - throw new Error('bad secret key size'); - var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); - crypto_scalarmult_base(pk, secretKey); - return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; +nacl.box.keyPair.fromSecretKey = function (secretKey) { + checkArrayTypes(secretKey); + if (secretKey.length !== crypto_box_SECRETKEYBYTES) + throw new Error('bad secret key size'); + var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); + crypto_scalarmult_base(pk, secretKey); + return { publicKey: pk, secretKey: new Uint8Array(secretKey) }; }; nacl.box.publicKeyLength = crypto_box_PUBLICKEYBYTES; @@ -2288,75 +2286,75 @@ nacl.box.sharedKeyLength = crypto_box_BEFORENMBYTES; nacl.box.nonceLength = crypto_box_NONCEBYTES; nacl.box.overheadLength = nacl.secretbox.overheadLength; -nacl.sign = function(msg, secretKey) { - checkArrayTypes(msg, secretKey); - if (secretKey.length !== crypto_sign_SECRETKEYBYTES) - throw new Error('bad secret key size'); - var signedMsg = new Uint8Array(crypto_sign_BYTES+msg.length); - crypto_sign(signedMsg, msg, msg.length, secretKey); - return signedMsg; +nacl.sign = function (msg, secretKey) { + checkArrayTypes(msg, secretKey); + if (secretKey.length !== crypto_sign_SECRETKEYBYTES) + throw new Error('bad secret key size'); + var signedMsg = new Uint8Array(crypto_sign_BYTES + msg.length); + crypto_sign(signedMsg, msg, msg.length, secretKey); + return signedMsg; }; -nacl.sign.open = function(signedMsg, publicKey) { - if (arguments.length !== 2) - throw new Error('nacl.sign.open accepts 2 arguments; did you mean to use nacl.sign.detached.verify?'); - checkArrayTypes(signedMsg, publicKey); - if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) - throw new Error('bad public key size'); - var tmp = new Uint8Array(signedMsg.length); - var mlen = crypto_sign_open(tmp, signedMsg, signedMsg.length, publicKey); - if (mlen < 0) return null; - var m = new Uint8Array(mlen); - for (var i = 0; i < m.length; i++) m[i] = tmp[i]; - return m; +nacl.sign.open = function (signedMsg, publicKey) { + if (arguments.length !== 2) + throw new Error('nacl.sign.open accepts 2 arguments; did you mean to use nacl.sign.detached.verify?'); + checkArrayTypes(signedMsg, publicKey); + if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) + throw new Error('bad public key size'); + var tmp = new Uint8Array(signedMsg.length); + var mlen = crypto_sign_open(tmp, signedMsg, signedMsg.length, publicKey); + if (mlen < 0) return null; + var m = new Uint8Array(mlen); + for (var i = 0; i < m.length; i++) m[i] = tmp[i]; + return m; }; -nacl.sign.detached = function(msg, secretKey) { - var signedMsg = nacl.sign(msg, secretKey); - var sig = new Uint8Array(crypto_sign_BYTES); - for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i]; - return sig; +nacl.sign.detached = function (msg, secretKey) { + var signedMsg = nacl.sign(msg, secretKey); + var sig = new Uint8Array(crypto_sign_BYTES); + for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i]; + return sig; }; -nacl.sign.detached.verify = function(msg, sig, publicKey) { - checkArrayTypes(msg, sig, publicKey); - if (sig.length !== crypto_sign_BYTES) - throw new Error('bad signature size'); - if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) - throw new Error('bad public key size'); - var sm = new Uint8Array(crypto_sign_BYTES + msg.length); - var m = new Uint8Array(crypto_sign_BYTES + msg.length); - var i; - for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i]; - for (i = 0; i < msg.length; i++) sm[i+crypto_sign_BYTES] = msg[i]; - return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0); +nacl.sign.detached.verify = function (msg, sig, publicKey) { + checkArrayTypes(msg, sig, publicKey); + if (sig.length !== crypto_sign_BYTES) + throw new Error('bad signature size'); + if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) + throw new Error('bad public key size'); + var sm = new Uint8Array(crypto_sign_BYTES + msg.length); + var m = new Uint8Array(crypto_sign_BYTES + msg.length); + var i; + for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i]; + for (i = 0; i < msg.length; i++) sm[i + crypto_sign_BYTES] = msg[i]; + return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0); }; -nacl.sign.keyPair = function() { - var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); - var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); - crypto_sign_keypair(pk, sk); - return {publicKey: pk, secretKey: sk}; +nacl.sign.keyPair = function () { + var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); + var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); + crypto_sign_keypair(pk, sk); + return { publicKey: pk, secretKey: sk }; }; -nacl.sign.keyPair.fromSecretKey = function(secretKey) { - checkArrayTypes(secretKey); - if (secretKey.length !== crypto_sign_SECRETKEYBYTES) - throw new Error('bad secret key size'); - var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); - for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32+i]; - return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; +nacl.sign.keyPair.fromSecretKey = function (secretKey) { + checkArrayTypes(secretKey); + if (secretKey.length !== crypto_sign_SECRETKEYBYTES) + throw new Error('bad secret key size'); + var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); + for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32 + i]; + return { publicKey: pk, secretKey: new Uint8Array(secretKey) }; }; -nacl.sign.keyPair.fromSeed = function(seed) { - checkArrayTypes(seed); - if (seed.length !== crypto_sign_SEEDBYTES) - throw new Error('bad seed size'); - var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); - var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); - for (var i = 0; i < 32; i++) sk[i] = seed[i]; - crypto_sign_keypair(pk, sk, true); - return {publicKey: pk, secretKey: sk}; +nacl.sign.keyPair.fromSeed = function (seed) { + checkArrayTypes(seed); + if (seed.length !== crypto_sign_SEEDBYTES) + throw new Error('bad seed size'); + var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); + var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); + for (var i = 0; i < 32; i++) sk[i] = seed[i]; + crypto_sign_keypair(pk, sk, true); + return { publicKey: pk, secretKey: sk }; }; nacl.sign.publicKeyLength = crypto_sign_PUBLICKEYBYTES; @@ -2364,59 +2362,58 @@ nacl.sign.secretKeyLength = crypto_sign_SECRETKEYBYTES; nacl.sign.seedLength = crypto_sign_SEEDBYTES; nacl.sign.signatureLength = crypto_sign_BYTES; -nacl.hash = function(msg) { - checkArrayTypes(msg); - var h = new Uint8Array(crypto_hash_BYTES); - crypto_hash(h, msg, msg.length); - return h; +nacl.hash = function (msg) { + checkArrayTypes(msg); + var h = new Uint8Array(crypto_hash_BYTES); + crypto_hash(h, msg, msg.length); + return h; }; nacl.hash.hashLength = crypto_hash_BYTES; -nacl.verify = function(x, y) { - checkArrayTypes(x, y); - // Zero length arguments are considered not equal. - if (x.length === 0 || y.length === 0) return false; - if (x.length !== y.length) return false; - return (vn(x, 0, y, 0, x.length) === 0); +nacl.verify = function (x, y) { + checkArrayTypes(x, y); + // Zero length arguments are considered not equal. + if (x.length === 0 || y.length === 0) return false; + if (x.length !== y.length) return false; + return (vn(x, 0, y, 0, x.length) === 0); }; -nacl.setPRNG = function(fn) { - randombytes = fn; +nacl.setPRNG = function (fn) { + randombytes = fn; }; -(function() { - // Initialize PRNG if environment provides CSPRNG. - // If not, methods calling randombytes will throw. - var crypto; - if (typeof window !== 'undefined') { - // Browser. - if (window.crypto && window.crypto.getRandomValues) { - crypto = window.crypto; // Standard - } else if (window.msCrypto && window.msCrypto.getRandomValues) { - crypto = window.msCrypto; // Internet Explorer 11+ - } - if (crypto) { - nacl.setPRNG(function(x, n) { - var i, v = new Uint8Array(n); - crypto.getRandomValues(v); - for (i = 0; i < n; i++) x[i] = v[i]; - cleanup(v); - }); - } - } else if (typeof require !== 'undefined') { - // Node.js. - crypto = require('crypto'); - if (crypto) { - nacl.setPRNG(function(x, n) { - var i, v = crypto.randomBytes(n); - for (i = 0; i < n; i++) x[i] = v[i]; - cleanup(v); - }); - } - } +(function () { + // Initialize PRNG if environment provides CSPRNG. + // If not, methods calling randombytes will throw. + var crypto; + if (typeof window !== 'undefined') { + // Browser. + if (window.crypto && window.crypto.getRandomValues) { + crypto = window.crypto; // Standard + } else if (window.msCrypto && window.msCrypto.getRandomValues) { + crypto = window.msCrypto; // Internet Explorer 11+ + } + if (crypto) { + nacl.setPRNG(function (x, n) { + var i, v = new Uint8Array(n); + crypto.getRandomValues(v); + for (i = 0; i < n; i++) x[i] = v[i]; + cleanup(v); + }); + } + } else if (typeof require !== 'undefined') { + // Node.js. + crypto = require('crypto'); + if (crypto) { + nacl.setPRNG(function (x, n) { + var i, v = crypto.randomBytes(n); + for (i = 0; i < n; i++) x[i] = v[i]; + cleanup(v); + }); + } + } })(); // == CHANGE TO ES6 EXPORT == // -//})(typeof module !== 'undefined' && module.exports ? module.exports : (window.nacl = window.nacl || {})); export default nacl diff --git a/crypto/api/deps/qora.js b/crypto/api/deps/qora.js index 5c52ec44..bc385942 100644 --- a/crypto/api/deps/qora.js +++ b/crypto/api/deps/qora.js @@ -26,9 +26,8 @@ const TYPES = { MESSAGE_TRANSACTION: 17 }; -function getKeyPairFromSeed(seed, returnBase58) -{ - if(typeof(seed) == "string") { +function getKeyPairFromSeed(seed, returnBase58) { + if (typeof (seed) == "string") { seed = new Uint8Array(Base58.decode(seed)); } @@ -36,7 +35,7 @@ function getKeyPairFromSeed(seed, returnBase58) var base58privateKey = Base58.encode(keyPair.secretKey); var base58publicKey = Base58.encode(keyPair.publicKey); - if(returnBase58) { + if (returnBase58) { return { privateKey: Base58.encode(keyPair.secretKey), publicKey: Base58.encode(keyPair.publicKey) @@ -51,16 +50,16 @@ function getKeyPairFromSeed(seed, returnBase58) function stringtoUTF8Array(message) { if (typeof message == 'string') { - var s = unescape(encodeURIComponent(message)); // UTF-8 - message = new Uint8Array(s.length); - for (var i = 0; i < s.length; i++) { + var s = unescape(encodeURIComponent(message)); // UTF-8 + message = new Uint8Array(s.length); + for (var i = 0; i < s.length; i++) { message[i] = s.charCodeAt(i) & 0xff; } } return message; } -function int32ToBytes (word) { +function int32ToBytes(word) { var byteArray = []; for (var b = 0; b < 32; b += 8) { byteArray.push((word >>> (24 - b % 32)) & 0xFF); @@ -68,20 +67,20 @@ function int32ToBytes (word) { return byteArray; } -function int64ToBytes (int64) { - // we want to represent the input as a 8-bytes array - var byteArray = [0, 0, 0, 0, 0, 0, 0, 0]; +function int64ToBytes(int64) { + // we want to represent the input as a 8-bytes array + var byteArray = [0, 0, 0, 0, 0, 0, 0, 0]; - for ( var index = 0; index < byteArray.length; index ++ ) { - var byte = int64 & 0xff; - byteArray [ byteArray.length - index - 1 ] = byte; - int64 = (int64 - byte) / 256 ; - } + for (var index = 0; index < byteArray.length; index++) { + var byte = int64 & 0xff; + byteArray[byteArray.length - index - 1] = byte; + int64 = (int64 - byte) / 256; + } - return byteArray; + return byteArray; } -function appendBuffer (buffer1, buffer2) { +function appendBuffer(buffer1, buffer2) { buffer1 = new Uint8Array(buffer1); buffer2 = new Uint8Array(buffer2); var tmp = new Uint8Array(buffer1.byteLength + buffer2.byteLength); @@ -90,21 +89,18 @@ function appendBuffer (buffer1, buffer2) { return tmp; } -function equal (buf1, buf2) -{ - if (buf1.byteLength != buf2.byteLength) return false; - var dv1 = new Uint8Array(buf1); - var dv2 = new Uint8Array(buf2); - for (var i = 0; i != buf1.byteLength; i++) - { - if (dv1[i] != dv2[i]) return false; - } - return true; +function equal(buf1, buf2) { + if (buf1.byteLength != buf2.byteLength) return false; + var dv1 = new Uint8Array(buf1); + var dv2 = new Uint8Array(buf2); + for (var i = 0; i != buf1.byteLength; i++) { + if (dv1[i] != dv2[i]) return false; + } + return true; } -function generateAccountSeed(seed, nonce, returnBase58) -{ - if(typeof(seed) == "string") { +function generateAccountSeed(seed, nonce, returnBase58) { + if (typeof (seed) == "string") { seed = Base58.decode(seed); } @@ -116,7 +112,7 @@ function generateAccountSeed(seed, nonce, returnBase58) resultSeed = appendBuffer(resultSeed, seed); resultSeed = appendBuffer(resultSeed, nonceBytes); - if(returnBase58) { + if (returnBase58) { return Base58.encode(SHA256.digest(SHA256.digest(resultSeed))); } else { return new SHA256.digest(SHA256.digest(resultSeed)); @@ -124,11 +120,10 @@ function generateAccountSeed(seed, nonce, returnBase58) } -function getAccountAddressFromPublicKey(publicKey) -{ +function getAccountAddressFromPublicKey(publicKey) { var ADDRESS_VERSION = 58; // Q - if(typeof(publicKey) == "string") { + if (typeof (publicKey) == "string") { publicKey = Base58.decode(publicKey); } @@ -150,13 +145,12 @@ function getAccountAddressFromPublicKey(publicKey) return Base58.encode(addressArray); } -function getAccountAddressType(address) -{ +function getAccountAddressType(address) { try { var ADDRESS_VERSION = 58; // Q var AT_ADDRESS_VERSION = 23; // A - if(typeof(address) == "string") { + if (typeof (address) == "string") { address = Base58.decode(address); } @@ -166,14 +160,11 @@ function getAccountAddressType(address) var checkSumTwo = SHA256.digest(SHA256.digest(addressWitoutChecksum)); checkSumTwo = checkSumTwo.subarray(0, 4); - if (equal(checkSum, checkSumTwo)) - { - if(address[0] == ADDRESS_VERSION) - { + if (equal(checkSum, checkSumTwo)) { + if (address[0] == ADDRESS_VERSION) { return "standard"; } - if(address[0] == AT_ADDRESS_VERSION) - { + if (address[0] == AT_ADDRESS_VERSION) { return "at"; } } @@ -185,8 +176,7 @@ function getAccountAddressType(address) } } -function isValidAddress(address) -{ +function isValidAddress(address) { return (getAccountAddressType(address) != "invalid"); } @@ -307,8 +297,8 @@ function generateSignatureRegisterNameTransaction(keyPair, lastReference, owner, } function generateRegisterNameTransaction(keyPair, lastReference, owner, name, value, fee, timestamp, signature) { - return appendBuffer( generateRegisterNameTransactionBase(keyPair.publicKey, lastReference, owner, name, value, fee, timestamp), - signature ); + return appendBuffer(generateRegisterNameTransactionBase(keyPair.publicKey, lastReference, owner, name, value, fee, timestamp), + signature); } function generateRegisterNameTransactionBase(publicKey, lastReference, owner, name, value, fee, timestamp) { @@ -333,4 +323,4 @@ function generateRegisterNameTransactionBase(publicKey, lastReference, owner, na data = appendBuffer(data, feeBytes); return data; -} \ No newline at end of file +} diff --git a/crypto/api/deps/ripemd160.js b/crypto/api/deps/ripemd160.js index a50d0035..88f72c31 100644 --- a/crypto/api/deps/ripemd160.js +++ b/crypto/api/deps/ripemd160.js @@ -1,5 +1,7 @@ // Extracted from https://github.com/crypto-browserify/ripemd160 + const ARRAY16 = new Array(16); + const zl = initU8Array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, diff --git a/crypto/api/deps/sha256.js b/crypto/api/deps/sha256.js index e4f718f4..4b1fcb93 100644 --- a/crypto/api/deps/sha256.js +++ b/crypto/api/deps/sha256.js @@ -3,140 +3,139 @@ const SHA256 = {}; SHA256.K = [ - 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, - 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, - 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, - 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, - 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, - 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, - 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, - 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, - 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, - 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, - 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, - 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, - 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, + 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, + 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, + 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, + 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, + 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, + 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, + 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, + 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, + 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, + 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, + 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 ]; // The digest function returns the hash value (digest) // as a 32 byte (typed) array. // message: the string or byte array to hash -SHA256.digest = function(message) { - var h0 = 0x6a09e667; - var h1 = 0xbb67ae85; - var h2 = 0x3c6ef372; - var h3 = 0xa54ff53a; - var h4 = 0x510e527f; - var h5 = 0x9b05688c; - var h6 = 0x1f83d9ab; - var h7 = 0x5be0cd19; - var K = SHA256.K; - if (typeof message == 'string') { - var s = unescape(encodeURIComponent(message)); // UTF-8 - message = new Uint8Array(s.length); - for (var i = 0; i < s.length; i++) { - message[i] = s.charCodeAt(i) & 0xff; - } - } - var length = message.length; - var byteLength = Math.floor((length + 72) / 64) * 64; - var wordLength = byteLength / 4; - var bitLength = length * 8; - var m = new Uint8Array(byteLength); - m.set(message); - m[length] = 0x80; - m[byteLength - 4] = bitLength >>> 24; - m[byteLength - 3] = (bitLength >>> 16) & 0xff; - m[byteLength - 2] = (bitLength >>> 8) & 0xff; - m[byteLength - 1] = bitLength & 0xff; - var words = new Int32Array(wordLength); - var byteIndex = 0; - for (var i = 0; i < words.length; i++) { - var word = m[byteIndex++] << 24; - word |= m[byteIndex++] << 16; - word |= m[byteIndex++] << 8; - word |= m[byteIndex++]; - words[i] = word; - } - var w = new Int32Array(64); - for (var j = 0; j < wordLength; j += 16) { - for (i = 0; i < 16; i++) { - w[i] = words[j + i]; - } - for (i = 16; i < 64; i++) { - var v = w[i - 15]; - var s0 = (v >>> 7) | (v << 25); - s0 ^= (v >>> 18) | (v << 14); - s0 ^= (v >>> 3); - v = w[i - 2]; - var s1 = (v >>> 17) | (v << 15); - s1 ^= (v >>> 19) | (v << 13); - s1 ^= (v >>> 10); - w[i] = (w[i - 16] + s0 + w[i - 7] + s1) & 0xffffffff; - } - var a = h0; - var b = h1; - var c = h2; - var d = h3; - var e = h4; - var f = h5; - var g = h6; - var h = h7; - for (i = 0; i < 64; i++) { - s1 = (e >>> 6) | (e << 26); - s1 ^= (e >>> 11) | (e << 21); - s1 ^= (e >>> 25) | (e << 7); - var ch = (e & f) ^ (~e & g); - var temp1 = (h + s1 + ch + K[i] + w[i]) & 0xffffffff; - s0 = (a >>> 2) | (a << 30); - s0 ^= (a >>> 13) | (a << 19); - s0 ^= (a >>> 22) | (a << 10); - var maj = (a & b) ^ (a & c) ^ (b & c); - var temp2 = (s0 + maj) & 0xffffffff; - h = g - g = f - f = e - e = (d + temp1) & 0xffffffff; - d = c; - c = b; - b = a; - a = (temp1 + temp2) & 0xffffffff; - } - h0 = (h0 + a) & 0xffffffff; - h1 = (h1 + b) & 0xffffffff; - h2 = (h2 + c) & 0xffffffff; - h3 = (h3 + d) & 0xffffffff; - h4 = (h4 + e) & 0xffffffff; - h5 = (h5 + f) & 0xffffffff; - h6 = (h6 + g) & 0xffffffff; - h7 = (h7 + h) & 0xffffffff; - } - var hash = new Uint8Array(32); - for (var i = 0; i < 4; i++) { - hash[i] = (h0 >>> (8 * (3 - i))) & 0xff; - hash[i + 4] = (h1 >>> (8 * (3 - i))) & 0xff; - hash[i + 8] = (h2 >>> (8 * (3 - i))) & 0xff; - hash[i + 12] = (h3 >>> (8 * (3 - i))) & 0xff; - hash[i + 16] = (h4 >>> (8 * (3 - i))) & 0xff; - hash[i + 20] = (h5 >>> (8 * (3 - i))) & 0xff; - hash[i + 24] = (h6 >>> (8 * (3 - i))) & 0xff; - hash[i + 28] = (h7 >>> (8 * (3 - i))) & 0xff; - } - return hash; -} +SHA256.digest = function (message) { + var h0 = 0x6a09e667; + var h1 = 0xbb67ae85; + var h2 = 0x3c6ef372; + var h3 = 0xa54ff53a; + var h4 = 0x510e527f; + var h5 = 0x9b05688c; + var h6 = 0x1f83d9ab; + var h7 = 0x5be0cd19; + var K = SHA256.K; + if (typeof message == 'string') { + var s = unescape(encodeURIComponent(message)); // UTF-8 + message = new Uint8Array(s.length); + for (var i = 0; i < s.length; i++) { + message[i] = s.charCodeAt(i) & 0xff; + } + } + var length = message.length; + var byteLength = Math.floor((length + 72) / 64) * 64; + var wordLength = byteLength / 4; + var bitLength = length * 8; + var m = new Uint8Array(byteLength); + m.set(message); + m[length] = 0x80; + m[byteLength - 4] = bitLength >>> 24; + m[byteLength - 3] = (bitLength >>> 16) & 0xff; + m[byteLength - 2] = (bitLength >>> 8) & 0xff; + m[byteLength - 1] = bitLength & 0xff; + var words = new Int32Array(wordLength); + var byteIndex = 0; + for (var i = 0; i < words.length; i++) { + var word = m[byteIndex++] << 24; + word |= m[byteIndex++] << 16; + word |= m[byteIndex++] << 8; + word |= m[byteIndex++]; + words[i] = word; + } + var w = new Int32Array(64); + for (var j = 0; j < wordLength; j += 16) { + for (i = 0; i < 16; i++) { + w[i] = words[j + i]; + } + for (i = 16; i < 64; i++) { + var v = w[i - 15]; + var s0 = (v >>> 7) | (v << 25); + s0 ^= (v >>> 18) | (v << 14); + s0 ^= (v >>> 3); + v = w[i - 2]; + var s1 = (v >>> 17) | (v << 15); + s1 ^= (v >>> 19) | (v << 13); + s1 ^= (v >>> 10); + w[i] = (w[i - 16] + s0 + w[i - 7] + s1) & 0xffffffff; + } + var a = h0; + var b = h1; + var c = h2; + var d = h3; + var e = h4; + var f = h5; + var g = h6; + var h = h7; + for (i = 0; i < 64; i++) { + s1 = (e >>> 6) | (e << 26); + s1 ^= (e >>> 11) | (e << 21); + s1 ^= (e >>> 25) | (e << 7); + var ch = (e & f) ^ (~e & g); + var temp1 = (h + s1 + ch + K[i] + w[i]) & 0xffffffff; + s0 = (a >>> 2) | (a << 30); + s0 ^= (a >>> 13) | (a << 19); + s0 ^= (a >>> 22) | (a << 10); + var maj = (a & b) ^ (a & c) ^ (b & c); + var temp2 = (s0 + maj) & 0xffffffff; + h = g + g = f + f = e + e = (d + temp1) & 0xffffffff; + d = c; + c = b; + b = a; + a = (temp1 + temp2) & 0xffffffff; + } + h0 = (h0 + a) & 0xffffffff; + h1 = (h1 + b) & 0xffffffff; + h2 = (h2 + c) & 0xffffffff; + h3 = (h3 + d) & 0xffffffff; + h4 = (h4 + e) & 0xffffffff; + h5 = (h5 + f) & 0xffffffff; + h6 = (h6 + g) & 0xffffffff; + h7 = (h7 + h) & 0xffffffff; + } + var hash = new Uint8Array(32); + for (var i = 0; i < 4; i++) { + hash[i] = (h0 >>> (8 * (3 - i))) & 0xff; + hash[i + 4] = (h1 >>> (8 * (3 - i))) & 0xff; + hash[i + 8] = (h2 >>> (8 * (3 - i))) & 0xff; + hash[i + 12] = (h3 >>> (8 * (3 - i))) & 0xff; + hash[i + 16] = (h4 >>> (8 * (3 - i))) & 0xff; + hash[i + 20] = (h5 >>> (8 * (3 - i))) & 0xff; + hash[i + 24] = (h6 >>> (8 * (3 - i))) & 0xff; + hash[i + 28] = (h7 >>> (8 * (3 - i))) & 0xff; + } + return hash; +} // The hash function returns the hash value as a hex string. // message: the string or byte array to hash -SHA256.hash = function(message) { - var digest = SHA256.digest(message); - var hex = ''; +SHA256.hash = function (message) { + var digest = SHA256.digest(message); + var hex = ''; for (var i = 0; i < digest.length; i++) { var s = '0' + digest[i].toString(16); - hex += s.length > 2 ? s.substring(1) : s; + hex += s.length > 2 ? s.substring(1) : s; } - return hex; + return hex; } - // == Convert to ES6 Module == // -export default SHA256; \ No newline at end of file +export default SHA256; diff --git a/crypto/api/deps/utils.js b/crypto/api/deps/utils.js index 20715934..ae83d18d 100644 --- a/crypto/api/deps/utils.js +++ b/crypto/api/deps/utils.js @@ -1,74 +1,73 @@ -'use strict' const utils = { - int32ToBytes(word) { - var byteArray = [] - for (var b = 0; b < 32; b += 8) { - byteArray.push((word >>> (24 - b % 32)) & 0xFF) - } - return byteArray - }, + int32ToBytes(word) { + var byteArray = [] + for (var b = 0; b < 32; b += 8) { + byteArray.push((word >>> (24 - b % 32)) & 0xFF) + } + return byteArray + }, - stringtoUTF8Array(message) { - if (typeof message === 'string') { - var s = unescape(encodeURIComponent(message)) // UTF-8 - message = new Uint8Array(s.length) - for (var i = 0; i < s.length; i++) { - message[i] = s.charCodeAt(i) & 0xff - } - } - return message - }, - // ...buffers then buffers.foreach and append to buffer1 - appendBuffer(buffer1, buffer2) { - buffer1 = new Uint8Array(buffer1) - buffer2 = new Uint8Array(buffer2) - let tmp = new Uint8Array(buffer1.byteLength + buffer2.byteLength) - tmp.set(buffer1, 0) - tmp.set(buffer2, buffer1.byteLength) - return tmp - }, + stringtoUTF8Array(message) { + if (typeof message === 'string') { + var s = unescape(encodeURIComponent(message)) // UTF-8 + message = new Uint8Array(s.length) + for (var i = 0; i < s.length; i++) { + message[i] = s.charCodeAt(i) & 0xff + } + } + return message + }, + // ...buffers then buffers.foreach and append to buffer1 + appendBuffer(buffer1, buffer2) { + buffer1 = new Uint8Array(buffer1) + buffer2 = new Uint8Array(buffer2) + let tmp = new Uint8Array(buffer1.byteLength + buffer2.byteLength) + tmp.set(buffer1, 0) + tmp.set(buffer2, buffer1.byteLength) + return tmp + }, - int64ToBytes(int64) { - // we want to represent the input as a 8-bytes array - var byteArray = [0, 0, 0, 0, 0, 0, 0, 0] + int64ToBytes(int64) { + // we want to represent the input as a 8-bytes array + var byteArray = [0, 0, 0, 0, 0, 0, 0, 0] - for (var index = 0; index < byteArray.length; index++) { - var byte = int64 & 0xff - byteArray[byteArray.length - index - 1] = byte - int64 = (int64 - byte) / 256 - } + for (var index = 0; index < byteArray.length; index++) { + var byte = int64 & 0xff + byteArray[byteArray.length - index - 1] = byte + int64 = (int64 - byte) / 256 + } - return byteArray - }, + return byteArray + }, - hexToBytes(hexString) { - return new Uint8Array(hexString.match(/.{1,2}/g).map(byte => parseInt(byte, 16))) - }, + hexToBytes(hexString) { + return new Uint8Array(hexString.match(/.{1,2}/g).map(byte => parseInt(byte, 16))) + }, - stringToHex(bytes) { - return bytes.reduce((str, byte) => str + byte.toString(16).padStart(2, '0'), '') - }, + stringToHex(bytes) { + return bytes.reduce((str, byte) => str + byte.toString(16).padStart(2, '0'), '') + }, - equal(buf1, buf2) { - if (buf1.byteLength != buf2.byteLength) return false - var dv1 = new Uint8Array(buf1) - var dv2 = new Uint8Array(buf2) - for (var i = 0; i != buf1.byteLength; i++) { - if (dv1[i] != dv2[i]) return false - } - return true - }, + equal(buf1, buf2) { + if (buf1.byteLength != buf2.byteLength) return false + var dv1 = new Uint8Array(buf1) + var dv2 = new Uint8Array(buf2) + for (var i = 0; i != buf1.byteLength; i++) { + if (dv1[i] != dv2[i]) return false + } + return true + }, - bytesToHex(byteArray) { - var _byteArrayToHex = [] + bytesToHex(byteArray) { + var _byteArrayToHex = [] - for (var index = 0; index < byteArray.length; index++) { - _byteArrayToHex.push((byteArray[index] >>> 4).toString(16)) - _byteArrayToHex.push((byteArray[index] & 15).toString(16)); - } + for (var index = 0; index < byteArray.length; index++) { + _byteArrayToHex.push((byteArray[index] >>> 4).toString(16)) + _byteArrayToHex.push((byteArray[index] & 15).toString(16)); + } - return _byteArrayToHex.join("") - } + return _byteArrayToHex.join("") + } } export default utils diff --git a/crypto/api/fetch-request.js b/crypto/api/fetch-request.js index 6adab74c..7c0201ee 100644 --- a/crypto/api/fetch-request.js +++ b/crypto/api/fetch-request.js @@ -1,4 +1,4 @@ -import {waitForConfig, watchConfig} from '../config.js' +import { waitForConfig, watchConfig } from '../config' let config = {} diff --git a/crypto/api/kdf.js b/crypto/api/kdf.js index 2c64d5d9..c71ef89e 100644 --- a/crypto/api/kdf.js +++ b/crypto/api/kdf.js @@ -1,11 +1,11 @@ -import {store} from '../api_deps.js' -import {stateAwait} from './utils/stateAwait.js' -import {Sha512} from 'asmcrypto.js' -import utils from '../api/deps/utils.js' -import {get, registerTranslateConfig} from '../../core/translate' +import { store } from '../api_deps' +import { stateAwait } from './utils/stateAwait' +import { Sha512 } from 'asmcrypto.js' +import utils from '../api/deps/utils' +import { get, registerTranslateConfig } from '../../core/translate' registerTranslateConfig({ - loader: lang => fetch(`/language/${lang}.json`).then(res => res.json()) + loader: lang => fetch(`/language/${lang}.json`).then(res => res.json()) }) export const kdf = async (seed, salt, status = () => { }) => { diff --git a/crypto/api/registerUsername.js b/crypto/api/registerUsername.js index 1092e756..377e7d15 100644 --- a/crypto/api/registerUsername.js +++ b/crypto/api/registerUsername.js @@ -1,7 +1,7 @@ /** * Not to be confused with register name...this is a special use case */ -import {createTransaction, processTransaction, request} from './api.js' +import { createTransaction, processTransaction, request } from './api' const TX_TYPE = 3 // NAME_REGISTRATION const CHECK_LAST_REF_INTERVAL = 30 * 1000 // err 30 seconds diff --git a/crypto/api/storeWallet.js b/crypto/api/storeWallet.js index f63a2ce2..6e9061a6 100644 --- a/crypto/api/storeWallet.js +++ b/crypto/api/storeWallet.js @@ -1,6 +1,6 @@ -import {AES_CBC, HmacSha512} from 'asmcrypto.js' -import {kdf} from './kdf.js' -import Base58 from './deps/Base58.js' +import { AES_CBC, HmacSha512 } from 'asmcrypto.js' +import { kdf } from './kdf' +import Base58 from './deps/Base58' const getRandomValues = window.crypto ? window.crypto.getRandomValues.bind(window.crypto) : window.msCrypto.getRandomValues.bind(window.msCrypto) diff --git a/crypto/api/tradeRequest.js b/crypto/api/tradeRequest.js index 892c1318..447244f0 100644 --- a/crypto/api/tradeRequest.js +++ b/crypto/api/tradeRequest.js @@ -1,9 +1,9 @@ // Trade Bot -import TradeBotCreateRequest from './transactions/trade-portal/tradebot/TradeBotCreateRequest.js' -import TradeBotRespondRequest from './transactions/trade-portal/tradebot/TradeBotRespondRequest.js' -import signTradeBotTransaction from './transactions/trade-portal/tradebot/signTradeBotTransaction.js' -import DeleteTradeOffer from './transactions/trade-portal/tradeoffer/DeleteTradeOffer.js' -import {request} from './fetch-request' +import TradeBotCreateRequest from './transactions/trade-portal/tradebot/TradeBotCreateRequest' +import TradeBotRespondRequest from './transactions/trade-portal/tradebot/TradeBotRespondRequest' +import signTradeBotTransaction from './transactions/trade-portal/tradebot/signTradeBotTransaction' +import DeleteTradeOffer from './transactions/trade-portal/tradeoffer/DeleteTradeOffer' +import { request } from './fetch-request' // TradeBotCreateRequest export const tradeBotCreateRequest = (requestObject) => { diff --git a/crypto/api/transactions/AirdropTransaction.js b/crypto/api/transactions/AirdropTransaction.js index 04aa8acf..007ed7ff 100644 --- a/crypto/api/transactions/AirdropTransaction.js +++ b/crypto/api/transactions/AirdropTransaction.js @@ -1,5 +1,5 @@ import TransactionBase from './TransactionBase' -import {QORT_DECIMALS} from '../constants' +import { QORT_DECIMALS } from '../constants' export default class PaymentTransaction extends TransactionBase { constructor() { diff --git a/crypto/api/transactions/DeployAtTransaction.js b/crypto/api/transactions/DeployAtTransaction.js index 4b77f21e..2ebfe957 100644 --- a/crypto/api/transactions/DeployAtTransaction.js +++ b/crypto/api/transactions/DeployAtTransaction.js @@ -1,6 +1,6 @@ import TransactionBase from './TransactionBase' -import {store} from '../../api' -import {QORT_DECIMALS} from '../constants' +import { store } from '../../api' +import { QORT_DECIMALS } from '../constants' export default class DeployAtTransaction extends TransactionBase { constructor() { diff --git a/crypto/api/transactions/PaymentTransaction.js b/crypto/api/transactions/PaymentTransaction.js index ad3c023b..df11e5b5 100644 --- a/crypto/api/transactions/PaymentTransaction.js +++ b/crypto/api/transactions/PaymentTransaction.js @@ -1,6 +1,6 @@ import TransactionBase from './TransactionBase' import Base58 from '../deps/Base58' -import {store} from '../../api' +import { store } from '../../api' export default class PaymentTransaction extends TransactionBase { constructor() { diff --git a/crypto/api/transactions/PublicizeTransaction.js b/crypto/api/transactions/PublicizeTransaction.js index 42e5ba50..44660da1 100644 --- a/crypto/api/transactions/PublicizeTransaction.js +++ b/crypto/api/transactions/PublicizeTransaction.js @@ -1,5 +1,5 @@ import ChatBase from './chat/ChatBase' -import {QORT_DECIMALS} from '../constants' +import { QORT_DECIMALS } from '../constants' export default class PublicizeTransaction extends ChatBase { constructor() { @@ -8,21 +8,21 @@ export default class PublicizeTransaction extends ChatBase { this.fee = 0 } - set proofOfWorkNonce(proofOfWorkNonce) { - this._proofOfWorkNonce = this.constructor.utils.int32ToBytes(proofOfWorkNonce) - } + set proofOfWorkNonce(proofOfWorkNonce) { + this._proofOfWorkNonce = this.constructor.utils.int32ToBytes(proofOfWorkNonce) + } - set fee(fee) { - this._fee = fee * QORT_DECIMALS - this._feeBytes = this.constructor.utils.int64ToBytes(this._fee) - } + set fee(fee) { + this._fee = fee * QORT_DECIMALS + this._feeBytes = this.constructor.utils.int64ToBytes(this._fee) + } - get params() { - const params = super.params - params.push( - this._proofOfWorkNonce, - this._feeBytes - ) - return params - } + get params() { + const params = super.params + params.push( + this._proofOfWorkNonce, + this._feeBytes + ) + return params + } } diff --git a/crypto/api/transactions/TransactionBase.js b/crypto/api/transactions/TransactionBase.js index c5a96068..5e327116 100644 --- a/crypto/api/transactions/TransactionBase.js +++ b/crypto/api/transactions/TransactionBase.js @@ -1,4 +1,4 @@ -import {QORT_DECIMALS, TX_TYPES} from '../constants' +import { QORT_DECIMALS, TX_TYPES } from '../constants' import nacl from '../deps/nacl-fast' import Base58 from '../deps/Base58' import utils from '../deps/utils' diff --git a/crypto/api/transactions/TransferPrivsTransaction.js b/crypto/api/transactions/TransferPrivsTransaction.js index b9eaf809..6aaff1b9 100644 --- a/crypto/api/transactions/TransferPrivsTransaction.js +++ b/crypto/api/transactions/TransferPrivsTransaction.js @@ -1,6 +1,6 @@ import TransactionBase from './TransactionBase' -import {store} from '../../api' -import {QORT_DECIMALS} from '../constants' +import { store } from '../../api' +import { QORT_DECIMALS } from '../constants' export default class TransferPrivsTransaction extends TransactionBase { constructor() { diff --git a/crypto/api/transactions/arbitraryV3.js b/crypto/api/transactions/arbitraryV3.js index dd871aac..515b4044 100644 --- a/crypto/api/transactions/arbitraryV3.js +++ b/crypto/api/transactions/arbitraryV3.js @@ -1,38 +1,36 @@ -'use strict' +(function () { + function generateSignatureArbitraryTransactionV3(keyPair, lastReference, service, arbitraryData, fee, timestamp) => { + const data = generateArbitraryTransactionV3Base(keyPair.publicKey, lastReference, service, arbitraryData, fee, timestamp) + return nacl.sign.detached(data, keyPair.privateKey) + } - (function () { - function generateSignatureArbitraryTransactionV3(keyPair, lastReference, service, arbitraryData, fee, timestamp) => { - const data = generateArbitraryTransactionV3Base(keyPair.publicKey, lastReference, service, arbitraryData, fee, timestamp) - return nacl.sign.detached(data, keyPair.privateKey) - } + function generateArbitraryTransactionV3(keyPair, lastReference, service, arbitraryData, fee, timestamp, signature) => { + return appendBuffer(generateArbitraryTransactionV3Base(keyPair.publicKey, lastReference, service, arbitraryData, fee, timestamp), signature) + } - function generateArbitraryTransactionV3(keyPair, lastReference, service, arbitraryData, fee, timestamp, signature) => { - return appendBuffer(generateArbitraryTransactionV3Base(keyPair.publicKey, lastReference, service, arbitraryData, fee, timestamp), signature) - } + function generateArbitraryTransactionV3Base(publicKey, lastReference, service, arbitraryData, fee, timestamp) => { + const txType = TYPES.ARBITRARY_TRANSACTION + const typeBytes = int32ToBytes(txType) + const timestampBytes = int64ToBytes(timestamp) + const feeBytes = int64ToBytes(fee * 100000000) + const serviceBytes = int32ToBytes(service) + const dataSizeBytes = int32ToBytes(arbitraryData.length) + const paymentsLengthBytes = int32ToBytes(0) // Support payments - not yet. - function generateArbitraryTransactionV3Base(publicKey, lastReference, service, arbitraryData, fee, timestamp) => { - const txType = TYPES.ARBITRARY_TRANSACTION - const typeBytes = int32ToBytes(txType) - const timestampBytes = int64ToBytes(timestamp) - const feeBytes = int64ToBytes(fee * 100000000) - const serviceBytes = int32ToBytes(service) - const dataSizeBytes = int32ToBytes(arbitraryData.length) - const paymentsLengthBytes = int32ToBytes(0) // Support payments - not yet. + var data = new Uint8Array() - var data = new Uint8Array() + data = appendBuffer(data, typeBytes) + data = appendBuffer(data, timestampBytes) + data = appendBuffer(data, lastReference) + data = appendBuffer(data, publicKey) + data = appendBuffer(data, paymentsLengthBytes) - data = appendBuffer(data, typeBytes) - data = appendBuffer(data, timestampBytes) - data = appendBuffer(data, lastReference) - data = appendBuffer(data, publicKey) - data = appendBuffer(data, paymentsLengthBytes) + // Here it is necessary to insert the payments, if there are + data = appendBuffer(data, serviceBytes) + data = appendBuffer(data, dataSizeBytes) + data = appendBuffer(data, arbitraryData) + data = appendBuffer(data, feeBytes) - // Here it is necessary to insert the payments, if there are - data = appendBuffer(data, serviceBytes) - data = appendBuffer(data, dataSizeBytes) - data = appendBuffer(data, arbitraryData) - data = appendBuffer(data, feeBytes) - - return data - } - }()) + return data + } +}()) diff --git a/crypto/api/transactions/chat/ChatBase.js b/crypto/api/transactions/chat/ChatBase.js index fe1b26f5..48429c27 100644 --- a/crypto/api/transactions/chat/ChatBase.js +++ b/crypto/api/transactions/chat/ChatBase.js @@ -1,143 +1,143 @@ -import {QORT_DECIMALS, TX_TYPES} from '../../constants' +import { QORT_DECIMALS, TX_TYPES } from '../../constants' import nacl from '../../deps/nacl-fast' import Base58 from '../../deps/Base58' import utils from '../../deps/utils' export default class ChatBase { - static get utils() { - return utils - } + static get utils() { + return utils + } - static get nacl() { - return nacl - } + static get nacl() { + return nacl + } - static get Base58() { - return Base58 - } + static get Base58() { + return Base58 + } - constructor() { - this.fee = 0 - this.groupID = 0 - this.tests = [ - () => { - if (!(this._type >= 1 && this._type in TX_TYPES)) { - return 'Invalid type: ' + this.type - } - return true - }, - () => { - if (this._fee < 0) { - return 'Invalid fee: ' + this._fee / QORT_DECIMALS - } - return true - }, - () => { - if (this._groupID < 0 || !Number.isInteger(this._groupID)) { - return 'Invalid groupID: ' + this._groupID - } - return true - }, - () => { - if (!(new Date(this._timestamp)).getTime() > 0) { - return 'Invalid timestamp: ' + this._timestamp - } - return true - }, - () => { - if (!(this._lastReference instanceof Uint8Array && this._lastReference.byteLength == 64)) { - return 'Invalid last reference: ' + this._lastReference - } - return true - }, - () => { - if (!(this._keyPair)) { - return 'keyPair must be specified' - } - if (!(this._keyPair.publicKey instanceof Uint8Array && this._keyPair.publicKey.byteLength === 32)) { - return 'Invalid publicKey' - } - if (!(this._keyPair.privateKey instanceof Uint8Array && this._keyPair.privateKey.byteLength === 64)) { - return 'Invalid privateKey' - } - return true - } - ] - } + constructor() { + this.fee = 0 + this.groupID = 0 + this.tests = [ + () => { + if (!(this._type >= 1 && this._type in TX_TYPES)) { + return 'Invalid type: ' + this.type + } + return true + }, + () => { + if (this._fee < 0) { + return 'Invalid fee: ' + this._fee / QORT_DECIMALS + } + return true + }, + () => { + if (this._groupID < 0 || !Number.isInteger(this._groupID)) { + return 'Invalid groupID: ' + this._groupID + } + return true + }, + () => { + if (!(new Date(this._timestamp)).getTime() > 0) { + return 'Invalid timestamp: ' + this._timestamp + } + return true + }, + () => { + if (!(this._lastReference instanceof Uint8Array && this._lastReference.byteLength == 64)) { + return 'Invalid last reference: ' + this._lastReference + } + return true + }, + () => { + if (!(this._keyPair)) { + return 'keyPair must be specified' + } + if (!(this._keyPair.publicKey instanceof Uint8Array && this._keyPair.publicKey.byteLength === 32)) { + return 'Invalid publicKey' + } + if (!(this._keyPair.privateKey instanceof Uint8Array && this._keyPair.privateKey.byteLength === 64)) { + return 'Invalid privateKey' + } + return true + } + ] + } - set keyPair(keyPair) { - this._keyPair = keyPair - } + set keyPair(keyPair) { + this._keyPair = keyPair + } - set type(type) { - this.typeText = TX_TYPES[type] - this._type = type - this._typeBytes = this.constructor.utils.int32ToBytes(this._type) - } + set type(type) { + this.typeText = TX_TYPES[type] + this._type = type + this._typeBytes = this.constructor.utils.int32ToBytes(this._type) + } - set groupID(groupID) { - this._groupID = groupID - this._groupIDBytes = this.constructor.utils.int32ToBytes(this._groupID) - } + set groupID(groupID) { + this._groupID = groupID + this._groupIDBytes = this.constructor.utils.int32ToBytes(this._groupID) + } - set timestamp(timestamp) { - this._timestamp = timestamp - this._timestampBytes = this.constructor.utils.int64ToBytes(this._timestamp) - } + set timestamp(timestamp) { + this._timestamp = timestamp + this._timestampBytes = this.constructor.utils.int64ToBytes(this._timestamp) + } - set fee(fee) { - this._fee = fee * QORT_DECIMALS - this._feeBytes = this.constructor.utils.int64ToBytes(this._fee) - } + set fee(fee) { + this._fee = fee * QORT_DECIMALS + this._feeBytes = this.constructor.utils.int64ToBytes(this._fee) + } - set lastReference(lastReference) { - this._lastReference = lastReference instanceof Uint8Array ? lastReference : this.constructor.Base58.decode(lastReference) - } + set lastReference(lastReference) { + this._lastReference = lastReference instanceof Uint8Array ? lastReference : this.constructor.Base58.decode(lastReference) + } - get params() { - return [ - this._typeBytes, - this._timestampBytes, - this._groupIDBytes, - this._lastReference, - this._keyPair.publicKey - ] - } + get params() { + return [ + this._typeBytes, + this._timestampBytes, + this._groupIDBytes, + this._lastReference, + this._keyPair.publicKey + ] + } - get chatBytes() { - const isValid = this.validParams() - if (!isValid.valid) { - throw new Error(isValid.message) - } + get chatBytes() { + const isValid = this.validParams() + if (!isValid.valid) { + throw new Error(isValid.message) + } - let result = new Uint8Array() + let result = new Uint8Array() - this.params.forEach(item => { - result = this.constructor.utils.appendBuffer(result, item) - }) + this.params.forEach(item => { + result = this.constructor.utils.appendBuffer(result, item) + }) - this._chatBytes = result + this._chatBytes = result - return this._chatBytes - } + return this._chatBytes + } - validParams() { - let finalResult = { - valid: true - } + validParams() { + let finalResult = { + valid: true + } - this.tests.some(test => { - const result = test() - if (result !== true) { - finalResult = { - valid: false, - message: result - } - return true - } - }) + this.tests.some(test => { + const result = test() + if (result !== true) { + finalResult = { + valid: false, + message: result + } + return true + } + }) - return finalResult - } + return finalResult + } } diff --git a/crypto/api/transactions/chat/ChatTransaction.js b/crypto/api/transactions/chat/ChatTransaction.js index 1b048aa3..96ac6471 100644 --- a/crypto/api/transactions/chat/ChatTransaction.js +++ b/crypto/api/transactions/chat/ChatTransaction.js @@ -1,8 +1,8 @@ import ChatBase from './ChatBase' import nacl from '../../deps/nacl-fast' import ed2curve from '../../deps/ed2curve' -import {Sha256} from 'asmcrypto.js' -import {CHAT_REFERENCE_FEATURE_TRIGGER_TIMESTAMP} from '../../constants' +import { Sha256 } from 'asmcrypto.js' +import { CHAT_REFERENCE_FEATURE_TRIGGER_TIMESTAMP } from '../../constants' export default class ChatTransaction extends ChatBase { constructor() { diff --git a/crypto/api/transactions/chat/GroupChatTransaction.js b/crypto/api/transactions/chat/GroupChatTransaction.js index bb69f442..e58bc1d0 100644 --- a/crypto/api/transactions/chat/GroupChatTransaction.js +++ b/crypto/api/transactions/chat/GroupChatTransaction.js @@ -1,5 +1,5 @@ import ChatBase from './ChatBase' -import {CHAT_REFERENCE_FEATURE_TRIGGER_TIMESTAMP} from '../../constants' +import { CHAT_REFERENCE_FEATURE_TRIGGER_TIMESTAMP } from '../../constants' export default class GroupChatTransaction extends ChatBase { constructor() { diff --git a/crypto/api/transactions/chat/decryptChatMessage.js b/crypto/api/transactions/chat/decryptChatMessage.js index 8f4b05df..0a88b697 100644 --- a/crypto/api/transactions/chat/decryptChatMessage.js +++ b/crypto/api/transactions/chat/decryptChatMessage.js @@ -1,7 +1,7 @@ import nacl from '../../deps/nacl-fast' import Base58 from '../../deps/Base58' import ed2curve from '../../deps/ed2curve' -import {Sha256} from 'asmcrypto.js' +import { Sha256 } from 'asmcrypto.js' export const decryptChatMessage = (encryptedMessage, privateKey, recipientPublicKey, lastReference) => { let _encryptedMessage = Base58.decode(encryptedMessage) diff --git a/crypto/api/transactions/groups/AddGroupAdminTransaction.js b/crypto/api/transactions/groups/AddGroupAdminTransaction.js index 761e0029..003100aa 100644 --- a/crypto/api/transactions/groups/AddGroupAdminTransaction.js +++ b/crypto/api/transactions/groups/AddGroupAdminTransaction.js @@ -1,5 +1,5 @@ import TransactionBase from '../TransactionBase' -import {QORT_DECIMALS} from '../../constants' +import { QORT_DECIMALS } from '../../constants' export default class AddGroupAdminTransaction extends TransactionBase { constructor() { diff --git a/crypto/api/transactions/groups/CancelGroupBanTransaction.js b/crypto/api/transactions/groups/CancelGroupBanTransaction.js index f0b11fa1..604a5f8c 100644 --- a/crypto/api/transactions/groups/CancelGroupBanTransaction.js +++ b/crypto/api/transactions/groups/CancelGroupBanTransaction.js @@ -1,5 +1,5 @@ import TransactionBase from '../TransactionBase' -import {QORT_DECIMALS} from '../../constants' +import { QORT_DECIMALS } from '../../constants' export default class CancelGroupBanTransaction extends TransactionBase { constructor() { diff --git a/crypto/api/transactions/groups/CancelGroupInviteTransaction.js b/crypto/api/transactions/groups/CancelGroupInviteTransaction.js index 8dccb6fa..a3023eb4 100644 --- a/crypto/api/transactions/groups/CancelGroupInviteTransaction.js +++ b/crypto/api/transactions/groups/CancelGroupInviteTransaction.js @@ -1,5 +1,5 @@ import TransactionBase from '../TransactionBase' -import {QORT_DECIMALS} from '../../constants' +import { QORT_DECIMALS } from '../../constants' export default class CancelGroupInviteTransaction extends TransactionBase { constructor() { diff --git a/crypto/api/transactions/groups/CreateGroupTransaction.js b/crypto/api/transactions/groups/CreateGroupTransaction.js index b81e47ee..13c8220c 100644 --- a/crypto/api/transactions/groups/CreateGroupTransaction.js +++ b/crypto/api/transactions/groups/CreateGroupTransaction.js @@ -1,5 +1,5 @@ import TransactionBase from '../TransactionBase' -import {QORT_DECIMALS} from '../../constants' +import { QORT_DECIMALS } from '../../constants' export default class CreateGroupTransaction extends TransactionBase { constructor() { diff --git a/crypto/api/transactions/groups/GroupBanTransaction.js b/crypto/api/transactions/groups/GroupBanTransaction.js index ab679f7a..6bd88b87 100644 --- a/crypto/api/transactions/groups/GroupBanTransaction.js +++ b/crypto/api/transactions/groups/GroupBanTransaction.js @@ -1,5 +1,5 @@ import TransactionBase from '../TransactionBase' -import {QORT_DECIMALS} from '../../constants' +import { QORT_DECIMALS } from '../../constants' export default class GroupBanTransaction extends TransactionBase { constructor() { diff --git a/crypto/api/transactions/groups/GroupInviteTransaction.js b/crypto/api/transactions/groups/GroupInviteTransaction.js index 20ce9bed..8e3823a6 100644 --- a/crypto/api/transactions/groups/GroupInviteTransaction.js +++ b/crypto/api/transactions/groups/GroupInviteTransaction.js @@ -1,5 +1,5 @@ import TransactionBase from '../TransactionBase' -import {QORT_DECIMALS} from '../../constants' +import { QORT_DECIMALS } from '../../constants' export default class GroupInviteTransaction extends TransactionBase { constructor() { diff --git a/crypto/api/transactions/groups/GroupKickTransaction.js b/crypto/api/transactions/groups/GroupKickTransaction.js index 77391943..6c755ac0 100644 --- a/crypto/api/transactions/groups/GroupKickTransaction.js +++ b/crypto/api/transactions/groups/GroupKickTransaction.js @@ -1,5 +1,5 @@ import TransactionBase from '../TransactionBase' -import {QORT_DECIMALS} from '../../constants' +import { QORT_DECIMALS } from '../../constants' export default class GroupKickTransaction extends TransactionBase { constructor() { diff --git a/crypto/api/transactions/groups/JoinGroupTransaction.js b/crypto/api/transactions/groups/JoinGroupTransaction.js index 4db9cb73..7c715b65 100644 --- a/crypto/api/transactions/groups/JoinGroupTransaction.js +++ b/crypto/api/transactions/groups/JoinGroupTransaction.js @@ -1,5 +1,5 @@ import TransactionBase from '../TransactionBase' -import {QORT_DECIMALS} from '../../constants' +import { QORT_DECIMALS } from '../../constants' export default class JoinGroupTransaction extends TransactionBase { constructor() { diff --git a/crypto/api/transactions/groups/LeaveGroupTransaction.js b/crypto/api/transactions/groups/LeaveGroupTransaction.js index 104cb9fe..aa8303a5 100644 --- a/crypto/api/transactions/groups/LeaveGroupTransaction.js +++ b/crypto/api/transactions/groups/LeaveGroupTransaction.js @@ -1,5 +1,5 @@ import TransactionBase from '../TransactionBase' -import {QORT_DECIMALS} from '../../constants' +import { QORT_DECIMALS } from '../../constants' export default class LeaveGroupTransaction extends TransactionBase { constructor() { diff --git a/crypto/api/transactions/groups/RemoveGroupAdminTransaction.js b/crypto/api/transactions/groups/RemoveGroupAdminTransaction.js index d0aff6a3..a648ae6f 100644 --- a/crypto/api/transactions/groups/RemoveGroupAdminTransaction.js +++ b/crypto/api/transactions/groups/RemoveGroupAdminTransaction.js @@ -1,5 +1,5 @@ import TransactionBase from '../TransactionBase' -import {QORT_DECIMALS} from '../../constants' +import { QORT_DECIMALS } from '../../constants' export default class RemoveGroupAdminTransaction extends TransactionBase { constructor() { diff --git a/crypto/api/transactions/groups/UpdateGroupTransaction.js b/crypto/api/transactions/groups/UpdateGroupTransaction.js index d080c24f..43926245 100644 --- a/crypto/api/transactions/groups/UpdateGroupTransaction.js +++ b/crypto/api/transactions/groups/UpdateGroupTransaction.js @@ -1,5 +1,5 @@ import TransactionBase from '../TransactionBase' -import {QORT_DECIMALS} from '../../constants' +import { QORT_DECIMALS } from '../../constants' export default class UpdateGroupTransaction extends TransactionBase { constructor() { diff --git a/crypto/api/transactions/names/BuyNameTransacion.js b/crypto/api/transactions/names/BuyNameTransacion.js index d41a7ab8..7e18834d 100644 --- a/crypto/api/transactions/names/BuyNameTransacion.js +++ b/crypto/api/transactions/names/BuyNameTransacion.js @@ -1,5 +1,5 @@ import TransactionBase from '../TransactionBase' -import {QORT_DECIMALS} from '../../constants' +import { QORT_DECIMALS } from '../../constants' export default class BuyNameTransacion extends TransactionBase { constructor() { diff --git a/crypto/api/transactions/names/CancelSellNameTransacion.js b/crypto/api/transactions/names/CancelSellNameTransacion.js index 5d53b3a7..483b6982 100644 --- a/crypto/api/transactions/names/CancelSellNameTransacion.js +++ b/crypto/api/transactions/names/CancelSellNameTransacion.js @@ -1,5 +1,5 @@ import TransactionBase from '../TransactionBase' -import {QORT_DECIMALS} from '../../constants' +import { QORT_DECIMALS } from '../../constants' export default class CancelSellNameTransacion extends TransactionBase { constructor() { diff --git a/crypto/api/transactions/names/RegisterNameTransaction.js b/crypto/api/transactions/names/RegisterNameTransaction.js index 7240e281..7929d367 100644 --- a/crypto/api/transactions/names/RegisterNameTransaction.js +++ b/crypto/api/transactions/names/RegisterNameTransaction.js @@ -1,5 +1,5 @@ import TransactionBase from '../TransactionBase' -import {QORT_DECIMALS} from '../../constants' +import { QORT_DECIMALS } from '../../constants' export default class RegisterNameTransaction extends TransactionBase { constructor() { diff --git a/crypto/api/transactions/names/SellNameTransacion.js b/crypto/api/transactions/names/SellNameTransacion.js index f93ea901..38db5a81 100644 --- a/crypto/api/transactions/names/SellNameTransacion.js +++ b/crypto/api/transactions/names/SellNameTransacion.js @@ -1,5 +1,5 @@ import TransactionBase from '../TransactionBase' -import {QORT_DECIMALS} from '../../constants' +import { QORT_DECIMALS } from '../../constants' export default class SellNameTransacion extends TransactionBase { constructor() { diff --git a/crypto/api/transactions/names/UpdateNameTransaction.js b/crypto/api/transactions/names/UpdateNameTransaction.js index c9f5aebe..89faf7d2 100644 --- a/crypto/api/transactions/names/UpdateNameTransaction.js +++ b/crypto/api/transactions/names/UpdateNameTransaction.js @@ -1,5 +1,5 @@ import TransactionBase from '../TransactionBase' -import {QORT_DECIMALS} from '../../constants' +import { QORT_DECIMALS } from '../../constants' export default class UpdateNameTransaction extends TransactionBase { constructor() { diff --git a/crypto/api/transactions/polls/CreatePollTransaction.js b/crypto/api/transactions/polls/CreatePollTransaction.js index fa01e9b1..07815458 100644 --- a/crypto/api/transactions/polls/CreatePollTransaction.js +++ b/crypto/api/transactions/polls/CreatePollTransaction.js @@ -1,5 +1,5 @@ import TransactionBase from '../TransactionBase' -import {QORT_DECIMALS} from '../../constants' +import { QORT_DECIMALS } from '../../constants' export default class CreatePollTransaction extends TransactionBase { constructor() { @@ -35,7 +35,7 @@ export default class CreatePollTransaction extends TransactionBase { this._options.push({ length: optionLength, bytes: optionBytes }) } - set feeDialog(feeDialog){ + set feeDialog(feeDialog) { this._feeDialog = feeDialog } @@ -106,7 +106,7 @@ export default class CreatePollTransaction extends TransactionBase { params.push(this._options[i].length, this._options[i].bytes) } - params.push(this._feeBytes); + params.push(this._feeBytes) return params } diff --git a/crypto/api/transactions/polls/VoteOnPollTransaction.js b/crypto/api/transactions/polls/VoteOnPollTransaction.js index 83a7eda9..21ce36e6 100644 --- a/crypto/api/transactions/polls/VoteOnPollTransaction.js +++ b/crypto/api/transactions/polls/VoteOnPollTransaction.js @@ -1,5 +1,5 @@ import TransactionBase from '../TransactionBase' -import {QORT_DECIMALS} from '../../constants' +import { QORT_DECIMALS } from '../../constants' export default class VoteOnPollTransaction extends TransactionBase { constructor() { @@ -20,7 +20,7 @@ export default class VoteOnPollTransaction extends TransactionBase { ` } - set feeDialog(feeDialog){ + set feeDialog(feeDialog) { this._feeDialog = feeDialog } diff --git a/crypto/api/transactions/registerName_dnsthing.js b/crypto/api/transactions/registerName_dnsthing.js index 06210cc4..c32be3a2 100644 --- a/crypto/api/transactions/registerName_dnsthing.js +++ b/crypto/api/transactions/registerName_dnsthing.js @@ -1,36 +1,34 @@ -'use strict' +(function () { + function generateSignatureRegisterNameTransaction(keyPair, lastReference, owner, name, value, fee, timestamp) => { + const data = generateRegisterNameTransactionBase(keyPair.publicKey, lastReference, owner, name, value, fee, timestamp) + return nacl.sign.detached(data, keyPair.privateKey) + } - (function () { - function generateSignatureRegisterNameTransaction(keyPair, lastReference, owner, name, value, fee, timestamp) => { - const data = generateRegisterNameTransactionBase(keyPair.publicKey, lastReference, owner, name, value, fee, timestamp) - return nacl.sign.detached(data, keyPair.privateKey) - } + function generateRegisterNameTransaction(keyPair, lastReference, owner, name, value, fee, timestamp, signature) => { + return appendBuffer(generateRegisterNameTransactionBase(keyPair.publicKey, lastReference, owner, name, value, fee, timestamp), signature) + } - function generateRegisterNameTransaction(keyPair, lastReference, owner, name, value, fee, timestamp, signature) => { - return appendBuffer(generateRegisterNameTransactionBase(keyPair.publicKey, lastReference, owner, name, value, fee, timestamp), signature) - } + function generateRegisterNameTransactionBase(publicKey, lastReference, owner, name, value, fee, timestamp) => { + const txType = TYPES.REGISTER_NAME_TRANSACTION + const typeBytes = int32ToBytes(txType) + const timestampBytes = int64ToBytes(timestamp) + const feeBytes = int64ToBytes(fee * 100000000) + const nameSizeBytes = int32ToBytes(name.length) + const valueSizeBytes = int32ToBytes(value.length) - function generateRegisterNameTransactionBase(publicKey, lastReference, owner, name, value, fee, timestamp) => { - const txType = TYPES.REGISTER_NAME_TRANSACTION - const typeBytes = int32ToBytes(txType) - const timestampBytes = int64ToBytes(timestamp) - const feeBytes = int64ToBytes(fee * 100000000) - const nameSizeBytes = int32ToBytes(name.length) - const valueSizeBytes = int32ToBytes(value.length) + let data = new Uint8Array() - let data = new Uint8Array() + data = appendBuffer(data, typeBytes) + data = appendBuffer(data, timestampBytes) + data = appendBuffer(data, lastReference) + data = appendBuffer(data, publicKey) + data = appendBuffer(data, owner) + data = appendBuffer(data, nameSizeBytes) + data = appendBuffer(data, name) + data = appendBuffer(data, valueSizeBytes) + data = appendBuffer(data, value) + data = appendBuffer(data, feeBytes) - data = appendBuffer(data, typeBytes) - data = appendBuffer(data, timestampBytes) - data = appendBuffer(data, lastReference) - data = appendBuffer(data, publicKey) - data = appendBuffer(data, owner) - data = appendBuffer(data, nameSizeBytes) - data = appendBuffer(data, name) - data = appendBuffer(data, valueSizeBytes) - data = appendBuffer(data, value) - data = appendBuffer(data, feeBytes) - - return data - } - }()) + return data + } +}()) diff --git a/crypto/api/transactions/reward-share/RemoveRewardShareTransaction.js b/crypto/api/transactions/reward-share/RemoveRewardShareTransaction.js index d16ff579..fe4ecc98 100644 --- a/crypto/api/transactions/reward-share/RemoveRewardShareTransaction.js +++ b/crypto/api/transactions/reward-share/RemoveRewardShareTransaction.js @@ -1,7 +1,7 @@ import TransactionBase from '../TransactionBase' import publicKeyToAddress from '../../wallet/publicKeyToAddress' -import {Base58} from '../../deps/deps' -import {DYNAMIC_FEE_TIMESTAMP} from '../../constants' +import { Base58 } from '../../deps/deps' +import { DYNAMIC_FEE_TIMESTAMP } from '../../constants' export default class RemoveRewardShareTransaction extends TransactionBase { constructor() { diff --git a/crypto/api/transactions/reward-share/RewardShareTransaction.js b/crypto/api/transactions/reward-share/RewardShareTransaction.js index 7033417e..b31e24e0 100644 --- a/crypto/api/transactions/reward-share/RewardShareTransaction.js +++ b/crypto/api/transactions/reward-share/RewardShareTransaction.js @@ -2,8 +2,8 @@ import publicKeyToAddress from '../../wallet/publicKeyToAddress' import TransactionBase from '../TransactionBase' import nacl from '../../deps/nacl-fast' import ed2curve from '../../deps/ed2curve' -import {Sha256} from 'asmcrypto.js' -import {DYNAMIC_FEE_TIMESTAMP} from '../../constants' +import { Sha256 } from 'asmcrypto.js' +import { DYNAMIC_FEE_TIMESTAMP } from '../../constants' export default class RewardShareTransaction extends TransactionBase { constructor() { diff --git a/crypto/api/utils/randomBase58Generator.js b/crypto/api/utils/randomBase58Generator.js index 57e6b0aa..1cc21c7a 100644 --- a/crypto/api/utils/randomBase58Generator.js +++ b/crypto/api/utils/randomBase58Generator.js @@ -1,11 +1,11 @@ export const randomBase58Generator = (digits) => { - digits = digits || 0 - let base58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'.split('') - let result = '' - let char - while (result.length < digits) { - char = base58[Math.random() * 57 >> 0] - if (result.indexOf(char) === -1) result += char - } - return result + digits = digits || 0 + let base58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'.split('') + let result = '' + let char + while (result.length < digits) { + char = base58[Math.random() * 57 >> 0] + if (result.indexOf(char) === -1) result += char + } + return result } diff --git a/crypto/api/utils/stateAwait.js b/crypto/api/utils/stateAwait.js index 666eb0db..800663b5 100644 --- a/crypto/api/utils/stateAwait.js +++ b/crypto/api/utils/stateAwait.js @@ -1,31 +1,31 @@ -import {store} from '../../api.js' +import { store } from '../../api' let subscriptions = [] // Have to wait with init because something import stateAwait before the store gets initialized let initialized = false const init = () => { - initialized = true - store.subscribe(() => { - const state = store.getState() + initialized = true + store.subscribe(() => { + const state = store.getState() - subscriptions = subscriptions.filter(fn => fn(state)) - }) + subscriptions = subscriptions.filter(fn => fn(state)) + }) } export const stateAwait = fn => { - return new Promise((resolve, reject) => { - // Check immediately...then if not true store it - if (!initialized) { - init() - } - if (fn(store.getState())) resolve() - subscriptions.push(state => { - if (fn(state)) { - resolve() - return true - } - return false - }) - }) + return new Promise((resolve, reject) => { + // Check immediately...then if not true store it + if (!initialized) { + init() + } + if (fn(store.getState())) resolve() + subscriptions.push(state => { + if (fn(state)) { + resolve() + return true + } + return false + }) + }) } diff --git a/crypto/api/wallet/base58PublicKeyToAddress.js b/crypto/api/wallet/base58PublicKeyToAddress.js index 6ed36383..8b20cb51 100644 --- a/crypto/api/wallet/base58PublicKeyToAddress.js +++ b/crypto/api/wallet/base58PublicKeyToAddress.js @@ -1,5 +1,5 @@ import publicKeyToAddress from './publicKeyToAddress' -import Base58 from '../deps/Base58.js' +import Base58 from '../deps/Base58' export const base58PublicKeyToAddress = (base58pubkey, qora = false) => { const decodePubKey = Base58.decode(base58pubkey) diff --git a/crypto/api/wallet/publicKeyToAddress.js b/crypto/api/wallet/publicKeyToAddress.js index 67954a0a..7852393f 100644 --- a/crypto/api/wallet/publicKeyToAddress.js +++ b/crypto/api/wallet/publicKeyToAddress.js @@ -1,10 +1,10 @@ -import Base58 from '../deps/Base58.js' -import BROKEN_RIPEMD160 from '../deps/broken-ripemd160.js' -import RIPEMD160 from '../deps/ripemd160.js' -import utils from '../deps/utils.js' -import {ADDRESS_VERSION} from '../constants.js' -import {Buffer} from 'buffer' -import {Sha256} from 'asmcrypto.js' +import Base58 from '../deps/Base58' +import BROKEN_RIPEMD160 from '../deps/broken-ripemd160' +import RIPEMD160 from '../deps/ripemd160' +import utils from '../deps/utils' +import { ADDRESS_VERSION } from '../constants' +import { Buffer } from 'buffer' +import { Sha256 } from 'asmcrypto.js' const repeatSHA256 = (passphrase, hashes) => { let hash = passphrase diff --git a/crypto/api/wallet/validateAddress.js b/crypto/api/wallet/validateAddress.js index 59d016cc..1dc9b1b5 100644 --- a/crypto/api/wallet/validateAddress.js +++ b/crypto/api/wallet/validateAddress.js @@ -1,8 +1,8 @@ -import Base58 from '../deps/Base58.js' +import Base58 from '../deps/Base58' export const validateAddress = (address) => { const decodePubKey = Base58.decode(address) - return decodePubKey instanceof Uint8Array && decodePubKey.length == 25; + return decodePubKey instanceof Uint8Array && decodePubKey.length == 25 } diff --git a/crypto/config.js b/crypto/config.js index 375b5bd8..bedeca43 100644 --- a/crypto/config.js +++ b/crypto/config.js @@ -1,4 +1,4 @@ -import {store} from './api.js' +import { store } from './api' let config = false let loaded = false