Add isBase{32, 58, 64} utils (#689)

* Add isBase{32, 58, 64} utils

* Allow empty inputs

* Add base64{Trim, Pad}

* isBase64

* Update assert messages

* Cleaup ifsCompat checks
This commit is contained in:
Jaco Greeff
2020-09-20 10:05:38 +02:00
committed by GitHub
parent 301eb587cb
commit e7c665e5da
19 changed files with 121 additions and 34 deletions
+3 -9
View File
@@ -24,20 +24,14 @@ const LOOKUP = BASE32_ALPHABET
* From the provided input, decode the base32 and return the result as an `Uint8Array`.
*/
export default function base32Decode (value: string, ipfsCompat = false): Uint8Array {
if (ipfsCompat) {
assert(value[0] === 'b', "Expected IPFS base32 identifier 'b' at string start");
validate(value, ipfsCompat);
value = value.substr(1);
}
validate(value);
const out = new Uint8Array((value.length * BITS_PER_CHAR / 8) | 0);
const out = new Uint8Array(((value.length - (ipfsCompat ? 1 : 0)) * BITS_PER_CHAR / 8) | 0);
let bits = 0;
let buffer = 0;
let written = 0;
for (let i = 0; i < value.length; ++i) {
for (let i = (ipfsCompat ? 1 : 0); i < value.length; ++i) {
buffer = (buffer << BITS_PER_CHAR) | LOOKUP[value[i]];
bits += BITS_PER_CHAR;
+1
View File
@@ -8,3 +8,4 @@
export { default as base32Decode } from './decode';
export { default as base32Encode } from './encode';
export { default as base32Validate } from './validate';
export { default as isBase32 } from './is';
+12
View File
@@ -0,0 +1,12 @@
// Copyright 2017-2020 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import validate from './validate';
export default function isBase32 (value?: string | null): boolean {
try {
return validate(value);
} catch (error) {
return false;
}
}
@@ -0,0 +1,12 @@
// Copyright 2017-2020 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { base32Validate } from '.';
describe('base32Validate', (): void => {
it('validates ipfs-compat encoded', (): void => {
expect(
() => base32Validate('bafkreigh2akiscaildcqabsyg3dfr6chu3fgpregiymsck7e7aqa4s52zy', true)
).not.toThrow();
});
});
+2 -2
View File
@@ -10,6 +10,6 @@ import { BASE32_ALPHABET } from './bs32';
* @description
* Validates the the supplied value is valid base32
*/
export default function base32Validate (value: string): true {
return validateChars('base32', BASE32_ALPHABET, value);
export default function base32Validate (value?: string | null, ipfsCompat = false): true {
return validateChars('base32', BASE32_ALPHABET, value, ipfsCompat ? 'b' : undefined);
}