react-native-quick-crypto 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +84 -0
- package/android/.DS_Store +0 -0
- package/android/CMakeLists.txt +117 -0
- package/android/build.gradle +367 -0
- package/android/gradle/.DS_Store +0 -0
- package/android/gradle/wrapper/gradle-wrapper.jar +0 -0
- package/android/gradle/wrapper/gradle-wrapper.properties +5 -0
- package/android/gradle.properties +6 -0
- package/android/gradlew +183 -0
- package/android/gradlew.bat +100 -0
- package/android/src/.DS_Store +0 -0
- package/android/src/main/.DS_Store +0 -0
- package/android/src/main/AndroidManifest.xml +4 -0
- package/android/src/main/cpp/cpp-adapter.cpp +60 -0
- package/android/src/main/java/.DS_Store +0 -0
- package/android/src/main/java/com/.DS_Store +0 -0
- package/android/src/main/java/com/reactnativequickcrypto/QuickCryptoModule.java +70 -0
- package/android/src/main/java/com/reactnativequickcrypto/QuickCryptoPackage.java +26 -0
- package/cpp/.DS_Store +0 -0
- package/cpp/Cipher/MGLCipherHostObject.cpp +632 -0
- package/cpp/Cipher/MGLCipherHostObject.h +90 -0
- package/cpp/Cipher/MGLCreateCipherInstaller.cpp +74 -0
- package/cpp/Cipher/MGLCreateCipherInstaller.h +17 -0
- package/cpp/Cipher/MGLCreateDecipherInstaller.cpp +74 -0
- package/cpp/Cipher/MGLCreateDecipherInstaller.h +17 -0
- package/cpp/HMAC/MGLHmacHostObject.cpp +95 -0
- package/cpp/HMAC/MGLHmacHostObject.h +39 -0
- package/cpp/HMAC/MGLHmacInstaller.cpp +43 -0
- package/cpp/HMAC/MGLHmacInstaller.h +20 -0
- package/cpp/Hash/MGLHashHostObject.cpp +147 -0
- package/cpp/Hash/MGLHashHostObject.h +53 -0
- package/cpp/Hash/MGLHashInstaller.cpp +46 -0
- package/cpp/Hash/MGLHashInstaller.h +20 -0
- package/cpp/JSIUtils/MGLJSIMacros.h +37 -0
- package/cpp/JSIUtils/MGLSmartHostObject.cpp +43 -0
- package/cpp/JSIUtils/MGLSmartHostObject.h +46 -0
- package/cpp/JSIUtils/MGLThreadAwareHostObject.cpp +24 -0
- package/cpp/JSIUtils/MGLThreadAwareHostObject.h +43 -0
- package/cpp/JSIUtils/MGLTypedArray.cpp +325 -0
- package/cpp/JSIUtils/MGLTypedArray.h +160 -0
- package/cpp/MGLQuickCryptoHostObject.cpp +64 -0
- package/cpp/MGLQuickCryptoHostObject.h +30 -0
- package/cpp/Random/MGLRandomHostObject.cpp +89 -0
- package/cpp/Random/MGLRandomHostObject.h +27 -0
- package/cpp/Utils/MGLDispatchQueue.cpp +75 -0
- package/cpp/Utils/MGLDispatchQueue.h +55 -0
- package/cpp/Utils/logs.h +38 -0
- package/cpp/fastpbkdf2/MGLPbkdf2HostObject.cpp +164 -0
- package/cpp/fastpbkdf2/MGLPbkdf2HostObject.h +29 -0
- package/cpp/fastpbkdf2/fastpbkdf2.c +352 -0
- package/cpp/fastpbkdf2/fastpbkdf2.h +68 -0
- package/ios/.DS_Store +0 -0
- package/ios/QuickCrypto.xcodeproj/project.pbxproj +274 -0
- package/ios/QuickCryptoModule.h +5 -0
- package/ios/QuickCryptoModule.mm +42 -0
- package/lib/.DS_Store +0 -0
- package/lib/commonjs/Cipher.js +293 -0
- package/lib/commonjs/Cipher.js.map +1 -0
- package/lib/commonjs/Hash.js +102 -0
- package/lib/commonjs/Hash.js.map +1 -0
- package/lib/commonjs/Hmac.js +104 -0
- package/lib/commonjs/Hmac.js.map +1 -0
- package/lib/commonjs/NativeQuickCrypto/Cipher.js +6 -0
- package/lib/commonjs/NativeQuickCrypto/Cipher.js.map +1 -0
- package/lib/commonjs/NativeQuickCrypto/NativeQuickCrypto.js +61 -0
- package/lib/commonjs/NativeQuickCrypto/NativeQuickCrypto.js.map +1 -0
- package/lib/commonjs/NativeQuickCrypto/hash.js +2 -0
- package/lib/commonjs/NativeQuickCrypto/hash.js.map +1 -0
- package/lib/commonjs/NativeQuickCrypto/hmac.js +2 -0
- package/lib/commonjs/NativeQuickCrypto/hmac.js.map +1 -0
- package/lib/commonjs/NativeQuickCrypto/pbkdf2.js +2 -0
- package/lib/commonjs/NativeQuickCrypto/pbkdf2.js.map +1 -0
- package/lib/commonjs/NativeQuickCrypto/random.js +2 -0
- package/lib/commonjs/NativeQuickCrypto/random.js.map +1 -0
- package/lib/commonjs/QuickCrypto.js +35 -0
- package/lib/commonjs/QuickCrypto.js.map +1 -0
- package/lib/commonjs/Utils.js +152 -0
- package/lib/commonjs/Utils.js.map +1 -0
- package/lib/commonjs/index.js +19 -0
- package/lib/commonjs/index.js.map +1 -0
- package/lib/commonjs/pbkdf2.js +64 -0
- package/lib/commonjs/pbkdf2.js.map +1 -0
- package/lib/commonjs/random.js +213 -0
- package/lib/commonjs/random.js.map +1 -0
- package/lib/module/Cipher.js +287 -0
- package/lib/module/Cipher.js.map +1 -0
- package/lib/module/Hash.js +87 -0
- package/lib/module/Hash.js.map +1 -0
- package/lib/module/Hmac.js +90 -0
- package/lib/module/Hmac.js.map +1 -0
- package/lib/module/NativeQuickCrypto/Cipher.js +2 -0
- package/lib/module/NativeQuickCrypto/Cipher.js.map +1 -0
- package/lib/module/NativeQuickCrypto/NativeQuickCrypto.js +53 -0
- package/lib/module/NativeQuickCrypto/NativeQuickCrypto.js.map +1 -0
- package/lib/module/NativeQuickCrypto/hash.js +2 -0
- package/lib/module/NativeQuickCrypto/hash.js.map +1 -0
- package/lib/module/NativeQuickCrypto/hmac.js +2 -0
- package/lib/module/NativeQuickCrypto/hmac.js.map +1 -0
- package/lib/module/NativeQuickCrypto/pbkdf2.js +2 -0
- package/lib/module/NativeQuickCrypto/pbkdf2.js.map +1 -0
- package/lib/module/NativeQuickCrypto/random.js +2 -0
- package/lib/module/NativeQuickCrypto/random.js.map +1 -0
- package/lib/module/QuickCrypto.js +18 -0
- package/lib/module/QuickCrypto.js.map +1 -0
- package/lib/module/Utils.js +131 -0
- package/lib/module/Utils.js.map +1 -0
- package/lib/module/index.js +2 -0
- package/lib/module/index.js.map +1 -0
- package/lib/module/pbkdf2.js +51 -0
- package/lib/module/pbkdf2.js.map +1 -0
- package/lib/module/random.js +190 -0
- package/lib/module/random.js.map +1 -0
- package/lib/typescript/Cipher.d.ts +30 -0
- package/lib/typescript/Hash.d.ts +44 -0
- package/lib/typescript/Hmac.d.ts +37 -0
- package/lib/typescript/NativeQuickCrypto/Cipher.d.ts +22 -0
- package/lib/typescript/NativeQuickCrypto/NativeQuickCrypto.d.ts +19 -0
- package/lib/typescript/NativeQuickCrypto/hash.d.ts +6 -0
- package/lib/typescript/NativeQuickCrypto/hmac.d.ts +5 -0
- package/lib/typescript/NativeQuickCrypto/pbkdf2.d.ts +4 -0
- package/lib/typescript/NativeQuickCrypto/random.d.ts +4 -0
- package/lib/typescript/QuickCrypto.d.ts +31 -0
- package/lib/typescript/Utils.d.ts +13 -0
- package/lib/typescript/index.d.ts +1 -0
- package/lib/typescript/pbkdf2.d.ts +9 -0
- package/lib/typescript/random.d.ts +20 -0
- package/package.json +168 -0
- package/react-native-quick-crypto.podspec +44 -0
- package/src/Cipher.ts +322 -0
- package/src/Hash.ts +98 -0
- package/src/Hmac.ts +107 -0
- package/src/NativeQuickCrypto/Cipher.ts +25 -0
- package/src/NativeQuickCrypto/NativeQuickCrypto.ts +79 -0
- package/src/NativeQuickCrypto/hash.ts +10 -0
- package/src/NativeQuickCrypto/hmac.ts +9 -0
- package/src/NativeQuickCrypto/pbkdf2.ts +16 -0
- package/src/NativeQuickCrypto/random.ts +12 -0
- package/src/QuickCrypto.ts +23 -0
- package/src/Utils.ts +151 -0
- package/src/index.ts +1 -0
- package/src/pbkdf2.ts +96 -0
- package/src/random.ts +277 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["pbkdf2.ts"],"names":["WRONG_PASS","WRON_SALT","sanitizeInput","input","errorMsg","e","nativePbkdf2","NativeQuickCrypto","pbkdf2","password","salt","iterations","keylen","arg0","arg1","digest","callback","undefined","Error","sanitizedPassword","sanitizedSalt","then","res","Buffer","from","pbkdf2Sync","algo","result"],"mappings":";;;;;;;;AAAA;;AACA;;AACA;;AAEA,MAAMA,UAAU,GACd,kEADF;AAEA,MAAMC,SAAS,GAAI,8DAAnB;;AAMA,SAASC,aAAT,CAAuBC,KAAvB,EAA0CC,QAA1C,EAAyE;AACvE,MAAI;AACF,WAAO,oCAAwBD,KAAxB,CAAP;AACD,GAFD,CAEE,OAAOE,CAAP,EAAe;AACf,UAAMD,QAAN;AACD;AACF;;AAED,MAAME,YAAY,GAAGC,qCAAkBC,MAAvC;;AAiBO,SAASA,MAAT,CACLC,QADK,EAELC,IAFK,EAGLC,UAHK,EAILC,MAJK,EAKLC,IALK,EAMLC,IANK,EAOC;AACN,MAAIC,MAAM,GAAG,MAAb;AACA,MAAIC,QAAJ;;AACA,MAAI,OAAOH,IAAP,KAAgB,QAApB,EAA8B;AAC5BE,IAAAA,MAAM,GAAGF,IAAT;;AACA,QAAI,OAAOC,IAAP,KAAgB,UAApB,EAAgC;AAC9BE,MAAAA,QAAQ,GAAGF,IAAX;AACD;AACF,GALD,MAKO;AACL,QAAI,OAAOD,IAAP,KAAgB,UAApB,EAAgC;AAC9BG,MAAAA,QAAQ,GAAGH,IAAX;AACD;AACF;;AACD,MAAIG,QAAQ,KAAKC,SAAjB,EAA4B;AAC1B,UAAM,IAAIC,KAAJ,CAAU,gCAAV,CAAN;AACD;;AAED,QAAMC,iBAAiB,GAAGjB,aAAa,CAACO,QAAD,EAAWT,UAAX,CAAvC;AACA,QAAMoB,aAAa,GAAGlB,aAAa,CAACQ,IAAD,EAAOT,SAAP,CAAnC;AAEAK,EAAAA,YAAY,CACTE,MADH,CACUW,iBADV,EAC6BC,aAD7B,EAC4CT,UAD5C,EACwDC,MADxD,EACgEG,MADhE,EAEGM,IAFH,CAGKC,GAAD,IAAsB;AACpBN,IAAAA,QAAQ,CAAE,IAAF,EAAQO,0BAAOC,IAAP,CAAYF,GAAZ,CAAR,CAAR;AACD,GALL,EAMKjB,CAAD,IAAc;AACZW,IAAAA,QAAQ,CAAEX,CAAF,CAAR;AACD,GARL;AAUD;;AACM,SAASoB,UAAT,CACLhB,QADK,EAELC,IAFK,EAGLC,UAHK,EAILC,MAJK,EAKLG,MALK,EAMG;AACR,QAAMI,iBAAiB,GAAGjB,aAAa,CAACO,QAAD,EAAWT,UAAX,CAAvC;AACA,QAAMoB,aAAa,GAAGlB,aAAa,CAACQ,IAAD,EAAOT,SAAP,CAAnC;AAEA,QAAMyB,IAAI,GAAGX,MAAM,GAAGA,MAAH,GAAY,MAA/B;AACA,MAAIY,MAAmB,GAAGrB,YAAY,CAACmB,UAAb,CACxBN,iBADwB,EAExBC,aAFwB,EAGxBT,UAHwB,EAIxBC,MAJwB,EAKxBc,IALwB,CAA1B;AAQA,SAAOH,0BAAOC,IAAP,CAAYG,MAAZ,CAAP;AACD","sourcesContent":["import { NativeQuickCrypto } from './NativeQuickCrypto/NativeQuickCrypto';\nimport { Buffer } from '@craftzdog/react-native-buffer';\nimport { BinaryLike, binaryLikeToArrayBuffer } from './Utils';\n\nconst WRONG_PASS =\n 'Password must be a string, a Buffer, a typed array or a DataView';\nconst WRON_SALT = `Salt must be a string, a Buffer, a typed array or a DataView`;\n\ntype Password = BinaryLike;\ntype Salt = BinaryLike;\ntype Pbkdf2Callback = (err: Error | null, derivedKey?: Buffer) => void;\n\nfunction sanitizeInput(input: BinaryLike, errorMsg: string): ArrayBuffer {\n try {\n return binaryLikeToArrayBuffer(input);\n } catch (e: any) {\n throw errorMsg;\n }\n}\n\nconst nativePbkdf2 = NativeQuickCrypto.pbkdf2;\n\nexport function pbkdf2(\n password: Password,\n salt: Salt,\n iterations: number,\n keylen: number,\n digest: string,\n callback: Pbkdf2Callback\n): void;\nexport function pbkdf2(\n password: Password,\n salt: Salt,\n iterations: number,\n keylen: number,\n callback: Pbkdf2Callback\n): void;\nexport function pbkdf2(\n password: Password,\n salt: Salt,\n iterations: number,\n keylen: number,\n arg0?: unknown,\n arg1?: unknown\n): void {\n let digest = 'sha1';\n let callback: undefined | Pbkdf2Callback;\n if (typeof arg0 === 'string') {\n digest = arg0;\n if (typeof arg1 === 'function') {\n callback = arg1 as Pbkdf2Callback;\n }\n } else {\n if (typeof arg0 === 'function') {\n callback = arg0 as Pbkdf2Callback;\n }\n }\n if (callback === undefined) {\n throw new Error('No callback provided to pbkdf2');\n }\n\n const sanitizedPassword = sanitizeInput(password, WRONG_PASS);\n const sanitizedSalt = sanitizeInput(salt, WRON_SALT);\n\n nativePbkdf2\n .pbkdf2(sanitizedPassword, sanitizedSalt, iterations, keylen, digest)\n .then(\n (res: ArrayBuffer) => {\n callback!(null, Buffer.from(res));\n },\n (e: Error) => {\n callback!(e);\n }\n );\n}\nexport function pbkdf2Sync(\n password: Password,\n salt: Salt,\n iterations: number,\n keylen: number,\n digest?: string\n): Buffer {\n const sanitizedPassword = sanitizeInput(password, WRONG_PASS);\n const sanitizedSalt = sanitizeInput(salt, WRON_SALT);\n\n const algo = digest ? digest : 'sha1';\n let result: ArrayBuffer = nativePbkdf2.pbkdf2Sync(\n sanitizedPassword,\n sanitizedSalt,\n iterations,\n keylen,\n algo\n );\n\n return Buffer.from(result);\n}\n"]}
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
Object.defineProperty(exports, "__esModule", {
|
|
4
|
+
value: true
|
|
5
|
+
});
|
|
6
|
+
exports.getRandomValues = getRandomValues;
|
|
7
|
+
exports.pseudoRandomBytes = exports.prng = void 0;
|
|
8
|
+
exports.randomBytes = randomBytes;
|
|
9
|
+
exports.randomFill = randomFill;
|
|
10
|
+
exports.randomFillSync = randomFillSync;
|
|
11
|
+
exports.randomInt = randomInt;
|
|
12
|
+
exports.rng = void 0;
|
|
13
|
+
|
|
14
|
+
var _NativeQuickCrypto = require("./NativeQuickCrypto/NativeQuickCrypto");
|
|
15
|
+
|
|
16
|
+
var _reactNativeBuffer = require("@craftzdog/react-native-buffer");
|
|
17
|
+
|
|
18
|
+
var _Utils = require("../src/Utils");
|
|
19
|
+
|
|
20
|
+
const random = _NativeQuickCrypto.NativeQuickCrypto.random;
|
|
21
|
+
|
|
22
|
+
function randomFill(buffer) {
|
|
23
|
+
var _ref, _ref2;
|
|
24
|
+
|
|
25
|
+
if (typeof (_ref = (arguments.length <= 1 ? 0 : arguments.length - 1) - 1 + 1, _ref < 1 || arguments.length <= _ref ? undefined : arguments[_ref]) !== 'function') {
|
|
26
|
+
throw new Error('No callback provided to randomDill');
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const callback = (_ref2 = (arguments.length <= 1 ? 0 : arguments.length - 1) - 1 + 1, _ref2 < 1 || arguments.length <= _ref2 ? undefined : arguments[_ref2]);
|
|
30
|
+
let offset = 0;
|
|
31
|
+
let size = buffer.byteLength;
|
|
32
|
+
|
|
33
|
+
if (typeof (arguments.length <= 3 ? undefined : arguments[3]) === 'function') {
|
|
34
|
+
offset = arguments.length <= 1 ? undefined : arguments[1];
|
|
35
|
+
size = arguments.length <= 2 ? undefined : arguments[2];
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
if (typeof (arguments.length <= 2 ? undefined : arguments[2]) === 'function') {
|
|
39
|
+
offset = arguments.length <= 1 ? undefined : arguments[1];
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
random.randomFill((0, _Utils.isBuffer)(buffer) ? buffer.buffer : buffer, offset, size).then(() => {
|
|
43
|
+
callback(null, buffer);
|
|
44
|
+
}, e => {
|
|
45
|
+
callback(e);
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function randomFillSync(buffer) {
|
|
50
|
+
let offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
|
|
51
|
+
let size = arguments.length > 2 ? arguments[2] : undefined;
|
|
52
|
+
random.randomFillSync(buffer.buffer ? buffer.buffer : buffer, offset, size !== null && size !== void 0 ? size : buffer.byteLength);
|
|
53
|
+
return buffer;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function randomBytes(size, callback) {
|
|
57
|
+
const buf = new _reactNativeBuffer.Buffer(size);
|
|
58
|
+
|
|
59
|
+
if (callback === undefined) {
|
|
60
|
+
randomFillSync(buf.buffer, 0, size);
|
|
61
|
+
return buf;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
randomFill(buf.buffer, 0, size, error => {
|
|
65
|
+
if (error) {
|
|
66
|
+
callback(error);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
callback(null, buf);
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const rng = randomBytes;
|
|
74
|
+
exports.rng = rng;
|
|
75
|
+
const pseudoRandomBytes = randomBytes;
|
|
76
|
+
exports.pseudoRandomBytes = pseudoRandomBytes;
|
|
77
|
+
const prng = randomBytes;
|
|
78
|
+
exports.prng = prng;
|
|
79
|
+
// The rest of the file is taken from https://github.com/nodejs/node/blob/master/lib/internal/crypto/random.js
|
|
80
|
+
// Largest integer we can read from a buffer.
|
|
81
|
+
// e.g.: Buffer.from("ff".repeat(6), "hex").readUIntBE(0, 6);
|
|
82
|
+
const RAND_MAX = 0xffffffffffff; // Cache random data to use in randomInt. The cache size must be evenly
|
|
83
|
+
// divisible by 6 because each attempt to obtain a random int uses 6 bytes.
|
|
84
|
+
|
|
85
|
+
const randomCache = new _reactNativeBuffer.Buffer(6 * 1024);
|
|
86
|
+
let randomCacheOffset = randomCache.length;
|
|
87
|
+
let asyncCacheFillInProgress = false;
|
|
88
|
+
const asyncCachePendingTasks = []; // Generates an integer in [min, max) range where min is inclusive and max is
|
|
89
|
+
// exclusive.
|
|
90
|
+
|
|
91
|
+
function randomInt(arg1, arg2, callback) {
|
|
92
|
+
// Detect optional min syntax
|
|
93
|
+
// randomInt(max)
|
|
94
|
+
// randomInt(max, callback)
|
|
95
|
+
let max;
|
|
96
|
+
let min;
|
|
97
|
+
const minNotSpecified = typeof arg2 === 'undefined' || typeof arg2 === 'function';
|
|
98
|
+
|
|
99
|
+
if (minNotSpecified) {
|
|
100
|
+
callback = arg2;
|
|
101
|
+
max = arg1;
|
|
102
|
+
min = 0;
|
|
103
|
+
} else {
|
|
104
|
+
min = arg1;
|
|
105
|
+
max = arg2;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const isSync = typeof callback === 'undefined';
|
|
109
|
+
|
|
110
|
+
if (!Number.isSafeInteger(min)) {
|
|
111
|
+
// todo throw new ERR_INVALID_ARG_TYPE('min', 'a safe integer', min);
|
|
112
|
+
throw 'ERR_INVALID_ARG_TYPE';
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
if (!Number.isSafeInteger(max)) {
|
|
116
|
+
// todo throw new ERR_INVALID_ARG_TYPE('max', 'a safe integer', max);
|
|
117
|
+
throw 'ERR_INVALID_ARG_TYPE';
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
if (max <= min) {
|
|
121
|
+
/* todo throw new ERR_OUT_OF_RANGE(
|
|
122
|
+
'max',
|
|
123
|
+
`greater than the value of "min" (${min})`,
|
|
124
|
+
max
|
|
125
|
+
);*/
|
|
126
|
+
throw 'ERR_OUT_OF_RANGE';
|
|
127
|
+
} // First we generate a random int between [0..range)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
const range = max - min;
|
|
131
|
+
|
|
132
|
+
if (!(range <= RAND_MAX)) {
|
|
133
|
+
/* todo throw new ERR_OUT_OF_RANGE(
|
|
134
|
+
`max${minNotSpecified ? '' : ' - min'}`,
|
|
135
|
+
`<= ${RAND_MAX}`,
|
|
136
|
+
range
|
|
137
|
+
);*/
|
|
138
|
+
throw 'ERR_OUT_OF_RANGE';
|
|
139
|
+
} // For (x % range) to produce an unbiased value greater than or equal to 0 and
|
|
140
|
+
// less than range, x must be drawn randomly from the set of integers greater
|
|
141
|
+
// than or equal to 0 and less than randLimit.
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
const randLimit = RAND_MAX - RAND_MAX % range; // If we don't have a callback, or if there is still data in the cache, we can
|
|
145
|
+
// do this synchronously, which is super fast.
|
|
146
|
+
|
|
147
|
+
while (isSync || randomCacheOffset < randomCache.length) {
|
|
148
|
+
if (randomCacheOffset === randomCache.length) {
|
|
149
|
+
// This might block the thread for a bit, but we are in sync mode.
|
|
150
|
+
randomFillSync(randomCache);
|
|
151
|
+
randomCacheOffset = 0;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
const x = randomCache.readUIntBE(randomCacheOffset, 6);
|
|
155
|
+
randomCacheOffset += 6;
|
|
156
|
+
|
|
157
|
+
if (x < randLimit) {
|
|
158
|
+
const n = x % range + min;
|
|
159
|
+
if (isSync) return n;
|
|
160
|
+
process.nextTick(callback, undefined, n);
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
} // At this point, we are in async mode with no data in the cache. We cannot
|
|
164
|
+
// simply refill the cache, because another async call to randomInt might
|
|
165
|
+
// already be doing that. Instead, queue this call for when the cache has
|
|
166
|
+
// been refilled.
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
if (callback !== undefined) {
|
|
170
|
+
// it is (typescript doesn't know it)
|
|
171
|
+
asyncCachePendingTasks.push({
|
|
172
|
+
min,
|
|
173
|
+
max,
|
|
174
|
+
callback
|
|
175
|
+
});
|
|
176
|
+
asyncRefillRandomIntCache();
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function asyncRefillRandomIntCache() {
|
|
181
|
+
if (asyncCacheFillInProgress) return;
|
|
182
|
+
asyncCacheFillInProgress = true;
|
|
183
|
+
randomFill(randomCache, err => {
|
|
184
|
+
asyncCacheFillInProgress = false;
|
|
185
|
+
const tasks = asyncCachePendingTasks;
|
|
186
|
+
const errorReceiver = err && tasks.shift();
|
|
187
|
+
if (!err) randomCacheOffset = 0; // Restart all pending tasks. If an error occurred, we only notify a single
|
|
188
|
+
// callback (errorReceiver) about it. This way, every async call to
|
|
189
|
+
// randomInt has a chance of being successful, and it avoids complex
|
|
190
|
+
// exception handling here.
|
|
191
|
+
|
|
192
|
+
tasks.splice(0).forEach(task => {
|
|
193
|
+
randomInt(task.min, task.max, task.callback);
|
|
194
|
+
}); // This is the only call that might throw, and is therefore done at the end.
|
|
195
|
+
|
|
196
|
+
if (errorReceiver) errorReceiver.callback(err, 0);
|
|
197
|
+
});
|
|
198
|
+
} // Really just the Web Crypto API alternative
|
|
199
|
+
// to require('crypto').randomFillSync() with an
|
|
200
|
+
// additional limitation that the input buffer is
|
|
201
|
+
// not allowed to exceed 65536 bytes, and can only
|
|
202
|
+
// be an integer-type TypedArray.
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
function getRandomValues(data) {
|
|
206
|
+
if (data.byteLength > 65536) {
|
|
207
|
+
throw new Error('The requested length exceeds 65,536 bytes');
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
randomFillSync(data, 0);
|
|
211
|
+
return data;
|
|
212
|
+
}
|
|
213
|
+
//# sourceMappingURL=random.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["random.ts"],"names":["random","NativeQuickCrypto","randomFill","buffer","Error","callback","offset","size","byteLength","then","e","randomFillSync","randomBytes","buf","Buffer","undefined","error","rng","pseudoRandomBytes","prng","RAND_MAX","randomCache","randomCacheOffset","length","asyncCacheFillInProgress","asyncCachePendingTasks","randomInt","arg1","arg2","max","min","minNotSpecified","isSync","Number","isSafeInteger","range","randLimit","x","readUIntBE","n","process","nextTick","push","asyncRefillRandomIntCache","err","tasks","errorReceiver","shift","splice","forEach","task","getRandomValues","data"],"mappings":";;;;;;;;;;;;;AAAA;;AACA;;AACA;;AAEA,MAAMA,MAAM,GAAGC,qCAAkBD,MAAjC;;AAgCO,SAASE,UAAT,CAAoBC,MAApB,EAAuD;AAAA;;AAC5D,MAAI,eAAY,qDAAc,CAA1B,8EAAiC,UAArC,EAAiD;AAC/C,UAAM,IAAIC,KAAJ,CAAU,oCAAV,CAAN;AACD;;AAED,QA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,IAAAA,wBAAwB,GAAG,KAA3B;AAEA,UAAMqB,KAAK,GAAGpB,sBAAd;AACA,UAAMqB,aAAa,GAAGF,GAAG,IAAIC,KAAK,CAACE,KAAN,EAA7B;AACA,QAAI,CAACH,GAAL,EAAUtB,iBAAiB,GAAG,CAApB,CALqB,CAO/B;AACA;AACA;AACA;;AACAuB,IAAAA,KAAK,CAACG,MAAN,CAAa,CAAb,EAAgBC,OAAhB,CAAyBC,IAAD,IAAU;AAChCxB,MAAAA,SAAS,CAACwB,IAAI,CAACpB,GAAN,EAAWoB,IAAI,CAACrB,GAAhB,EAAqBqB,IAAI,CAAC7C,QAA1B,CAAT;AACD,KAFD,EAX+B,CAe/B;;AACA,QAAIyC,aAAJ,EAAmBA,aAAa,CAACzC,QAAd,CAAuBuC,GAAvB,EAA4B,CAA5B;AACpB,GAjBS,CAAV;AAkBD,C,CAED;AACA;AACA;AACA;AACA;;;AAQO,SAASO,eAAT,CAAyBC,IAAzB,EAAyC;AAC9C,MAAIA,IAAI,CAAC5C,UAAL,GAAkB,KAAtB,EAA6B;AAC3B,UAAM,IAAIJ,KAAJ,CAAU,2CAAV,CAAN;AACD;;AACDO,EAAAA,cAAc,CAACyC,IAAD,EAAO,CAAP,CAAd;AACA,SAAOA,IAAP;AACD","sourcesContent":["import { NativeQuickCrypto } from './NativeQuickCrypto/NativeQuickCrypto';\nimport { Buffer } from '@craftzdog/react-native-buffer';\nimport { isBuffer } from '../src/Utils';\n\nconst random = NativeQuickCrypto.random;\n\ntype TypedArray =\n | Uint8Array\n | Uint8ClampedArray\n | Uint16Array\n | Uint32Array\n | Int8Array\n | Int16Array\n | Int32Array\n | Float32Array\n | Float64Array;\ntype ArrayBufferView = TypedArray | DataView | ArrayBufferLike | Buffer;\n\nexport function randomFill<T extends ArrayBufferView>(\n buffer: T,\n callback: (err: Error | null, buf: T) => void\n): void;\n\nexport function randomFill<T extends ArrayBufferView>(\n buffer: T,\n offset: number,\n callback: (err: Error | null, buf: T) => void\n): void;\n\nexport function randomFill<T extends ArrayBufferView>(\n buffer: T,\n offset: number,\n size: number,\n callback: (err: Error | null, buf: T) => void\n): void;\n\nexport function randomFill(buffer: any, ...rest: any[]): void {\n if (typeof rest[rest.length - 1] !== 'function') {\n throw new Error('No callback provided to randomDill');\n }\n\n const callback = rest[rest.length - 1] as any as (\n err: Error | null,\n buf?: ArrayBuffer\n ) => void;\n\n let offset: number = 0;\n let size: number = buffer.byteLength;\n\n if (typeof rest[2] === 'function') {\n offset = rest[0];\n size = rest[1];\n }\n\n if (typeof rest[1] === 'function') {\n offset = rest[0];\n }\n\n random\n .randomFill(isBuffer(buffer) ? buffer.buffer : buffer, offset, size)\n .then(\n () => {\n callback(null, buffer);\n },\n (e: Error) => {\n callback(e);\n }\n );\n}\n\nexport function randomFillSync<T extends ArrayBufferView>(\n buffer: T,\n offset?: number,\n size?: number\n): T;\n\nexport function randomFillSync(buffer: any, offset: number = 0, size?: number) {\n random.randomFillSync(\n buffer.buffer ? buffer.buffer : buffer,\n offset,\n size ?? buffer.byteLength\n );\n return buffer;\n}\n\nexport function randomBytes(size: number): ArrayBuffer;\n\nexport function randomBytes(\n size: number,\n callback: (err: Error | null, buf?: ArrayBuffer) => void\n): void;\n\nexport function randomBytes(\n size: number,\n callback?: (err: Error | null, buf?: ArrayBuffer) => void\n): void | ArrayBuffer {\n const buf = new Buffer(size);\n\n if (callback === undefined) {\n randomFillSync(buf.buffer, 0, size);\n return buf;\n }\n\n randomFill(buf.buffer, 0, size, (error: Error | null) => {\n if (error) {\n callback(error);\n }\n callback(null, buf);\n });\n}\n\nexport const rng = randomBytes;\nexport const pseudoRandomBytes = randomBytes;\nexport const prng = randomBytes;\n\ntype RandomIntCallback = (err: Error | null, value: number) => void;\ntype Task = {\n min: number;\n max: number;\n callback: RandomIntCallback;\n};\n\n// The rest of the file is taken from https://github.com/nodejs/node/blob/master/lib/internal/crypto/random.js\n\n// Largest integer we can read from a buffer.\n// e.g.: Buffer.from(\"ff\".repeat(6), \"hex\").readUIntBE(0, 6);\nconst RAND_MAX = 0xffff_ffff_ffff;\n\n// Cache random data to use in randomInt. The cache size must be evenly\n// divisible by 6 because each attempt to obtain a random int uses 6 bytes.\nconst randomCache = new Buffer(6 * 1024);\nlet randomCacheOffset = randomCache.length;\nlet asyncCacheFillInProgress = false;\nconst asyncCachePendingTasks: Task[] = [];\n\n// Generates an integer in [min, max) range where min is inclusive and max is\n// exclusive.\n\nexport function randomInt(max: number, callback: RandomIntCallback): void;\nexport function randomInt(max: number): number;\nexport function randomInt(\n min: number,\n max: number,\n callback: RandomIntCallback\n): void;\nexport function randomInt(min: number, max: number): number;\nexport function randomInt(\n arg1: number,\n arg2?: number | RandomIntCallback,\n callback?: RandomIntCallback\n): void | number {\n // Detect optional min syntax\n // randomInt(max)\n // randomInt(max, callback)\n let max: number;\n let min: number;\n const minNotSpecified =\n typeof arg2 === 'undefined' || typeof arg2 === 'function';\n\n if (minNotSpecified) {\n callback = arg2 as any as undefined | RandomIntCallback;\n max = arg1;\n min = 0;\n } else {\n min = arg1;\n max = arg2 as any as number;\n }\n\n const isSync = typeof callback === 'undefined';\n if (!Number.isSafeInteger(min)) {\n // todo throw new ERR_INVALID_ARG_TYPE('min', 'a safe integer', min);\n throw 'ERR_INVALID_ARG_TYPE';\n }\n if (!Number.isSafeInteger(max)) {\n // todo throw new ERR_INVALID_ARG_TYPE('max', 'a safe integer', max);\n throw 'ERR_INVALID_ARG_TYPE';\n }\n if (max <= min) {\n /* todo throw new ERR_OUT_OF_RANGE(\n 'max',\n `greater than the value of \"min\" (${min})`,\n max\n );*/\n throw 'ERR_OUT_OF_RANGE';\n }\n\n // First we generate a random int between [0..range)\n const range = max - min;\n\n if (!(range <= RAND_MAX)) {\n /* todo throw new ERR_OUT_OF_RANGE(\n `max${minNotSpecified ? '' : ' - min'}`,\n `<= ${RAND_MAX}`,\n range\n );*/\n throw 'ERR_OUT_OF_RANGE';\n }\n\n // For (x % range) to produce an unbiased value greater than or equal to 0 and\n // less than range, x must be drawn randomly from the set of integers greater\n // than or equal to 0 and less than randLimit.\n const randLimit = RAND_MAX - (RAND_MAX % range);\n\n // If we don't have a callback, or if there is still data in the cache, we can\n // do this synchronously, which is super fast.\n while (isSync || randomCacheOffset < randomCache.length) {\n if (randomCacheOffset === randomCache.length) {\n // This might block the thread for a bit, but we are in sync mode.\n randomFillSync(randomCache);\n randomCacheOffset = 0;\n }\n\n const x = randomCache.readUIntBE(randomCacheOffset, 6);\n randomCacheOffset += 6;\n\n if (x < randLimit) {\n const n = (x % range) + min;\n if (isSync) return n;\n process.nextTick(callback as Function, undefined, n);\n return;\n }\n }\n\n // At this point, we are in async mode with no data in the cache. We cannot\n // simply refill the cache, because another async call to randomInt might\n // already be doing that. Instead, queue this call for when the cache has\n // been refilled.\n if (callback !== undefined) {\n // it is (typescript doesn't know it)\n asyncCachePendingTasks.push({ min, max, callback });\n asyncRefillRandomIntCache();\n }\n}\n\nfunction asyncRefillRandomIntCache() {\n if (asyncCacheFillInProgress) return;\n\n asyncCacheFillInProgress = true;\n randomFill(randomCache, (err) => {\n asyncCacheFillInProgress = false;\n\n const tasks = asyncCachePendingTasks;\n const errorReceiver = err && tasks.shift();\n if (!err) randomCacheOffset = 0;\n\n // Restart all pending tasks. If an error occurred, we only notify a single\n // callback (errorReceiver) about it. This way, every async call to\n // randomInt has a chance of being successful, and it avoids complex\n // exception handling here.\n tasks.splice(0).forEach((task) => {\n randomInt(task.min, task.max, task.callback);\n });\n\n // This is the only call that might throw, and is therefore done at the end.\n if (errorReceiver) errorReceiver.callback(err, 0);\n });\n}\n\n// Really just the Web Crypto API alternative\n// to require('crypto').randomFillSync() with an\n// additional limitation that the input buffer is\n// not allowed to exceed 65536 bytes, and can only\n// be an integer-type TypedArray.\ntype DataType =\n | Int8Array\n | Int16Array\n | Int32Array\n | Uint8Array\n | Uint16Array\n | Uint32Array;\nexport function getRandomValues(data: DataType) {\n if (data.byteLength > 65536) {\n throw new Error('The requested length exceeds 65,536 bytes');\n }\n randomFillSync(data, 0);\n return data;\n}\n"]}
|
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
|
|
2
|
+
|
|
3
|
+
/* eslint-disable no-dupe-class-members */
|
|
4
|
+
import { NativeQuickCrypto } from './NativeQuickCrypto/NativeQuickCrypto';
|
|
5
|
+
import Stream from 'stream';
|
|
6
|
+
import { binaryLikeToArrayBuffer, getDefaultEncoding } from './Utils';
|
|
7
|
+
// TODO(osp) re-enable type specific constructors
|
|
8
|
+
// They are nice to have but not absolutely necessary
|
|
9
|
+
// import type {
|
|
10
|
+
// CipherCCMOptions,
|
|
11
|
+
// CipherCCMTypes,
|
|
12
|
+
// CipherGCMTypes,
|
|
13
|
+
// CipherGCMOptions,
|
|
14
|
+
// // CipherKey,
|
|
15
|
+
// // KeyObject,
|
|
16
|
+
// // TODO @Szymon20000 This types seem to be missing? Where did you get this definitions from?
|
|
17
|
+
// // CipherOCBTypes,
|
|
18
|
+
// // CipherOCBOptions,
|
|
19
|
+
// } from 'crypto'; // Node crypto typings
|
|
20
|
+
import { StringDecoder } from 'string_decoder';
|
|
21
|
+
import { Buffer as SBuffer } from 'safe-buffer';
|
|
22
|
+
const createInternalCipher = NativeQuickCrypto.createCipher;
|
|
23
|
+
const createInternalDecipher = NativeQuickCrypto.createDecipher;
|
|
24
|
+
|
|
25
|
+
function getUIntOption(options, key) {
|
|
26
|
+
let value;
|
|
27
|
+
|
|
28
|
+
if (options && (value = options[key]) != null) {
|
|
29
|
+
// >>> Turns any type into a positive integer (also sets the sign bit to 0)
|
|
30
|
+
// eslint-disable-next-line no-bitwise
|
|
31
|
+
if (value >>> 0 !== value) throw new Error(`options.${key}: ${value}`);
|
|
32
|
+
return value;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
return -1;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function normalizeEncoding(enc) {
|
|
39
|
+
if (!enc) return 'utf8';
|
|
40
|
+
var retried;
|
|
41
|
+
|
|
42
|
+
while (true) {
|
|
43
|
+
switch (enc) {
|
|
44
|
+
case 'utf8':
|
|
45
|
+
case 'utf-8':
|
|
46
|
+
return 'utf8';
|
|
47
|
+
|
|
48
|
+
case 'ucs2':
|
|
49
|
+
case 'ucs-2':
|
|
50
|
+
case 'utf16le':
|
|
51
|
+
case 'utf-16le':
|
|
52
|
+
return 'utf16le';
|
|
53
|
+
|
|
54
|
+
case 'latin1':
|
|
55
|
+
case 'binary':
|
|
56
|
+
return 'latin1';
|
|
57
|
+
|
|
58
|
+
case 'base64':
|
|
59
|
+
case 'ascii':
|
|
60
|
+
case 'hex':
|
|
61
|
+
return enc;
|
|
62
|
+
|
|
63
|
+
default:
|
|
64
|
+
if (retried) return; // undefined
|
|
65
|
+
|
|
66
|
+
enc = ('' + enc).toLowerCase();
|
|
67
|
+
retried = true;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function validateEncoding(data, encoding) {
|
|
73
|
+
const normalizedEncoding = normalizeEncoding(encoding);
|
|
74
|
+
const length = data.length;
|
|
75
|
+
|
|
76
|
+
if (normalizedEncoding === 'hex' && length % 2 !== 0) {
|
|
77
|
+
throw new Error(`Encoding ${encoding} not valid for data length ${length}`);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function getDecoder(decoder, encoding) {
|
|
82
|
+
return decoder !== null && decoder !== void 0 ? decoder : new StringDecoder(encoding);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
class CipherCommon extends Stream.Transform {
|
|
86
|
+
constructor(cipherType, cipherKey, isCipher) {
|
|
87
|
+
let options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
|
|
88
|
+
let iv = arguments.length > 4 ? arguments[4] : undefined;
|
|
89
|
+
super(options);
|
|
90
|
+
|
|
91
|
+
_defineProperty(this, "internal", void 0);
|
|
92
|
+
|
|
93
|
+
_defineProperty(this, "decoder", void 0);
|
|
94
|
+
|
|
95
|
+
const cipherKeyBuffer = binaryLikeToArrayBuffer(cipherKey); // TODO(osp) This might not be smart, check again after release
|
|
96
|
+
|
|
97
|
+
const authTagLength = getUIntOption(options, 'authTagLength');
|
|
98
|
+
const args = {
|
|
99
|
+
cipher_type: cipherType,
|
|
100
|
+
cipher_key: cipherKeyBuffer,
|
|
101
|
+
iv,
|
|
102
|
+
...options,
|
|
103
|
+
auth_tag_len: authTagLength
|
|
104
|
+
};
|
|
105
|
+
this.internal = isCipher ? createInternalCipher(args) : createInternalDecipher(args);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
update(data, inputEncoding, outputEncoding) {
|
|
109
|
+
var _inputEncoding, _outputEncoding;
|
|
110
|
+
|
|
111
|
+
const defaultEncoding = getDefaultEncoding();
|
|
112
|
+
inputEncoding = (_inputEncoding = inputEncoding) !== null && _inputEncoding !== void 0 ? _inputEncoding : defaultEncoding;
|
|
113
|
+
outputEncoding = (_outputEncoding = outputEncoding) !== null && _outputEncoding !== void 0 ? _outputEncoding : defaultEncoding;
|
|
114
|
+
|
|
115
|
+
if (typeof data === 'string') {
|
|
116
|
+
validateEncoding(data, inputEncoding);
|
|
117
|
+
} else if (!ArrayBuffer.isView(data)) {
|
|
118
|
+
throw new Error('Invalid data argument');
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
if (typeof data === 'string') {
|
|
122
|
+
// On node this is handled on the native side
|
|
123
|
+
// on our case we need to correctly send the arraybuffer to the jsi side
|
|
124
|
+
inputEncoding = inputEncoding === 'buffer' ? 'utf8' : inputEncoding;
|
|
125
|
+
data = binaryLikeToArrayBuffer(data, inputEncoding);
|
|
126
|
+
} else {
|
|
127
|
+
data = binaryLikeToArrayBuffer(data, inputEncoding);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
const ret = this.internal.update(data);
|
|
131
|
+
|
|
132
|
+
if (outputEncoding && outputEncoding !== 'buffer') {
|
|
133
|
+
this.decoder = getDecoder(this.decoder, outputEncoding);
|
|
134
|
+
return this.decoder.write(SBuffer.from(ret));
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
return ret;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
final(outputEncoding) {
|
|
141
|
+
const ret = this.internal.final();
|
|
142
|
+
|
|
143
|
+
if (outputEncoding && outputEncoding !== 'buffer') {
|
|
144
|
+
this.decoder = getDecoder(this.decoder, outputEncoding);
|
|
145
|
+
return this.decoder.end(SBuffer.from(ret));
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
return ret;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
_transform(chunk, encoding, callback) {
|
|
152
|
+
this.push(this.update(chunk, encoding));
|
|
153
|
+
callback();
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
_flush(callback) {
|
|
157
|
+
this.push(this.final());
|
|
158
|
+
callback();
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
setAutoPadding(autoPadding) {
|
|
162
|
+
this.internal.setAutoPadding(!!autoPadding);
|
|
163
|
+
return this;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
setAAD(buffer, options) {
|
|
167
|
+
this.internal.setAAD({
|
|
168
|
+
data: buffer.buffer,
|
|
169
|
+
plaintextLength: options === null || options === void 0 ? void 0 : options.plaintextLength
|
|
170
|
+
});
|
|
171
|
+
return this;
|
|
172
|
+
} // protected getAuthTag(): Buffer {
|
|
173
|
+
// return Buffer.from(this.internal.getAuthTag());
|
|
174
|
+
// }
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
setAuthTag(tag) {
|
|
178
|
+
this.internal.setAuthTag(tag.buffer);
|
|
179
|
+
return this;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
class Cipher extends CipherCommon {
|
|
185
|
+
constructor(cipherType, cipherKey) {
|
|
186
|
+
let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
|
|
187
|
+
let iv = arguments.length > 3 ? arguments[3] : undefined;
|
|
188
|
+
|
|
189
|
+
if (iv != null) {
|
|
190
|
+
iv = binaryLikeToArrayBuffer(iv);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
super(cipherType, cipherKey, true, options, iv);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
class Decipher extends CipherCommon {
|
|
199
|
+
constructor(cipherType, cipherKey) {
|
|
200
|
+
let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
|
|
201
|
+
let iv = arguments.length > 3 ? arguments[3] : undefined;
|
|
202
|
+
|
|
203
|
+
if (iv != null) {
|
|
204
|
+
iv = binaryLikeToArrayBuffer(iv);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
super(cipherType, cipherKey, false, options, iv);
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
} // TODO(osp) This definitions cause typescript errors when using the API
|
|
211
|
+
// export function createDecipher(
|
|
212
|
+
// algorithm: CipherCCMTypes,
|
|
213
|
+
// password: BinaryLike,
|
|
214
|
+
// options: CipherCCMOptions
|
|
215
|
+
// ): Decipher;
|
|
216
|
+
// export function createDecipher(
|
|
217
|
+
// algorithm: CipherGCMTypes,
|
|
218
|
+
// password: BinaryLike,
|
|
219
|
+
// options?: CipherGCMOptions
|
|
220
|
+
// ): Decipher;
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
export function createDecipher(algorithm, password, options) {
|
|
224
|
+
return new Decipher(algorithm, password, options);
|
|
225
|
+
} // TODO(osp) This definitions cause typescript errors when using the API
|
|
226
|
+
// export function createDecipheriv(
|
|
227
|
+
// algorithm: CipherCCMTypes,
|
|
228
|
+
// key: BinaryLike,
|
|
229
|
+
// iv: BinaryLike,
|
|
230
|
+
// options: CipherCCMOptions
|
|
231
|
+
// ): Decipher;
|
|
232
|
+
// export function createDecipheriv(
|
|
233
|
+
// algorithm: CipherOCBTypes,
|
|
234
|
+
// key: BinaryLike,
|
|
235
|
+
// iv: BinaryLike,
|
|
236
|
+
// options: CipherOCBOptions
|
|
237
|
+
// ): DecipherOCB;
|
|
238
|
+
// export function createDecipheriv(
|
|
239
|
+
// algorithm: CipherGCMTypes,
|
|
240
|
+
// key: BinaryLike,
|
|
241
|
+
// iv: BinaryLike,
|
|
242
|
+
// options?: CipherGCMOptions
|
|
243
|
+
// ): Decipher;
|
|
244
|
+
|
|
245
|
+
export function createDecipheriv(algorithm, key, iv, options) {
|
|
246
|
+
return new Decipher(algorithm, key, options, iv);
|
|
247
|
+
} // TODO(osp) This definitions cause typescript errors when using the API
|
|
248
|
+
// commenting them out for now
|
|
249
|
+
// export function createCipher(
|
|
250
|
+
// algorithm: CipherCCMTypes,
|
|
251
|
+
// password: BinaryLike,
|
|
252
|
+
// options: CipherCCMOptions
|
|
253
|
+
// ): Cipher;
|
|
254
|
+
// export function createCipher(
|
|
255
|
+
// algorithm: CipherGCMTypes,
|
|
256
|
+
// password: BinaryLike,
|
|
257
|
+
// options?: CipherGCMOptions
|
|
258
|
+
// ): Cipher;
|
|
259
|
+
|
|
260
|
+
export function createCipher(algorithm, password, options) {
|
|
261
|
+
return new Cipher(algorithm, password, options);
|
|
262
|
+
} // TODO(osp) on all the createCipheriv methods, node seems to use a "KeyObject" is seems to be a thread safe
|
|
263
|
+
// object that creates keys and what not. Not sure if we should support it.
|
|
264
|
+
// Fow now I replaced all of them to BinaryLike
|
|
265
|
+
// export function createCipheriv(
|
|
266
|
+
// algorithm: CipherCCMTypes,
|
|
267
|
+
// key: BinaryLike,
|
|
268
|
+
// iv: BinaryLike,
|
|
269
|
+
// options: CipherCCMOptions
|
|
270
|
+
// ): Cipher;
|
|
271
|
+
// export function createCipheriv(
|
|
272
|
+
// algorithm: CipherOCBTypes,
|
|
273
|
+
// key: BinaryLike,
|
|
274
|
+
// iv: BinaryLike,
|
|
275
|
+
// options: CipherOCBOptions
|
|
276
|
+
// ): CipherOCB;
|
|
277
|
+
// export function createCipheriv(
|
|
278
|
+
// algorithm: CipherGCMTypes,
|
|
279
|
+
// key: BinaryLike,
|
|
280
|
+
// iv: BinaryLike,
|
|
281
|
+
// options?: CipherGCMOptions
|
|
282
|
+
// ): Cipher;
|
|
283
|
+
|
|
284
|
+
export function createCipheriv(algorithm, key, iv, options) {
|
|
285
|
+
return new Cipher(algorithm, key, options, iv);
|
|
286
|
+
}
|
|
287
|
+
//# sourceMappingURL=Cipher.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["Cipher.ts"],"names":["NativeQuickCrypto","Stream","binaryLikeToArrayBuffer","getDefaultEncoding","StringDecoder","Buffer","SBuffer","createInternalCipher","createCipher","createInternalDecipher","createDecipher","getUIntOption","options","key","value","Error","normalizeEncoding","enc","retried","toLowerCase","validateEncoding","data","encoding","normalizedEncoding","length","getDecoder","decoder","CipherCommon","Transform","constructor","cipherType","cipherKey","isCipher","iv","cipherKeyBuffer","authTagLength","args","cipher_type","cipher_key","auth_tag_len","internal","update","inputEncoding","outputEncoding","defaultEncoding","ArrayBuffer","isView","ret","write","from","final","end","_transform","chunk","callback","push","_flush","setAutoPadding","autoPadding","setAAD","buffer","plaintextLength","setAuthTag","tag","Cipher","Decipher","algorithm","password","createDecipheriv","createCipheriv"],"mappings":";;AAAA;AACA,SAASA,iBAAT,QAAkC,uCAAlC;AACA,OAAOC,MAAP,MAAmB,QAAnB;AACA,SAEEC,uBAFF,EAKEC,kBALF,QAMO,SANP;AAQA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAASC,aAAT,QAA8B,gBAA9B;AAEA,SAASC,MAAM,IAAIC,OAAnB,QAAkC,aAAlC;AAEA,MAAMC,oBAAoB,GAAGP,iBAAiB,CAACQ,YAA/C;AACA,MAAMC,sBAAsB,GAAGT,iBAAiB,CAACU,cAAjD;;AAEA,SAASC,aAAT,CAAuBC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qB,EAA7C;AACD;;AAZiC,C,CAepC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AACA,OAAO,SAASvB,cAAT,CACLwD,SADK,EAELC,QAFK,EAGLvD,OAHK,EAIK;AACV,SAAO,IAAIqD,QAAJ,CAAaC,SAAb,EAAwBC,QAAxB,EAAkCvD,OAAlC,CAAP;AACD,C,CAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AACA,OAAO,SAASwD,gBAAT,CACLF,SADK,EAELrD,GAFK,EAGLoB,EAHK,EAILrB,OAJK,EAKK;AACV,SAAO,IAAIqD,QAAJ,CAAaC,SAAb,EAAwBrD,GAAxB,EAA6BD,OAA7B,EAAsCqB,EAAtC,CAAP;AACD,C,CAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AACA,OAAO,SAASzB,YAAT,CACL0D,SADK,EAELC,QAFK,EAGLvD,OAHK,EAIG;AACR,SAAO,IAAIoD,MAAJ,CAAWE,SAAX,EAAsBC,QAAtB,EAAgCvD,OAAhC,CAAP;AACD,C,CAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AACA,OAAO,SAASyD,cAAT,CACLH,SADK,EAELrD,GAFK,EAGLoB,EAHK,EAILrB,OAJK,EAKG;AACR,SAAO,IAAIoD,MAAJ,CAAWE,SAAX,EAAsBrD,GAAtB,EAA2BD,OAA3B,EAAoCqB,EAApC,CAAP;AACD","sourcesContent":["/* eslint-disable no-dupe-class-members */\nimport { NativeQuickCrypto } from './NativeQuickCrypto/NativeQuickCrypto';\nimport Stream from 'stream';\nimport {\n BinaryLike,\n binaryLikeToArrayBuffer,\n CipherEncoding,\n Encoding,\n getDefaultEncoding,\n} from './Utils';\nimport type { InternalCipher } from './NativeQuickCrypto/Cipher';\n// TODO(osp) re-enable type specific constructors\n// They are nice to have but not absolutely necessary\n// import type {\n// CipherCCMOptions,\n// CipherCCMTypes,\n// CipherGCMTypes,\n// CipherGCMOptions,\n// // CipherKey,\n// // KeyObject,\n// // TODO @Szymon20000 This types seem to be missing? Where did you get this definitions from?\n// // CipherOCBTypes,\n// // CipherOCBOptions,\n// } from 'crypto'; // Node crypto typings\nimport { StringDecoder } from 'string_decoder';\nimport type { Buffer } from '@craftzdog/react-native-buffer';\nimport { Buffer as SBuffer } from 'safe-buffer';\n\nconst createInternalCipher = NativeQuickCrypto.createCipher;\nconst createInternalDecipher = NativeQuickCrypto.createDecipher;\n\nfunction getUIntOption(options: Record<string, any>, key: string) {\n let value;\n if (options && (value = options[key]) != null) {\n // >>> Turns any type into a positive integer (also sets the sign bit to 0)\n // eslint-disable-next-line no-bitwise\n if (value >>> 0 !== value) throw new Error(`options.${key}: ${value}`);\n return value;\n }\n return -1;\n}\n\nfunction normalizeEncoding(enc: string) {\n if (!enc) return 'utf8';\n var retried;\n while (true) {\n switch (enc) {\n case 'utf8':\n case 'utf-8':\n return 'utf8';\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return 'utf16le';\n case 'latin1':\n case 'binary':\n return 'latin1';\n case 'base64':\n case 'ascii':\n case 'hex':\n return enc;\n default:\n if (retried) return; // undefined\n enc = ('' + enc).toLowerCase();\n retried = true;\n }\n }\n}\n\nfunction validateEncoding(data: string, encoding: string) {\n const normalizedEncoding = normalizeEncoding(encoding);\n const length = data.length;\n\n if (normalizedEncoding === 'hex' && length % 2 !== 0) {\n throw new Error(`Encoding ${encoding} not valid for data length ${length}`);\n }\n}\n\nfunction getDecoder(decoder?: StringDecoder, encoding?: BufferEncoding) {\n return decoder ?? new StringDecoder(encoding);\n}\n\nclass CipherCommon extends Stream.Transform {\n private internal: InternalCipher;\n private decoder: StringDecoder | undefined;\n\n constructor(\n cipherType: string,\n cipherKey: BinaryLike,\n isCipher: boolean,\n options: Record<string, any> = {},\n iv?: BinaryLike | null\n ) {\n super(options);\n const cipherKeyBuffer = binaryLikeToArrayBuffer(cipherKey);\n // TODO(osp) This might not be smart, check again after release\n const authTagLength = getUIntOption(options, 'authTagLength');\n const args = {\n cipher_type: cipherType,\n cipher_key: cipherKeyBuffer,\n iv,\n ...options,\n auth_tag_len: authTagLength,\n };\n this.internal = isCipher\n ? createInternalCipher(args)\n : createInternalDecipher(args);\n }\n\n update(\n data: BinaryLike,\n inputEncoding?: CipherEncoding,\n outputEncoding?: CipherEncoding\n ): ArrayBuffer | string {\n const defaultEncoding = getDefaultEncoding();\n inputEncoding = inputEncoding ?? defaultEncoding;\n outputEncoding = outputEncoding ?? defaultEncoding;\n\n if (typeof data === 'string') {\n validateEncoding(data, inputEncoding);\n } else if (!ArrayBuffer.isView(data)) {\n throw new Error('Invalid data argument');\n }\n\n if (typeof data === 'string') {\n // On node this is handled on the native side\n // on our case we need to correctly send the arraybuffer to the jsi side\n inputEncoding = inputEncoding === 'buffer' ? 'utf8' : inputEncoding;\n data = binaryLikeToArrayBuffer(data, inputEncoding);\n } else {\n data = binaryLikeToArrayBuffer(data as any, inputEncoding);\n }\n\n const ret = this.internal.update(data);\n\n if (outputEncoding && outputEncoding !== 'buffer') {\n this.decoder = getDecoder(this.decoder, outputEncoding);\n\n return this.decoder!.write(SBuffer.from(ret) as any);\n }\n\n return ret;\n }\n\n final(): ArrayBuffer;\n final(outputEncoding: BufferEncoding | 'buffer'): string;\n final(outputEncoding?: BufferEncoding | 'buffer'): ArrayBuffer | string {\n const ret = this.internal.final();\n\n if (outputEncoding && outputEncoding !== 'buffer') {\n this.decoder = getDecoder(this.decoder, outputEncoding);\n\n return this.decoder!.end(SBuffer.from(ret) as any);\n }\n\n return ret;\n }\n\n _transform(chunk: BinaryLike, encoding: Encoding, callback: () => void) {\n this.push(this.update(chunk, encoding));\n callback();\n }\n\n _flush(callback: () => void) {\n this.push(this.final());\n callback();\n }\n\n public setAutoPadding(autoPadding?: boolean): this {\n this.internal.setAutoPadding(!!autoPadding);\n return this;\n }\n\n public setAAD(\n buffer: Buffer,\n options?: {\n plaintextLength: number;\n }\n ): this {\n this.internal.setAAD({\n data: buffer.buffer,\n plaintextLength: options?.plaintextLength,\n });\n return this;\n }\n\n // protected getAuthTag(): Buffer {\n // return Buffer.from(this.internal.getAuthTag());\n // }\n\n public setAuthTag(tag: Buffer): this {\n this.internal.setAuthTag(tag.buffer);\n return this;\n }\n}\n\nclass Cipher extends CipherCommon {\n constructor(\n cipherType: string,\n cipherKey: BinaryLike,\n options: Record<string, any> = {},\n iv?: BinaryLike | null\n ) {\n if (iv != null) {\n iv = binaryLikeToArrayBuffer(iv);\n }\n super(cipherType, cipherKey, true, options, iv);\n }\n}\n\nclass Decipher extends CipherCommon {\n constructor(\n cipherType: string,\n cipherKey: BinaryLike,\n options: Record<string, any> = {},\n iv?: BinaryLike | null\n ) {\n if (iv != null) {\n iv = binaryLikeToArrayBuffer(iv);\n }\n\n super(cipherType, cipherKey, false, options, iv);\n }\n}\n\n// TODO(osp) This definitions cause typescript errors when using the API\n// export function createDecipher(\n// algorithm: CipherCCMTypes,\n// password: BinaryLike,\n// options: CipherCCMOptions\n// ): Decipher;\n// export function createDecipher(\n// algorithm: CipherGCMTypes,\n// password: BinaryLike,\n// options?: CipherGCMOptions\n// ): Decipher;\nexport function createDecipher(\n algorithm: string,\n password: BinaryLike,\n options?: Stream.TransformOptions\n): Decipher {\n return new Decipher(algorithm, password, options);\n}\n\n// TODO(osp) This definitions cause typescript errors when using the API\n// export function createDecipheriv(\n// algorithm: CipherCCMTypes,\n// key: BinaryLike,\n// iv: BinaryLike,\n// options: CipherCCMOptions\n// ): Decipher;\n// export function createDecipheriv(\n// algorithm: CipherOCBTypes,\n// key: BinaryLike,\n// iv: BinaryLike,\n// options: CipherOCBOptions\n// ): DecipherOCB;\n// export function createDecipheriv(\n// algorithm: CipherGCMTypes,\n// key: BinaryLike,\n// iv: BinaryLike,\n// options?: CipherGCMOptions\n// ): Decipher;\nexport function createDecipheriv(\n algorithm: string,\n key: BinaryLike,\n iv: BinaryLike | null,\n options?: Stream.TransformOptions\n): Decipher {\n return new Decipher(algorithm, key, options, iv);\n}\n\n// TODO(osp) This definitions cause typescript errors when using the API\n// commenting them out for now\n// export function createCipher(\n// algorithm: CipherCCMTypes,\n// password: BinaryLike,\n// options: CipherCCMOptions\n// ): Cipher;\n// export function createCipher(\n// algorithm: CipherGCMTypes,\n// password: BinaryLike,\n// options?: CipherGCMOptions\n// ): Cipher;\nexport function createCipher(\n algorithm: string,\n password: BinaryLike,\n options?: Stream.TransformOptions\n): Cipher {\n return new Cipher(algorithm, password, options);\n}\n\n// TODO(osp) on all the createCipheriv methods, node seems to use a \"KeyObject\" is seems to be a thread safe\n// object that creates keys and what not. Not sure if we should support it.\n// Fow now I replaced all of them to BinaryLike\n// export function createCipheriv(\n// algorithm: CipherCCMTypes,\n// key: BinaryLike,\n// iv: BinaryLike,\n// options: CipherCCMOptions\n// ): Cipher;\n// export function createCipheriv(\n// algorithm: CipherOCBTypes,\n// key: BinaryLike,\n// iv: BinaryLike,\n// options: CipherOCBOptions\n// ): CipherOCB;\n// export function createCipheriv(\n// algorithm: CipherGCMTypes,\n// key: BinaryLike,\n// iv: BinaryLike,\n// options?: CipherGCMOptions\n// ): Cipher;\nexport function createCipheriv(\n algorithm: string,\n key: BinaryLike,\n iv: BinaryLike | null,\n options?: Stream.TransformOptions\n): Cipher {\n return new Cipher(algorithm, key, options, iv);\n}\n"]}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
|
|
2
|
+
|
|
3
|
+
/* eslint-disable no-dupe-class-members */
|
|
4
|
+
import 'react-native';
|
|
5
|
+
import { NativeQuickCrypto } from './NativeQuickCrypto/NativeQuickCrypto';
|
|
6
|
+
import { toArrayBuffer } from './Utils';
|
|
7
|
+
import Stream from 'stream';
|
|
8
|
+
import { Buffer } from '@craftzdog/react-native-buffer';
|
|
9
|
+
global.process.nextTick = setImmediate;
|
|
10
|
+
const createInternalHash = NativeQuickCrypto.createHash;
|
|
11
|
+
export function createHash(algorithm, options) {
|
|
12
|
+
return new Hash(algorithm, options);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
class Hash extends Stream.Transform {
|
|
16
|
+
constructor(arg, options) {
|
|
17
|
+
super(options !== null && options !== void 0 ? options : undefined);
|
|
18
|
+
|
|
19
|
+
_defineProperty(this, "internalHash", void 0);
|
|
20
|
+
|
|
21
|
+
if (arg instanceof Hash) {
|
|
22
|
+
this.internalHash = arg.internalHash.copy(options === null || options === void 0 ? void 0 : options.outputLength);
|
|
23
|
+
} else {
|
|
24
|
+
this.internalHash = createInternalHash(arg, options === null || options === void 0 ? void 0 : options.outputLength);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
copy(options) {
|
|
29
|
+
const copy = new Hash(this, options);
|
|
30
|
+
return copy;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Updates the hash content with the given `data`, the encoding of which
|
|
34
|
+
* is given in `inputEncoding`.
|
|
35
|
+
* If `encoding` is not provided, and the `data` is a string, an
|
|
36
|
+
* encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored.
|
|
37
|
+
*
|
|
38
|
+
* This can be called many times with new data as it is streamed.
|
|
39
|
+
* @since v0.1.92
|
|
40
|
+
* @param inputEncoding The `encoding` of the `data` string.
|
|
41
|
+
*/
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
update(data, inputEncoding) {
|
|
45
|
+
if (data instanceof ArrayBuffer) {
|
|
46
|
+
this.internalHash.update(data);
|
|
47
|
+
return this;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const buffer = Buffer.from(data, inputEncoding);
|
|
51
|
+
this.internalHash.update(toArrayBuffer(buffer));
|
|
52
|
+
return this;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
_transform(chunk, encoding, callback) {
|
|
56
|
+
this.update(chunk, encoding);
|
|
57
|
+
callback();
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
_flush(callback) {
|
|
61
|
+
this.push(this.digest());
|
|
62
|
+
callback();
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Calculates the digest of all of the data passed to be hashed (using the `hash.update()` method).
|
|
66
|
+
* If `encoding` is provided a string will be returned; otherwise
|
|
67
|
+
* a `Buffer` is returned.
|
|
68
|
+
*
|
|
69
|
+
* The `Hash` object can not be used again after `hash.digest()` method has been
|
|
70
|
+
* called. Multiple calls will cause an error to be thrown.
|
|
71
|
+
* @since v0.1.92
|
|
72
|
+
* @param encoding The `encoding` of the return value.
|
|
73
|
+
*/
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
digest(encoding) {
|
|
77
|
+
const result = this.internalHash.digest();
|
|
78
|
+
|
|
79
|
+
if (encoding && encoding !== 'buffer') {
|
|
80
|
+
return Buffer.from(result).toString(encoding);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
return Buffer.from(result);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
}
|
|
87
|
+
//# sourceMappingURL=Hash.js.map
|