Modernizes util.js

This commit is contained in:
Mahrud Sayrafi 2018-02-28 15:49:41 -08:00
parent 9275119dbc
commit 9e1236c04c
No known key found for this signature in database
GPG Key ID: C24071B956C3245F
41 changed files with 369 additions and 418 deletions

View File

@ -30,7 +30,7 @@ function node_hash(type) {
function hashjs_hash(hash) {
return function(data) {
return util.str2Uint8Array(util.hex2bin(hash().update(data).digest('hex')));
return util.str_to_Uint8Array(util.hex_to_str(hash().update(data).digest('hex')));
};
}
@ -51,7 +51,7 @@ if (nodeCrypto) { // Use Node native crypto for all hash functions
md5: md5,
/** @see module:rusha */
sha1: function(data) {
return util.str2Uint8Array(util.hex2bin(rusha.digest(data)));
return util.str_to_Uint8Array(util.hex_to_str(rusha.digest(data)));
},
/** @see module:hash.js */
sha224: hashjs_hash(sha224),

View File

@ -24,8 +24,8 @@ import util from '../../util.js';
* @param {String} entree string to hash
*/
export default function(entree) {
const hex = md5(util.Uint8Array2str(entree));
const bin = util.str2Uint8Array(util.hex2bin(hex));
const hex = md5(util.Uint8Array_to_str(entree));
const bin = util.str_to_Uint8Array(util.hex_to_str(hex));
return bin;
}

View File

@ -125,7 +125,7 @@ export default {
encode: function(algo, M, emLen) {
let i;
// Apply the hash function to the message M to produce a hash value H
const H = util.Uint8Array2str(hash.digest(algo, util.str2Uint8Array(M)));
const H = util.Uint8Array_to_str(hash.digest(algo, util.str_to_Uint8Array(M)));
if (H.length !== hash.getHashByteLength(algo)) {
throw new Error('Invalid hash length');
}
@ -155,7 +155,7 @@ export default {
PS +
String.fromCharCode(0x00) +
T;
return util.hexstrdump(EM);
return util.str_to_hex(EM);
}
}
};

View File

@ -63,9 +63,9 @@ export default {
// truncated) hash function result is treated as a number and used
// directly in the DSA signature algorithm.
const h = new BN(
util.str2Uint8Array(
util.str_to_Uint8Array(
util.getLeftNBits(
util.Uint8Array2str(hash.digest(hash_algo, m)), q.bitLength())));
util.Uint8Array_to_str(hash.digest(hash_algo, m)), q.bitLength())));
// FIPS-186-4, section 4.6:
// The values of r and s shall be checked to determine if r = 0 or s = 0.
// If either r = 0 or s = 0, a new value of k shall be generated, and the
@ -105,9 +105,9 @@ export default {
const redp = new BN.red(p);
const redq = new BN.red(q);
const h = new BN(
util.str2Uint8Array(
util.str_to_Uint8Array(
util.getLeftNBits(
util.Uint8Array2str(hash.digest(hash_algo, m)), q.bitLength())));
util.Uint8Array_to_str(hash.digest(hash_algo, m)), q.bitLength())));
const w = s.toRed(redq).redInvm(); // s**-1 mod q
if (zero.cmp(w) === 0) {
util.print_debug("invalid DSA Signature");

View File

@ -19,7 +19,10 @@
/**
* @requires bn.js
* @requires elliptic
* @requires crypto/public_key/elliptic/key
* @requires crypto/random
* @requires type/oid
* @requires enums
* @requires util
* @module crypto/public_key/elliptic/curve
@ -32,7 +35,6 @@ import random from '../../random';
import enums from '../../../enums';
import util from '../../../util';
import OID from '../../../type/oid';
import base64 from '../../../encoding/base64';
const webCrypto = util.getWebCrypto();
const nodeCrypto = util.getNodeCrypto();
@ -54,7 +56,7 @@ if (nodeCrypto) {
const curves = {
p256: {
oid: util.bin2str([0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07]),
oid: util.Uint8Array_to_str([0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07]),
keyType: enums.publicKey.ecdsa,
hash: enums.hash.sha256,
cipher: enums.symmetric.aes128,
@ -63,7 +65,7 @@ const curves = {
payloadSize: 32
},
p384: {
oid: util.bin2str([0x2B, 0x81, 0x04, 0x00, 0x22]),
oid: util.Uint8Array_to_str([0x2B, 0x81, 0x04, 0x00, 0x22]),
keyType: enums.publicKey.ecdsa,
hash: enums.hash.sha384,
cipher: enums.symmetric.aes192,
@ -72,7 +74,7 @@ const curves = {
payloadSize: 48
},
p521: {
oid: util.bin2str([0x2B, 0x81, 0x04, 0x00, 0x23]),
oid: util.Uint8Array_to_str([0x2B, 0x81, 0x04, 0x00, 0x23]),
keyType: enums.publicKey.ecdsa,
hash: enums.hash.sha512,
cipher: enums.symmetric.aes256,
@ -81,32 +83,32 @@ const curves = {
payloadSize: 66
},
secp256k1: {
oid: util.bin2str([0x2B, 0x81, 0x04, 0x00, 0x0A]),
oid: util.Uint8Array_to_str([0x2B, 0x81, 0x04, 0x00, 0x0A]),
keyType: enums.publicKey.ecdsa,
hash: enums.hash.sha256,
cipher: enums.symmetric.aes128,
node: false // FIXME when we replace jwk-to-pem or it supports this curve
},
ed25519: {
oid: util.bin2str([0x2B, 0x06, 0x01, 0x04, 0x01, 0xDA, 0x47, 0x0F, 0x01]),
oid: util.Uint8Array_to_str([0x2B, 0x06, 0x01, 0x04, 0x01, 0xDA, 0x47, 0x0F, 0x01]),
keyType: enums.publicKey.eddsa,
hash: enums.hash.sha512,
payloadSize: 32
},
curve25519: {
oid: util.bin2str([0x2B, 0x06, 0x01, 0x04, 0x01, 0x97, 0x55, 0x01, 0x05, 0x01]),
oid: util.Uint8Array_to_str([0x2B, 0x06, 0x01, 0x04, 0x01, 0x97, 0x55, 0x01, 0x05, 0x01]),
keyType: enums.publicKey.ecdsa,
hash: enums.hash.sha256,
cipher: enums.symmetric.aes128
},
brainpoolP256r1: { // TODO 1.3.36.3.3.2.8.1.1.7
oid: util.bin2str([0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x07])
oid: util.Uint8Array_to_str([0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x07])
},
brainpoolP384r1: { // TODO 1.3.36.3.3.2.8.1.1.11
oid: util.bin2str([0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0B])
oid: util.Uint8Array_to_str([0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0B])
},
brainpoolP512r1: { // TODO 1.3.36.3.3.2.8.1.1.13
oid: util.bin2str([0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0D])
oid: util.Uint8Array_to_str([0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0D])
}
};
@ -116,8 +118,8 @@ export default function Curve(oid_or_name, params) {
this.name = oid_or_name.toHex(); // by curve OID
} else if (enums.curve[oid_or_name]) {
this.name = oid_or_name; // by curve name
} else if (enums.curve[util.hexstrdump(oid_or_name)]) {
this.name = util.hexstrdump(oid_or_name); // by oid string
} else if (enums.curve[util.str_to_hex(oid_or_name)]) {
this.name = util.str_to_hex(oid_or_name); // by oid string
} else {
throw new Error('Not valid curve');
}
@ -172,7 +174,7 @@ Curve.prototype.genKeyPair = async function () {
if (!keyPair || !keyPair.priv) {
// elliptic fallback
const r = await this.curve.genKeyPair({ entropy: util.Uint8Array2str(random.getRandomBytes(32)) });
const r = await this.curve.genKeyPair({ entropy: util.Uint8Array_to_str(random.getRandomBytes(32)) });
const compact = this.curve.curve.type === 'edwards' || this.curve.curve.type === 'mont';
if (this.keyType === enums.publicKey.eddsa) {
keyPair = { secret: r.getSecret() };
@ -220,10 +222,10 @@ async function webGenKeyPair(name) {
return {
pub: {
x: base64.decode(publicKey.x, true),
y: base64.decode(publicKey.y, true)
x: util.b64_to_Uint8Array(publicKey.x, true),
y: util.b64_to_Uint8Array(publicKey.y, true)
},
priv: base64.decode(privateKey.d, true)
priv: util.b64_to_Uint8Array(privateKey.d, true)
};
}

View File

@ -46,7 +46,7 @@ function buildEcdhParam(public_algo, oid, cipher_algo, hash_algo, fingerprint) {
oid.write(),
new Uint8Array([public_algo]),
kdf_params.write(),
util.str2Uint8Array("Anonymous Sender "),
util.str_to_Uint8Array("Anonymous Sender "),
fingerprint
]);
}
@ -73,7 +73,7 @@ function kdf(hash_algo, X, length, param) {
* @return {{V: BN, C: BN}} Returns ephemeral key and encoded session key
*/
async function encrypt(oid, cipher_algo, hash_algo, m, Q, fingerprint) {
fingerprint = util.hex2Uint8Array(fingerprint);
fingerprint = util.hex_to_Uint8Array(fingerprint);
const curve = new Curve(oid);
const param = buildEcdhParam(enums.publicKey.ecdh, oid, cipher_algo, hash_algo, fingerprint);
cipher_algo = enums.read(enums.symmetric, cipher_algo);
@ -101,7 +101,7 @@ async function encrypt(oid, cipher_algo, hash_algo, m, Q, fingerprint) {
* @return {Uint8Array} Value derived from session
*/
async function decrypt(oid, cipher_algo, hash_algo, V, C, d, fingerprint) {
fingerprint = util.hex2Uint8Array(fingerprint);
fingerprint = util.hex_to_Uint8Array(fingerprint);
const curve = new Curve(oid);
const param = buildEcdhParam(enums.publicKey.ecdh, oid, cipher_algo, hash_algo, fingerprint);
cipher_algo = enums.read(enums.symmetric, cipher_algo);

View File

@ -23,7 +23,6 @@
* @requires crypto/hash
* @requires util
* @requires enums
* @requires encoding/base64
* @requires jwk-to-pem
* @requires asn1.js
* @module crypto/public_key/elliptic/key
@ -34,7 +33,6 @@ import { webCurves, nodeCurves } from './curves';
import hash from '../../hash';
import util from '../../../util';
import enums from '../../../enums';
import base64 from '../../../encoding/base64';
const webCrypto = util.getWebCrypto();
const nodeCrypto = util.getNodeCrypto();
@ -118,9 +116,9 @@ async function webSign(curve, hash_algo, message, keyPair) {
{
"kty": "EC",
"crv": webCurves[curve.name],
"x": base64.encode(new Uint8Array(keyPair.getPublic().getX().toArray('be', l)), true),
"y": base64.encode(new Uint8Array(keyPair.getPublic().getY().toArray('be', l)), true),
"d": base64.encode(new Uint8Array(keyPair.getPrivate().toArray('be', l)), true),
"x": util.Uint8Array_to_b64(new Uint8Array(keyPair.getPublic().getX().toArray('be', l)), true),
"y": util.Uint8Array_to_b64(new Uint8Array(keyPair.getPublic().getY().toArray('be', l)), true),
"d": util.Uint8Array_to_b64(new Uint8Array(keyPair.getPrivate().toArray('be', l)), true),
"use": "sig",
"kid": "ECDSA Private Key"
},
@ -158,8 +156,8 @@ async function webVerify(curve, hash_algo, { r, s }, message, publicKey) {
{
"kty": "EC",
"crv": webCurves[curve.name],
"x": base64.encode(new Uint8Array(publicKey.getX().toArray('be', l)), true),
"y": base64.encode(new Uint8Array(publicKey.getY().toArray('be', l)), true),
"x": util.Uint8Array_to_b64(new Uint8Array(publicKey.getX().toArray('be', l)), true),
"y": util.Uint8Array_to_b64(new Uint8Array(publicKey.getY().toArray('be', l)), true),
"use": "sig",
"kid": "ECDSA Public Key"
},
@ -186,13 +184,23 @@ async function webVerify(curve, hash_algo, { r, s }, message, publicKey) {
async function nodeSign(curve, hash_algo, message, keyPair) {
console.log({
"kty": "EC",
"crv": webCurves[curve.name],
"x": util.Uint8Array_to_b64(new Uint8Array(keyPair.getPublic().getX().toArray())),
"y": util.Uint8Array_to_b64(new Uint8Array(keyPair.getPublic().getY().toArray())),
"d": util.Uint8Array_to_b64(new Uint8Array(keyPair.getPrivate().toArray())),
"use": "sig",
"kid": "ECDSA Private Key"
});
const key = jwkToPem(
{
"kty": "EC",
"crv": webCurves[curve.name],
"x": base64.encode(new Uint8Array(keyPair.getPublic().getX().toArray())),
"y": base64.encode(new Uint8Array(keyPair.getPublic().getY().toArray())),
"d": base64.encode(new Uint8Array(keyPair.getPrivate().toArray())),
"x": util.Uint8Array_to_b64(new Uint8Array(keyPair.getPublic().getX().toArray())),
"y": util.Uint8Array_to_b64(new Uint8Array(keyPair.getPublic().getY().toArray())),
"d": util.Uint8Array_to_b64(new Uint8Array(keyPair.getPrivate().toArray())),
"use": "sig",
"kid": "ECDSA Private Key"
},
@ -215,8 +223,8 @@ async function nodeVerify(curve, hash_algo, { r, s }, message, publicKey) {
{
"kty": "EC",
"crv": webCurves[curve.name],
"x": base64.encode(new Uint8Array(publicKey.getX().toArray())),
"y": base64.encode(new Uint8Array(publicKey.getY().toArray())),
"x": util.Uint8Array_to_b64(new Uint8Array(publicKey.getX().toArray())),
"y": util.Uint8Array_to_b64(new Uint8Array(publicKey.getY().toArray())),
"use": "sig",
"kid": "ECDSA Public Key"
},

View File

@ -26,22 +26,12 @@
* @module crypto/public_key/rsa
*/
import BN from 'bn.js';
import prime from './prime';
import random from '../random';
import config from '../../config';
import util from '../../util';
const two = new BN(2);
// TODO use this is ../../encoding/base64.js and ./elliptic/{key,curve}.js
function b64toBN(base64url) {
const base64 = base64url.replace(/\-/g, '+').replace(/_/g, '/');
const hex = util.hexstrdump(atob(base64));
return new BN(hex, 16);
}
// Helper for IE11 KeyOperation objects
function promisifyIE11Op(keyObj, err) {
if (typeof keyObj.then !== 'function') { // IE11 KeyOperation
@ -127,7 +117,7 @@ export default {
let blinder;
let unblinder;
if (config.rsa_blinding) {
unblinder = random.getRandomBN(two, n).toRed(nred);
unblinder = random.getRandomBN(new BN(2), n).toRed(nred);
blinder = unblinder.redInvm().redPow(e);
m = m.toRed(nred).redMul(blinder).fromRed();
}
@ -202,11 +192,11 @@ export default {
// map JWK parameters to BN
key = {};
key.n = b64toBN(jwk.n);
key.n = new BN(util.b64_to_Uint8Array(jwk.n));
key.e = E;
key.d = b64toBN(jwk.d);
key.p = b64toBN(jwk.p);
key.q = b64toBN(jwk.q);
key.d = new BN(util.b64_to_Uint8Array(jwk.d));
key.p = new BN(util.b64_to_Uint8Array(jwk.p));
key.q = new BN(util.b64_to_Uint8Array(jwk.q));
key.u = key.p.invm(key.q);
return key;
}

View File

@ -35,8 +35,8 @@ export default {
const n = pub_MPIs[0].toBN();
const e = pub_MPIs[1].toBN();
const EM = publicKey.rsa.verify(m, n, e);
const EM2 = pkcs1.emsa.encode(hash_algo, util.Uint8Array2str(data), n.byteLength());
return util.hexidump(EM) === EM2;
const EM2 = pkcs1.emsa.encode(hash_algo, util.Uint8Array_to_str(data), n.byteLength());
return util.Uint8Array_to_hex(EM) === EM2;
}
case enums.publicKey.dsa: {
const r = msg_MPIs[0].toBN();
@ -86,10 +86,10 @@ export default {
const n = key_params[0].toBN();
const e = key_params[1].toBN();
const d = key_params[2].toBN();
data = util.Uint8Array2str(data);
data = util.Uint8Array_to_str(data);
const m = new BN(pkcs1.emsa.encode(hash_algo, data, n.byteLength()), 16);
const signature = publicKey.rsa.sign(m, n, e, d);
return util.Uint8Array2MPI(signature);
return util.Uint8Array_to_MPI(signature);
}
case enums.publicKey.dsa: {
const p = key_params[0].toBN();
@ -98,8 +98,8 @@ export default {
const x = key_params[4].toBN();
const signature = publicKey.dsa.sign(hash_algo, data, g, p, q, x);
return util.concatUint8Array([
util.Uint8Array2MPI(signature.r),
util.Uint8Array2MPI(signature.s)
util.Uint8Array_to_MPI(signature.r),
util.Uint8Array_to_MPI(signature.s)
]);
}
case enums.publicKey.elgamal: {
@ -110,8 +110,8 @@ export default {
const d = key_params[2].toUint8Array();
const signature = await publicKey.elliptic.ecdsa.sign(oid, hash_algo, data, d);
return util.concatUint8Array([
util.Uint8Array2MPI(signature.r),
util.Uint8Array2MPI(signature.s)
util.Uint8Array_to_MPI(signature.r),
util.Uint8Array_to_MPI(signature.s)
]);
}
case enums.publicKey.eddsa: {
@ -119,8 +119,8 @@ export default {
const d = Array.from(key_params[2].toUint8Array('be', 32));
const signature = await publicKey.elliptic.eddsa.sign(oid, hash_algo, data, d);
return util.concatUint8Array([
util.Uint8Array2MPI(signature.R),
util.Uint8Array2MPI(signature.S)
util.Uint8Array_to_MPI(signature.R),
util.Uint8Array_to_MPI(signature.S)
]);
}
default:

View File

@ -18,6 +18,7 @@
/**
* @fileoverview This class implements a client for the OpenPGP HTTP Keyserver Protocol (HKP)
* in order to lookup and upload keys on standard public key servers.
* @module hkp
*/
import config from './config';

View File

@ -235,7 +235,7 @@ Key.prototype.getUserIds = function() {
const userids = [];
for (let i = 0; i < this.users.length; i++) {
if (this.users[i].userId) {
userids.push(util.Uint8Array2str(this.users[i].userId.write()));
userids.push(util.Uint8Array_to_str(this.users[i].userId.write()));
}
}
return userids;
@ -1305,7 +1305,7 @@ async function wrapKeyObject(secretKeyPacket, secretSubkeyPacket, options) {
await Promise.all(options.userIds.map(async function(userId, index) {
const userIdPacket = new packet.Userid();
userIdPacket.read(util.str2Uint8Array(userId));
userIdPacket.read(util.str_to_Uint8Array(userId));
const dataToSign = {};
dataToSign.userid = userIdPacket;

View File

@ -188,7 +188,7 @@ Message.prototype.decryptSessionKeys = function(privateKeys, passwords) {
if (keyPackets.length > 1) {
const seen = {};
keyPackets = keyPackets.filter(function(item) {
const k = item.sessionKeyAlgorithm + util.Uint8Array2str(item.sessionKey);
const k = item.sessionKeyAlgorithm + util.Uint8Array_to_str(item.sessionKey);
if (seen.hasOwnProperty(k)) {
return false;
}
@ -622,7 +622,7 @@ export function read(input) {
*/
export function readSignedContent(content, detachedSignature) {
const literalDataPacket = new packet.Literal();
literalDataPacket.setBytes(util.str2Uint8Array(content), enums.read(enums.literal, enums.literal.binary));
literalDataPacket.setBytes(util.str_to_Uint8Array(content), enums.read(enums.literal, enums.literal.binary));
const packetlist = new packet.List();
packetlist.push(literalDataPacket);
const input = armor.decode(detachedSignature).data;

View File

@ -19,6 +19,7 @@
* @fileoverview This module implements packet list cloning required to
* pass certain object types between the web worker and main thread using
* the structured cloning algorithm.
* @module packet/clone
*/
import { Key } from '../key';

View File

@ -50,7 +50,7 @@ Literal.prototype.setText = function(text) {
// normalize EOL to \r\n
text = text.replace(/\r\n/g, '\n').replace(/\r/g, '\n').replace(/\n/g, '\r\n');
// encode UTF8
this.data = this.format === 'utf8' ? util.str2Uint8Array(util.encode_utf8(text)) : util.str2Uint8Array(text);
this.data = this.format === 'utf8' ? util.str_to_Uint8Array(util.encode_utf8(text)) : util.str_to_Uint8Array(text);
};
/**
@ -60,7 +60,7 @@ Literal.prototype.setText = function(text) {
*/
Literal.prototype.getText = function() {
// decode UTF8
const text = util.decode_utf8(util.Uint8Array2str(this.data));
const text = util.decode_utf8(util.Uint8Array_to_str(this.data));
// normalize EOL to \n
return text.replace(/\r\n/g, '\n');
};
@ -114,7 +114,7 @@ Literal.prototype.read = function(bytes) {
const format = enums.read(enums.literal, bytes[0]);
const filename_len = bytes[1];
this.filename = util.decode_utf8(util.Uint8Array2str(bytes.subarray(2, 2 + filename_len)));
this.filename = util.decode_utf8(util.Uint8Array_to_str(bytes.subarray(2, 2 + filename_len)));
this.date = util.readDate(bytes.subarray(2 + filename_len, 2 + filename_len + 4));
@ -129,7 +129,7 @@ Literal.prototype.read = function(bytes) {
* @return {Uint8Array} Uint8Array representation of the packet
*/
Literal.prototype.write = function() {
const filename = util.str2Uint8Array(util.encode_utf8(this.filename));
const filename = util.str_to_Uint8Array(util.encode_utf8(this.filename));
const filename_length = new Uint8Array([filename.length]);
const format = new Uint8Array([enums.write(enums.literal, this.format)]);

View File

@ -159,7 +159,7 @@ PublicKey.prototype.getKeyId = function () {
}
this.keyid = new type_keyid();
if (this.version === 4) {
this.keyid.read(util.str2Uint8Array(util.hex2bin(this.getFingerprint()).substr(12, 8)));
this.keyid.read(util.str_to_Uint8Array(util.hex_to_str(this.getFingerprint()).substr(12, 8)));
} else if (this.version === 3) {
const arr = this.params[0].write();
this.keyid.read(arr.subarray(arr.length - 8, arr.length));
@ -178,16 +178,16 @@ PublicKey.prototype.getFingerprint = function () {
let toHash = '';
if (this.version === 4) {
toHash = this.writeOld();
this.fingerprint = util.Uint8Array2str(crypto.hash.sha1(toHash));
this.fingerprint = util.Uint8Array_to_str(crypto.hash.sha1(toHash));
} else if (this.version === 3) {
const algo = enums.write(enums.publicKey, this.algorithm);
const paramCount = crypto.getPubKeyParamTypes(algo).length;
for (let i = 0; i < paramCount; i++) {
toHash += this.params[i].toString();
}
this.fingerprint = util.Uint8Array2str(crypto.hash.md5(util.str2Uint8Array(toHash)));
this.fingerprint = util.Uint8Array_to_str(crypto.hash.md5(util.str_to_Uint8Array(toHash)));
}
this.fingerprint = util.hexstrdump(this.fingerprint);
this.fingerprint = util.str_to_hex(this.fingerprint);
return this.fingerprint;
};

View File

@ -103,9 +103,9 @@ PublicKeyEncryptedSessionKey.prototype.write = function () {
PublicKeyEncryptedSessionKey.prototype.encrypt = async function (key) {
let data = String.fromCharCode(enums.write(enums.symmetric, this.sessionKeyAlgorithm));
data += util.Uint8Array2str(this.sessionKey);
data += util.Uint8Array_to_str(this.sessionKey);
const checksum = util.calc_checksum(this.sessionKey);
data += util.Uint8Array2str(util.writeNumber(checksum, 2));
data += util.Uint8Array_to_str(util.writeNumber(checksum, 2));
let toEncrypt;
const algo = enums.write(enums.publicKey, this.publicKeyAlgorithm);
@ -136,13 +136,13 @@ PublicKeyEncryptedSessionKey.prototype.decrypt = async function (key) {
let decoded;
if (algo === enums.publicKey.ecdh) {
decoded = crypto.pkcs5.decode(result.toString());
checksum = util.readNumber(util.str2Uint8Array(decoded.substr(decoded.length - 2)));
checksum = util.readNumber(util.str_to_Uint8Array(decoded.substr(decoded.length - 2)));
} else {
decoded = crypto.pkcs1.eme.decode(result.toString());
checksum = util.readNumber(result.toUint8Array().slice(result.byteLength() - 2));
}
key = util.str2Uint8Array(decoded.substring(1, decoded.length - 2));
key = util.str_to_Uint8Array(decoded.substring(1, decoded.length - 2));
if (checksum !== util.calc_checksum(key)) {
throw new Error('Checksum mismatch');

View File

@ -76,9 +76,9 @@ function parse_cleartext_params(hash_algorithm, cleartext, algorithm) {
const hashlen = get_hash_len(hash_algorithm);
const hashfn = get_hash_fn(hash_algorithm);
const hashtext = util.Uint8Array2str(cleartext.subarray(cleartext.length - hashlen, cleartext.length));
const hashtext = util.Uint8Array_to_str(cleartext.subarray(cleartext.length - hashlen, cleartext.length));
cleartext = cleartext.subarray(0, cleartext.length - hashlen);
const hash = util.Uint8Array2str(hashfn(cleartext));
const hash = util.Uint8Array_to_str(hashfn(cleartext));
if (hash !== hashtext) {
return new Error("Hash mismatch.");

View File

@ -280,7 +280,7 @@ Signature.prototype.write_all_sub_packets = function () {
arr.push(write_sub_packet(sub.key_expiration_time, util.writeNumber(this.keyExpirationTime, 4)));
}
if (this.preferredSymmetricAlgorithms !== null) {
bytes = util.str2Uint8Array(util.bin2str(this.preferredSymmetricAlgorithms));
bytes = util.str_to_Uint8Array(util.Uint8Array_to_str(this.preferredSymmetricAlgorithms));
arr.push(write_sub_packet(sub.preferred_symmetric_algorithms, bytes));
}
if (this.revocationKeyClass !== null) {
@ -300,51 +300,51 @@ Signature.prototype.write_all_sub_packets = function () {
bytes.push(util.writeNumber(name.length, 2));
// 2 octets of value length
bytes.push(util.writeNumber(value.length, 2));
bytes.push(util.str2Uint8Array(name + value));
bytes.push(util.str_to_Uint8Array(name + value));
bytes = util.concatUint8Array(bytes);
arr.push(write_sub_packet(sub.notation_data, bytes));
}
}
}
if (this.preferredHashAlgorithms !== null) {
bytes = util.str2Uint8Array(util.bin2str(this.preferredHashAlgorithms));
bytes = util.str_to_Uint8Array(util.Uint8Array_to_str(this.preferredHashAlgorithms));
arr.push(write_sub_packet(sub.preferred_hash_algorithms, bytes));
}
if (this.preferredCompressionAlgorithms !== null) {
bytes = util.str2Uint8Array(util.bin2str(this.preferredCompressionAlgorithms));
bytes = util.str_to_Uint8Array(util.Uint8Array_to_str(this.preferredCompressionAlgorithms));
arr.push(write_sub_packet(sub.preferred_compression_algorithms, bytes));
}
if (this.keyServerPreferences !== null) {
bytes = util.str2Uint8Array(util.bin2str(this.keyServerPreferences));
bytes = util.str_to_Uint8Array(util.Uint8Array_to_str(this.keyServerPreferences));
arr.push(write_sub_packet(sub.key_server_preferences, bytes));
}
if (this.preferredKeyServer !== null) {
arr.push(write_sub_packet(sub.preferred_key_server, util.str2Uint8Array(this.preferredKeyServer)));
arr.push(write_sub_packet(sub.preferred_key_server, util.str_to_Uint8Array(this.preferredKeyServer)));
}
if (this.isPrimaryUserID !== null) {
arr.push(write_sub_packet(sub.primary_user_id, new Uint8Array([this.isPrimaryUserID ? 1 : 0])));
}
if (this.policyURI !== null) {
arr.push(write_sub_packet(sub.policy_uri, util.str2Uint8Array(this.policyURI)));
arr.push(write_sub_packet(sub.policy_uri, util.str_to_Uint8Array(this.policyURI)));
}
if (this.keyFlags !== null) {
bytes = util.str2Uint8Array(util.bin2str(this.keyFlags));
bytes = util.str_to_Uint8Array(util.Uint8Array_to_str(this.keyFlags));
arr.push(write_sub_packet(sub.key_flags, bytes));
}
if (this.signersUserId !== null) {
arr.push(write_sub_packet(sub.signers_user_id, util.str2Uint8Array(this.signersUserId)));
arr.push(write_sub_packet(sub.signers_user_id, util.str_to_Uint8Array(this.signersUserId)));
}
if (this.reasonForRevocationFlag !== null) {
bytes = util.str2Uint8Array(String.fromCharCode(this.reasonForRevocationFlag) + this.reasonForRevocationString);
bytes = util.str_to_Uint8Array(String.fromCharCode(this.reasonForRevocationFlag) + this.reasonForRevocationString);
arr.push(write_sub_packet(sub.reason_for_revocation, bytes));
}
if (this.features !== null) {
bytes = util.str2Uint8Array(util.bin2str(this.features));
bytes = util.str_to_Uint8Array(util.Uint8Array_to_str(this.features));
arr.push(write_sub_packet(sub.features, bytes));
}
if (this.signatureTargetPublicKeyAlgorithm !== null) {
bytes = [new Uint8Array([this.signatureTargetPublicKeyAlgorithm, this.signatureTargetHashAlgorithm])];
bytes.push(util.str2Uint8Array(this.signatureTargetHash));
bytes.push(util.str_to_Uint8Array(this.signatureTargetHash));
bytes = util.concatUint8Array(bytes);
arr.push(write_sub_packet(sub.signature_target, bytes));
}
@ -459,8 +459,8 @@ Signature.prototype.read_sub_packet = function (bytes) {
const n = util.readNumber(bytes.subarray(mypos, mypos + 2));
mypos += 2;
const name = util.Uint8Array2str(bytes.subarray(mypos, mypos + m));
const value = util.Uint8Array2str(bytes.subarray(mypos + m, mypos + m + n));
const name = util.Uint8Array_to_str(bytes.subarray(mypos, mypos + m));
const value = util.Uint8Array_to_str(bytes.subarray(mypos + m, mypos + m + n));
this.notation = this.notation || {};
this.notation[name] = value;
@ -482,7 +482,7 @@ Signature.prototype.read_sub_packet = function (bytes) {
break;
case 24:
// Preferred Key Server
this.preferredKeyServer = util.Uint8Array2str(bytes.subarray(mypos, bytes.length));
this.preferredKeyServer = util.Uint8Array_to_str(bytes.subarray(mypos, bytes.length));
break;
case 25:
// Primary User ID
@ -490,7 +490,7 @@ Signature.prototype.read_sub_packet = function (bytes) {
break;
case 26:
// Policy URI
this.policyURI = util.Uint8Array2str(bytes.subarray(mypos, bytes.length));
this.policyURI = util.Uint8Array_to_str(bytes.subarray(mypos, bytes.length));
break;
case 27:
// Key Flags
@ -498,12 +498,12 @@ Signature.prototype.read_sub_packet = function (bytes) {
break;
case 28:
// Signer's User ID
this.signersUserId += util.Uint8Array2str(bytes.subarray(mypos, bytes.length));
this.signersUserId += util.Uint8Array_to_str(bytes.subarray(mypos, bytes.length));
break;
case 29:
// Reason for Revocation
this.reasonForRevocationFlag = bytes[mypos++];
this.reasonForRevocationString = util.Uint8Array2str(bytes.subarray(mypos, bytes.length));
this.reasonForRevocationString = util.Uint8Array_to_str(bytes.subarray(mypos, bytes.length));
break;
case 30:
// Features
@ -517,7 +517,7 @@ Signature.prototype.read_sub_packet = function (bytes) {
const len = crypto.getHashByteLength(this.signatureTargetHashAlgorithm);
this.signatureTargetHash = util.Uint8Array2str(bytes.subarray(mypos, mypos + len));
this.signatureTargetHash = util.Uint8Array_to_str(bytes.subarray(mypos, mypos + len));
break;
}
case 32:

View File

@ -121,8 +121,8 @@ SymEncryptedIntegrityProtected.prototype.decrypt = function (sessionKeyAlgorithm
const prefix = crypto.cfb.mdc(sessionKeyAlgorithm, key, this.encrypted);
const bytes = decrypted.subarray(0, decrypted.length - 20);
const tohash = util.concatUint8Array([prefix, bytes]);
this.hash = util.Uint8Array2str(crypto.hash.sha1(tohash));
const mdc = util.Uint8Array2str(decrypted.subarray(decrypted.length - 20, decrypted.length));
this.hash = util.Uint8Array_to_str(crypto.hash.sha1(tohash));
const mdc = util.Uint8Array_to_str(decrypted.subarray(decrypted.length - 20, decrypted.length));
if (this.hash !== mdc) {
throw new Error('Modification detected.');

View File

@ -58,7 +58,7 @@ UserAttribute.prototype.read = function(bytes) {
const len = packet.readSimpleLength(bytes.subarray(i, bytes.length));
i += len.offset;
this.attributes.push(util.Uint8Array2str(bytes.subarray(i, i + len.len)));
this.attributes.push(util.Uint8Array_to_str(bytes.subarray(i, i + len.len)));
i += len.len;
}
};
@ -71,7 +71,7 @@ UserAttribute.prototype.write = function() {
const arr = [];
for (let i = 0; i < this.attributes.length; i++) {
arr.push(packet.writeSimpleLength(this.attributes[i].length));
arr.push(util.str2Uint8Array(this.attributes[i]));
arr.push(util.str_to_Uint8Array(this.attributes[i]));
}
return util.concatUint8Array(arr);
};

View File

@ -48,7 +48,7 @@ export default function Userid() {
* @param {Uint8Array} input payload of a tag 13 packet
*/
Userid.prototype.read = function (bytes) {
this.userid = util.decode_utf8(util.Uint8Array2str(bytes));
this.userid = util.decode_utf8(util.Uint8Array_to_str(bytes));
};
/**
@ -56,5 +56,5 @@ Userid.prototype.read = function (bytes) {
* @return {Uint8Array} binary representation
*/
Userid.prototype.write = function () {
return util.str2Uint8Array(util.encode_utf8(this.userid));
return util.str_to_Uint8Array(util.encode_utf8(this.userid));
};

View File

@ -31,7 +31,7 @@ export default function ECDHSymmetricKey(data) {
if (typeof data === 'undefined') {
data = new Uint8Array([]);
} else if (util.isString(data)) {
data = util.str2Uint8Array(data);
data = util.str_to_Uint8Array(data);
} else {
data = new Uint8Array(data);
}

View File

@ -41,15 +41,15 @@ export default function Keyid() {
* @param {Uint8Array} input Input to read the key id from
*/
Keyid.prototype.read = function(bytes) {
this.bytes = util.Uint8Array2str(bytes.subarray(0, 8));
this.bytes = util.Uint8Array_to_str(bytes.subarray(0, 8));
};
Keyid.prototype.write = function() {
return util.str2Uint8Array(this.bytes);
return util.str_to_Uint8Array(this.bytes);
};
Keyid.prototype.toHex = function() {
return util.hexstrdump(this.bytes);
return util.str_to_hex(this.bytes);
};
Keyid.prototype.equals = function(keyid) {
@ -76,7 +76,7 @@ Keyid.fromClone = function (clone) {
Keyid.fromId = function (hex) {
const keyid = new Keyid();
keyid.read(util.str2Uint8Array(util.hex2bin(hex)));
keyid.read(util.str_to_Uint8Array(util.hex_to_str(hex)));
return keyid;
};

View File

@ -60,7 +60,7 @@ export default function MPI(data) {
*/
MPI.prototype.read = function (bytes, endian='be') {
if (util.isString(bytes)) {
bytes = util.str2Uint8Array(bytes);
bytes = util.str_to_Uint8Array(bytes);
}
const bits = (bytes[0] << 8) | bytes[1];
@ -80,7 +80,7 @@ MPI.prototype.read = function (bytes, endian='be') {
* @return {Uint8Aray} mpi Byte representation
*/
MPI.prototype.write = function (endian, length) {
return util.Uint8Array2MPI(this.toUint8Array(endian, length));
return util.Uint8Array_to_MPI(this.toUint8Array(endian, length));
};
MPI.prototype.bitLength = function () {
@ -119,11 +119,11 @@ MPI.prototype.fromUint8Array = function (bytes, endian='be') {
};
MPI.prototype.toString = function () {
return util.Uint8Array2str(this.toUint8Array());
return util.Uint8Array_to_str(this.toUint8Array());
};
MPI.prototype.fromString = function (str, endian='be') {
this.fromUint8Array(util.str2Uint8Array(str), endian);
this.fromUint8Array(util.str_to_Uint8Array(str), endian);
};
MPI.prototype.toBN = function () {

View File

@ -37,9 +37,9 @@ function OID(oid) {
} else if (typeof oid === 'undefined') {
oid = '';
} else if (util.isArray(oid)) {
oid = util.bin2str(oid);
oid = util.Uint8Array_to_str(oid);
} else if (util.isUint8Array(oid)) {
oid = util.Uint8Array2str(oid);
oid = util.Uint8Array_to_str(oid);
}
this.oid = oid;
}
@ -53,7 +53,7 @@ OID.prototype.read = function (input) {
if (input.length >= 1) {
const length = input[0];
if (input.length >= 1+length) {
this.oid = util.Uint8Array2str(input.subarray(1, 1+length));
this.oid = util.Uint8Array_to_str(input.subarray(1, 1+length));
return 1+this.oid.length;
}
}
@ -65,7 +65,7 @@ OID.prototype.read = function (input) {
* @return {Uint8Array} Array with the serialized value the OID
*/
OID.prototype.write = function () {
return util.str2Uint8Array(String.fromCharCode(this.oid.length)+this.oid);
return util.str_to_Uint8Array(String.fromCharCode(this.oid.length)+this.oid);
};
/**
@ -73,7 +73,7 @@ OID.prototype.write = function () {
* @return {string} String with the hex value of the OID
*/
OID.prototype.toHex = function() {
return util.hexstrdump(this.oid);
return util.str_to_hex(this.oid);
};
/**

View File

@ -84,7 +84,7 @@ S2K.prototype.read = function (bytes) {
break;
case 'gnu':
if (util.Uint8Array2str(bytes.subarray(i, 3)) === "GNU") {
if (util.Uint8Array_to_str(bytes.subarray(i, 3)) === "GNU") {
i += 3; // GNU
const gnuExtType = 1000 + bytes[i++];
if (gnuExtType === 1001) {
@ -140,7 +140,7 @@ S2K.prototype.write = function () {
* hashAlgorithm hash length
*/
S2K.prototype.produce_key = function (passphrase, numBytes) {
passphrase = util.str2Uint8Array(util.encode_utf8(passphrase));
passphrase = util.str_to_Uint8Array(util.encode_utf8(passphrase));
function round(prefix, s2k) {
const algorithm = enums.write(enums.hash, s2k.algorithm);

View File

@ -99,32 +99,12 @@ export default {
return time === null ? time : new Date(Math.floor(+time / 1000) * 1000);
},
hexdump: function (str) {
const r = [];
const e = str.length;
let c = 0;
let h;
let i = 0;
while (c < e) {
h = str.charCodeAt(c++).toString(16);
while (h.length < 2) {
h = "0" + h;
}
r.push(" " + h);
i++;
if (i % 32 === 0) {
r.push("\n ");
}
}
return r.join('');
},
/**
* Create hexstring from a binary
* Create hex string from a binary
* @param {String} str String to convert
* @return {String} String containing the hexadecimal values
*/
hexstrdump: function (str) {
str_to_hex: function (str) {
if (str === null) {
return "";
}
@ -145,9 +125,9 @@ export default {
/**
* Create binary string from a hex encoded string
* @param {String} str Hex string to convert
* @return {String} String containing the binary values
* @return {String}
*/
hex2bin: function (hex) {
hex_to_str: function (hex) {
let str = '';
for (let i = 0; i < hex.length; i += 2) {
str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
@ -155,27 +135,68 @@ export default {
return str;
},
/**
* Convert a Uint8Array to an MPI-formatted Uint8Array.
* Note: the output is **not** an MPI object.
* @see {@link module:type/mpi/MPI.fromUint8Array}
* @see {@link module:type/mpi/MPI.toUint8Array}
* @param {Uint8Array} bin An array of 8-bit integers to convert
* @return {Uint8Array} MPI-formatted Uint8Array
*/
Uint8Array_to_MPI: function (bin) {
const size = (bin.length - 1) * 8 + this.nbits(bin[0]);
const prefix = Uint8Array.from([(size & 0xFF00) >> 8, size & 0xFF]);
return this.concatUint8Array([prefix, bin]);
},
hex2Uint8Array: function (hex) {
const result = new Uint8Array(hex.length/2);
for (let k=0; k<hex.length/2; k++) {
result[k] = parseInt(hex.substr(2*k, 2), 16);
/**
* Convert a Base-64 encoded string an array of 8-bit integer
*
* Note: accepts both Radix-64 and URL-safe strings
* @param {String} base64 Base-64 encoded string to convert
* @return {Uint8Array} An array of 8-bit integers
*/
b64_to_Uint8Array: function (base64) {
const str = atob(base64.replace(/\-/g, '+').replace(/_/g, '/'));
return this.str_to_Uint8Array(str);
},
/**
* Convert an array of 8-bit integer to a Base-64 encoded string
* @param {Uint8Array} bytes An array of 8-bit integers to convert
* @param {bool} url If true, output is URL-safe
* @return {String} Base-64 encoded string
*/
Uint8Array_to_b64: function (bytes, url) {
const base64 = btoa(this.Uint8Array_to_str(bytes));
return url ? base64.replace(/\+/g, '-').replace(/\//g, '_') : base64;
},
/**
* Convert a hex string to an array of 8-bit integers
* @param {String} hex A hex string to convert
* @return {Uint8Array} An array of 8-bit integers
*/
hex_to_Uint8Array: function (hex) {
const result = new Uint8Array(hex.length >> 1);
for (let k = 0; k < hex.length >> 1; k++) {
result[k] = parseInt(hex.substr(k << 1, 2), 16);
}
return result;
},
/**
* Creating a hex string from an binary array of integers (0..255)
* @param {String} str Array of bytes to convert
* Convert an array of 8-bit integers to a hex string
* @param {Uint8Array} bytes Array of 8-bit integers to convert
* @return {String} Hexadecimal representation of the array
*/
hexidump: function (str) {
Uint8Array_to_hex: function (bytes) {
const r = [];
const e = str.length;
const e = bytes.length;
let c = 0;
let h;
while (c < e) {
h = str[c++].toString(16);
h = bytes[c++].toString(16);
while (h.length < 2) {
h = "0" + h;
}
@ -184,6 +205,39 @@ export default {
return r.join('');
},
/**
* Convert a string to an array of 8-bit integers
* @param {String} str String to convert
* @return {Uint8Array} An array of 8-bit integers
*/
str_to_Uint8Array: function (str) {
if (!this.isString(str)) {
throw new Error('str_to_Uint8Array: Data must be in the form of a string');
}
const result = new Uint8Array(str.length);
for (let i = 0; i < str.length; i++) {
result[i] = str.charCodeAt(i);
}
return result;
},
/**
* Convert an array of 8-bit integers to a string
* @param {Uint8Array} bytes An array of 8-bit integers to convert
* @return {String} String representation of the array
*/
Uint8Array_to_str: function (bytes) {
bytes = new Uint8Array(bytes);
const result = [];
const bs = 1 << 14;
const j = bytes.length;
for (let i = 0; i < j; i += bs) {
result.push(String.fromCharCode.apply(String, bytes.subarray(i, i+bs < j ? i+bs : j)));
}
return result.join('');
},
/**
* Convert a native javascript string to a string of utf8 bytes
@ -210,130 +264,20 @@ export default {
}
},
/**
* Convert an array of integers(0.255) to a string
* @param {Array<Integer>} bin An array of (binary) integers to convert
* @return {String} The string representation of the array
*/
bin2str: function (bin) {
const result = [];
for (let i = 0; i < bin.length; i++) {
result[i] = String.fromCharCode(bin[i]);
}
return result.join('');
},
/**
* Convert a string to an array of integers(0.255)
* @param {String} str String to convert
* @return {Array<Integer>} An array of (binary) integers
*/
str2bin: function (str) {
const result = [];
for (let i = 0; i < str.length; i++) {
result[i] = str.charCodeAt(i);
}
return result;
},
/**
* Convert a string to a Uint8Array
* @param {String} str String to convert
* @return {Uint8Array} The array of (binary) integers
*/
str2Uint8Array: function (str) {
if (typeof str !== 'string' && !String.prototype.isPrototypeOf(str)) {
throw new Error('str2Uint8Array: Data must be in the form of a string');
}
const result = new Uint8Array(str.length);
for (let i = 0; i < str.length; i++) {
result[i] = str.charCodeAt(i);
}
return result;
},
/**
* Convert a Uint8Array to a string. This currently functions
* the same as bin2str.
* @function module:util.Uint8Array2str
* @param {Uint8Array} bin An array of (binary) integers to convert
* @return {String} String representation of the array
*/
Uint8Array2str: function (bin) {
if (!Uint8Array.prototype.isPrototypeOf(bin)) {
throw new Error('Uint8Array2str: Data must be in the form of a Uint8Array');
}
const result = [];
const bs = 16384;
const j = bin.length;
for (let i = 0; i < j; i += bs) {
result.push(String.fromCharCode.apply(String, bin.subarray(i, i+bs < j ? i+bs : j)));
}
return result.join('');
},
// returns bit length of the integer x
nbits: function (x) {
let r = 1;
let t = x >>> 16;
if (t !== 0) {
x = t;
r += 16;
}
t = x >> 8;
if (t !== 0) {
x = t;
r += 8;
}
t = x >> 4;
if (t !== 0) {
x = t;
r += 4;
}
t = x >> 2;
if (t !== 0) {
x = t;
r += 2;
}
t = x >> 1;
if (t !== 0) {
x = t;
r += 1;
}
return r;
},
/**
* Convert a Uint8Array to an MPI array.
* @function module:util.Uint8Array2MPI
* @param {Uint8Array} bin An array of (binary) integers to convert
* @return {Uint8Array} MPI-formatted Uint8Array
*/
Uint8Array2MPI: function (bin) {
const size = (bin.length - 1) * 8 + this.nbits(bin[0]);
const prefix = Uint8Array.from([(size & 0xFF00) >> 8, size & 0xFF]);
return this.concatUint8Array([prefix, bin]);
},
/**
* Concat Uint8arrays
* @function module:util.concatUint8Array
* @param {Array<Uint8array>} Array of Uint8Arrays to concatenate
* @return {Uint8array} Concatenated array
*/
concatUint8Array: function (arrays) {
let totalLength = 0;
arrays.forEach(function (element) {
if (!Uint8Array.prototype.isPrototypeOf(element)) {
for (let i = 0; i < arrays.length; i++) {
if (!this.isUint8Array(arrays[i])) {
throw new Error('concatUint8Array: Data must be in the form of a Uint8Array');
}
totalLength += element.length;
});
totalLength += arrays[i].length;
}
const result = new Uint8Array(totalLength);
let pos = 0;
@ -347,12 +291,11 @@ export default {
/**
* Deep copy Uint8Array
* @function module:util.copyUint8Array
* @param {Uint8Array} Array to copy
* @return {Uint8Array} new Uint8Array
*/
copyUint8Array: function (array) {
if (!Uint8Array.prototype.isPrototypeOf(array)) {
if (!this.isUint8Array(array)) {
throw new Error('Data must be in the form of a Uint8Array');
}
@ -363,13 +306,12 @@ export default {
/**
* Check Uint8Array equality
* @function module:util.equalsUint8Array
* @param {Uint8Array} first array
* @param {Uint8Array} second array
* @return {Boolean} equality
*/
equalsUint8Array: function (array1, array2) {
if (!Uint8Array.prototype.isPrototypeOf(array1) || !Uint8Array.prototype.isPrototypeOf(array2)) {
if (!this.isUint8Array(array1) || !this.isUint8Array(array2)) {
throw new Error('Data must be in the form of a Uint8Array');
}
@ -421,12 +363,12 @@ export default {
* Helper function to print a debug message. Debug
* messages are only printed if
* @link module:config/config.debug is set to true.
* Different than print_debug because will call hexstrdump iff necessary.
* Different than print_debug because will call str_to_hex iff necessary.
* @param {String} str String of the debug message
*/
print_debug_hexstr_dump: function (str, strToHex) {
if (config.debug) {
str += this.hexstrdump(strToHex);
str += this.str_to_hex(strToHex);
console.log(str);
}
},
@ -442,6 +384,37 @@ export default {
return this.shiftRight(result, 8 - rest); // +String.fromCharCode(string.charCodeAt(bytes -1) << (8-rest) & 0xFF);
},
// returns bit length of the integer x
nbits: function (x) {
let r = 1;
let t = x >>> 16;
if (t !== 0) {
x = t;
r += 16;
}
t = x >> 8;
if (t !== 0) {
x = t;
r += 8;
}
t = x >> 4;
if (t !== 0) {
x = t;
r += 4;
}
t = x >> 2;
if (t !== 0) {
x = t;
r += 2;
}
t = x >> 1;
if (t !== 0) {
x = t;
r += 1;
}
return r;
},
/**
* Shifting a string to n bits right
* @param {String} value The string to shift
@ -450,7 +423,7 @@ export default {
* @return {String} Resulting string.
*/
shiftRight: function (value, bitcount) {
const temp = this.str2bin(value);
const temp = this.str_to_Uint8Array(value);
if (bitcount % 8 !== 0) {
for (let i = temp.length - 1; i >= 0; i--) {
temp[i] >>= bitcount % 8;
@ -461,31 +434,7 @@ export default {
} else {
return value;
}
return this.bin2str(temp);
},
/**
* Return the algorithm type as string
* @return {String} String representing the message type
*/
get_hashAlgorithmString: function (algo) {
switch (algo) {
case 1:
return "MD5";
case 2:
return "SHA1";
case 3:
return "RIPEMD160";
case 8:
return "SHA256";
case 9:
return "SHA384";
case 10:
return "SHA512";
case 11:
return "SHA224";
}
return "unknown";
return this.Uint8Array_to_str(temp);
},
/**

View File

@ -44,13 +44,13 @@ describe('AES Key Wrap and Unwrap', function () {
test_vectors.forEach(function(test) {
it(test[0], function(done) {
const kek = openpgp.util.hex2Uint8Array(test[1]);
const kek = openpgp.util.hex_to_Uint8Array(test[1]);
const input = test[2].replace(/\s/g, "");
const input_bin = openpgp.util.hex2bin(input);
const input_bin = openpgp.util.hex_to_str(input);
const output = test[3].replace(/\s/g, "");
const output_bin = openpgp.util.hex2bin(output);
expect(openpgp.util.hexidump(openpgp.crypto.aes_kw.wrap(kek, input_bin)).toUpperCase()).to.equal(output);
expect(openpgp.util.hexidump(openpgp.crypto.aes_kw.unwrap(kek, output_bin)).toUpperCase()).to.equal(input);
const output_bin = openpgp.util.hex_to_str(output);
expect(openpgp.util.Uint8Array_to_hex(openpgp.crypto.aes_kw.wrap(kek, input_bin)).toUpperCase()).to.equal(output);
expect(openpgp.util.Uint8Array_to_hex(openpgp.crypto.aes_kw.unwrap(kek, output_bin)).toUpperCase()).to.equal(input);
done();
});
});

View File

@ -9,9 +9,9 @@ describe('AES Rijndael cipher test with test vectors from ecb_tbl.txt', function
function test_aes(input, key, output) {
const aes = new openpgp.crypto.cipher.aes128(key);
const result = util.bin2str(aes.encrypt(new Uint8Array(input)));
const result = util.Uint8Array_to_str(aes.encrypt(new Uint8Array(input)));
return util.hexstrdump(result) === util.hexstrdump(util.bin2str(output));
return util.str_to_hex(result) === util.str_to_hex(util.Uint8Array_to_str(output));
}
const testvectors128 = [[[0x00,0x01,0x02,0x03,0x05,0x06,0x07,0x08,0x0A,0x0B,0x0C,0x0D,0x0F,0x10,0x11,0x12],[0x50,0x68,0x12,0xA4,0x5F,0x08,0xC8,0x89,0xB9,0x7F,0x59,0x80,0x03,0x8B,0x83,0x59],[0xD8,0xF5,0x32,0x53,0x82,0x89,0xEF,0x7D,0x06,0xB5,0x06,0xA4,0xFD,0x5B,0xE9,0xC9]],
@ -65,9 +65,9 @@ describe('AES Rijndael cipher test with test vectors from ecb_tbl.txt', function
it('128 bit key', function (done) {
for (let i = 0; i < testvectors128.length; i++) {
const res = test_aes(testvectors128[i][1],testvectors128[i][0],testvectors128[i][2]);
expect(res, 'block ' + util.hexidump(testvectors128[i][1]) +
' and key '+util.hexidump(testvectors128[i][0]) +
' should be '+util.hexidump(testvectors128[i][2])).to.be.true;
expect(res, 'block ' + util.Uint8Array_to_hex(testvectors128[i][1]) +
' and key '+util.Uint8Array_to_hex(testvectors128[i][0]) +
' should be '+util.Uint8Array_to_hex(testvectors128[i][2])).to.be.true;
}
done();
});
@ -75,9 +75,9 @@ describe('AES Rijndael cipher test with test vectors from ecb_tbl.txt', function
it('192 bit key', function (done) {
for (let i = 0; i < testvectors192.length; i++) {
const res = test_aes(testvectors192[i][1],testvectors192[i][0],testvectors192[i][2]);
expect(res, 'block ' + util.hexidump(testvectors192[i][1]) +
' and key ' + util.hexidump(testvectors192[i][0])+
' should be ' + util.hexidump(testvectors192[i][2])).to.be.true;
expect(res, 'block ' + util.Uint8Array_to_hex(testvectors192[i][1]) +
' and key ' + util.Uint8Array_to_hex(testvectors192[i][0])+
' should be ' + util.Uint8Array_to_hex(testvectors192[i][2])).to.be.true;
}
done();
});
@ -85,9 +85,9 @@ describe('AES Rijndael cipher test with test vectors from ecb_tbl.txt', function
it('256 bit key', function (done) {
for (let i = 0; i < testvectors256.length; i++) {
const res = test_aes(testvectors256[i][1],testvectors256[i][0],testvectors256[i][2]);
expect(res, 'block ' + util.hexidump(testvectors256[i][1]) +
' and key ' + util.hexidump(testvectors256[i][0]) +
' should be ' + util.hexidump(testvectors256[i][2])).to.be.true;
expect(res, 'block ' + util.Uint8Array_to_hex(testvectors256[i][1]) +
' and key ' + util.Uint8Array_to_hex(testvectors256[i][0]) +
' should be ' + util.Uint8Array_to_hex(testvectors256[i][2])).to.be.true;
}
done();
});

View File

@ -8,10 +8,10 @@ const { expect } = chai;
it('Blowfish cipher test with test vectors from https://www.schneier.com/code/vectors.txt', function(done) {
function test_bf(input, key, output) {
const blowfish = new openpgp.crypto.cipher.blowfish(util.bin2str(key));
const result = util.bin2str(blowfish.encrypt(input));
const blowfish = new openpgp.crypto.cipher.blowfish(util.Uint8Array_to_str(key));
const result = util.Uint8Array_to_str(blowfish.encrypt(input));
return (util.hexstrdump(result) === util.hexstrdump(util.bin2str(output)));
return (util.str_to_hex(result) === util.str_to_hex(util.Uint8Array_to_str(output)));
}
const testvectors = [[[0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00],[0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00],[0x4E,0xF9,0x97,0x45,0x61,0x98,0xDD,0x78]],
@ -51,9 +51,9 @@ it('Blowfish cipher test with test vectors from https://www.schneier.com/code/ve
for (let i = 0; i < testvectors.length; i++) {
const res = test_bf(testvectors[i][1],testvectors[i][0],testvectors[i][2]);
expect(res, 'vector '+ i + '" with block ' + util.hexidump(testvectors[i][0])+
' and key ' + util.hexidump(testvectors[i][1]) +
' should be ' + util.hexidump(testvectors[i][2]), false);
expect(res, 'vector '+ i + '" with block ' + util.Uint8Array_to_hex(testvectors[i][0])+
' and key ' + util.Uint8Array_to_hex(testvectors[i][1]) +
' should be ' + util.Uint8Array_to_hex(testvectors[i][2]), false);
}
done();
});

View File

@ -8,18 +8,18 @@ const { expect } = chai;
it('CAST-128 cipher test with test vectors from RFC2144', function (done) {
function test_cast(input, key, output) {
const cast5 = new openpgp.crypto.cipher.cast5(key);
const result = util.bin2str(cast5.encrypt(input));
const result = util.Uint8Array_to_str(cast5.encrypt(input));
return util.hexstrdump(result) === util.hexstrdump(util.bin2str(output));
return util.str_to_hex(result) === util.str_to_hex(util.Uint8Array_to_str(output));
}
const testvectors = [[[0x01,0x23,0x45,0x67,0x12,0x34,0x56,0x78,0x23,0x45,0x67,0x89,0x34,0x56,0x78,0x9A],[0x01,0x23,0x45,0x67,0x89,0xAB,0xCD,0xEF],[0x23,0x8B,0x4F,0xE5,0x84,0x7E,0x44,0xB2]]];
for (let i = 0; i < testvectors.length; i++) {
const res = test_cast(testvectors[i][1],testvectors[i][0],testvectors[i][2]);
expect(res, 'vector with block ' + util.hexidump(testvectors[i][0]) +
' and key ' + util.hexidump(testvectors[i][1]) +
' should be ' + util.hexidump(testvectors[i][2])).to.be.true;
expect(res, 'vector with block ' + util.Uint8Array_to_hex(testvectors[i][0]) +
' and key ' + util.Uint8Array_to_hex(testvectors[i][1]) +
' should be ' + util.Uint8Array_to_hex(testvectors[i][2])).to.be.true;
}
done();
});

View File

@ -77,12 +77,12 @@ describe('TripleDES (EDE) cipher test with test vectors from NIST SP 800-20', fu
for (let i = 0; i < testvectors.length; i++) {
const des = new openpgp.crypto.cipher.tripledes(key);
const encr = util.bin2str(des.encrypt(testvectors[i][0], key));
const encr = util.Uint8Array_to_str(des.encrypt(testvectors[i][0], key));
expect(encr, 'vector with block ' + util.hexidump(testvectors[i][0]) +
' and key ' + util.hexstrdump(util.Uint8Array2str(key)) +
' should be ' + util.hexidump(testvectors[i][1]) +
' != ' + util.hexidump(encr)).to.be.equal(util.bin2str(testvectors[i][1]));
expect(encr, 'vector with block ' + util.Uint8Array_to_hex(testvectors[i][0]) +
' and key ' + util.str_to_hex(util.Uint8Array_to_str(key)) +
' should be ' + util.Uint8Array_to_hex(testvectors[i][1]) +
' != ' + util.Uint8Array_to_hex(encr)).to.be.equal(util.Uint8Array_to_str(testvectors[i][1]));
}
done();
});
@ -124,18 +124,18 @@ describe('TripleDES (EDE) cipher test with test vectors from NIST SP 800-20', fu
const encrypted = des.encrypt(thisVectorSet[i][0], padding);
const decrypted = des.decrypt(encrypted, padding);
expect(util.bin2str(encrypted), 'vector with block [' + util.hexidump(thisVectorSet[i][0]) +
'] and key [' + util.hexstrdump(util.Uint8Array2str(key)) +
expect(util.Uint8Array_to_str(encrypted), 'vector with block [' + util.Uint8Array_to_hex(thisVectorSet[i][0]) +
'] and key [' + util.str_to_hex(util.Uint8Array_to_str(key)) +
'] and padding [' + padding +
'] should be ' + util.hexidump(thisVectorSet[i][1]) +
' - Actually [' + util.hexidump(encrypted) +
']').to.equal(util.bin2str(thisVectorSet[i][1]));
expect(util.bin2str(decrypted), 'vector with block [' + util.hexidump(thisVectorSet[i][0]) +
'] and key [' + util.hexstrdump(util.Uint8Array2str(key)) +
'] should be ' + util.Uint8Array_to_hex(thisVectorSet[i][1]) +
' - Actually [' + util.Uint8Array_to_hex(encrypted) +
']').to.equal(util.Uint8Array_to_str(thisVectorSet[i][1]));
expect(util.Uint8Array_to_str(decrypted), 'vector with block [' + util.Uint8Array_to_hex(thisVectorSet[i][0]) +
'] and key [' + util.str_to_hex(util.Uint8Array_to_str(key)) +
'] and padding [' + padding +
'] should be ' + util.hexidump(thisVectorSet[i][0]) +
' - Actually [' + util.hexidump(decrypted) +
']').to.equal(util.bin2str(thisVectorSet[i][0]));
'] should be ' + util.Uint8Array_to_hex(thisVectorSet[i][0]) +
' - Actually [' + util.Uint8Array_to_hex(decrypted) +
']').to.equal(util.Uint8Array_to_str(thisVectorSet[i][0]));
}
}
done();

View File

@ -7,7 +7,7 @@ const { expect } = chai;
it('Twofish with test vectors from https://www.schneier.com/code/ecb_ival.txt', function(done) {
function TFencrypt(block, key) {
const tf = new openpgp.crypto.cipher.twofish(util.str2Uint8Array(key));
const tf = new openpgp.crypto.cipher.twofish(util.str_to_Uint8Array(key));
return tf.encrypt(block);
}
@ -36,36 +36,36 @@ it('Twofish with test vectors from https://www.schneier.com/code/ecb_ival.txt',
if (i === 0) {
blk = start_short;
key = util.bin2str(start);
key = util.Uint8Array_to_str(start);
ct = testvectors[0];
res = util.bin2str(TFencrypt(blk,key));
exp = util.bin2str(ct);
res = util.Uint8Array_to_str(TFencrypt(blk,key));
exp = util.Uint8Array_to_str(ct);
} else if (i === 1) {
blk = testvectors[0];
key = util.bin2str(start);
key = util.Uint8Array_to_str(start);
ct = testvectors[1];
res = util.bin2str(TFencrypt(blk,key));
exp = util.bin2str(ct);
res = util.Uint8Array_to_str(TFencrypt(blk,key));
exp = util.Uint8Array_to_str(ct);
} else if (i === 2) {
blk = testvectors[i-1];
key = util.bin2str(testvectors[i-2].concat(start_short));
key = util.Uint8Array_to_str(testvectors[i-2].concat(start_short));
ct = testvectors[i];
res = util.bin2str(TFencrypt(blk,key));
exp = util.bin2str(ct);
res = util.Uint8Array_to_str(TFencrypt(blk,key));
exp = util.Uint8Array_to_str(ct);
} else if (i < 10 || i > 46) {
blk = testvectors[i-1];
key = util.bin2str(testvectors[i-2].concat(testvectors[i-3]));
key = util.Uint8Array_to_str(testvectors[i-2].concat(testvectors[i-3]));
ct = testvectors[i];
res = util.bin2str(TFencrypt(blk,key));
exp = util.bin2str(ct);
res = util.Uint8Array_to_str(TFencrypt(blk,key));
exp = util.Uint8Array_to_str(ct);
} else {
testvectors[i] = TFencrypt(testvectors[i-1],util.bin2str(testvectors[i-2].concat(testvectors[i-3])));
testvectors[i] = TFencrypt(testvectors[i-1],util.Uint8Array_to_str(testvectors[i-2].concat(testvectors[i-3])));
continue;
}
expect(res, 'vector with block ' + util.hexidump(blk) +
' with key ' + util.hexstrdump(key) +
' should be ' + util.hexidump(ct) +
' but is ' + util.hexidump(TFencrypt(blk,key))).to.equal(exp);
expect(res, 'vector with block ' + util.Uint8Array_to_hex(blk) +
' with key ' + util.str_to_hex(key) +
' should be ' + util.Uint8Array_to_hex(ct) +
' but is ' + util.Uint8Array_to_hex(TFencrypt(blk,key))).to.equal(exp);
}
done();
});

View File

@ -231,7 +231,7 @@ describe('API functional testing', function() {
ElgamalpubMPIs[i].read(ElgamalpubMPIstrs[i]);
}
const data = util.str2Uint8Array("foobar");
const data = util.str_to_Uint8Array("foobar");
describe('Sign and verify', function () {
it('RSA', function () {
@ -256,7 +256,7 @@ describe('API functional testing', function() {
return crypto.signature.sign(
17, 2, DSApubMPIs.concat(DSAsecMPIs), data
).then(DSAsignedData => {
DSAsignedData = util.Uint8Array2str(DSAsignedData);
DSAsignedData = util.Uint8Array_to_str(DSAsignedData);
const DSAmsgMPIs = [];
DSAmsgMPIs[0] = new openpgp.MPI();
DSAmsgMPIs[1] = new openpgp.MPI();
@ -280,8 +280,8 @@ describe('API functional testing', function() {
function testCFB(plaintext, resync) {
symmAlgos.forEach(function(algo) {
const symmKey = crypto.generateSessionKey(algo);
const symmencData = crypto.cfb.encrypt(crypto.getPrefixRandom(algo), algo, util.str2Uint8Array(plaintext), symmKey, resync);
const text = util.Uint8Array2str(crypto.cfb.decrypt(algo, symmKey, symmencData, resync));
const symmencData = crypto.cfb.encrypt(crypto.getPrefixRandom(algo), algo, util.str_to_Uint8Array(plaintext), symmKey, resync);
const text = util.Uint8Array_to_str(crypto.cfb.decrypt(algo, symmKey, symmencData, resync));
expect(text).to.equal(plaintext);
});
}
@ -295,10 +295,10 @@ describe('API functional testing', function() {
const repeat = new Uint8Array([rndm[rndm.length - 2], rndm[rndm.length - 1]]);
const prefix = util.concatUint8Array([rndm, repeat]);
const symmencData = crypto.cfb.encrypt(rndm, algo, util.str2Uint8Array(plaintext), symmKey, false);
const symmencData = crypto.cfb.encrypt(rndm, algo, util.str_to_Uint8Array(plaintext), symmKey, false);
const decrypted = crypto.cfb.decrypt(algo, symmKey, symmencData, false);
const text = util.Uint8Array2str(decrypted);
const text = util.Uint8Array_to_str(decrypted);
expect(text).to.equal(plaintext);
}
});
@ -312,11 +312,11 @@ describe('API functional testing', function() {
const iv = crypto.random.getRandomValues(new Uint8Array(crypto.gcm.ivLength));
return crypto.gcm.encrypt(
algo, util.str2Uint8Array(plaintext), key, iv
algo, util.str_to_Uint8Array(plaintext), key, iv
).then(function(ciphertext) {
return crypto.gcm.decrypt(algo, ciphertext, key, iv);
}).then(function(decrypted) {
const decryptedStr = util.Uint8Array2str(decrypted);
const decryptedStr = util.Uint8Array_to_str(decrypted);
expect(decryptedStr).to.equal(plaintext);
});
});
@ -372,7 +372,7 @@ describe('API functional testing', function() {
});
it('Asymmetric using RSA with eme_pkcs1 padding', function () {
const symmKey = util.Uint8Array2str(crypto.generateSessionKey('aes256'));
const symmKey = util.Uint8Array_to_str(crypto.generateSessionKey('aes256'));
const RSAUnencryptedData = crypto.pkcs1.eme.encode(symmKey, RSApubMPIs[0].byteLength())
const RSAUnencryptedMPI = new openpgp.MPI(RSAUnencryptedData);
return crypto.publicKeyEncrypt(
@ -383,7 +383,7 @@ describe('API functional testing', function() {
1, RSApubMPIs.concat(RSAsecMPIs), RSAEncryptedData
).then(data => {
data = data.write();
data = util.Uint8Array2str(data.subarray(2, data.length));
data = util.Uint8Array_to_str(data.subarray(2, data.length));
const result = crypto.pkcs1.eme.decode(data, RSApubMPIs[0].byteLength());
expect(result).to.equal(symmKey);
@ -392,7 +392,7 @@ describe('API functional testing', function() {
});
it('Asymmetric using Elgamal with eme_pkcs1 padding', function () {
const symmKey = util.Uint8Array2str(crypto.generateSessionKey('aes256'));
const symmKey = util.Uint8Array_to_str(crypto.generateSessionKey('aes256'));
const ElgamalUnencryptedData = crypto.pkcs1.eme.encode(symmKey, ElgamalpubMPIs[0].byteLength());
const ElgamalUnencryptedMPI = new openpgp.MPI(ElgamalUnencryptedData);
@ -404,7 +404,7 @@ describe('API functional testing', function() {
16, ElgamalpubMPIs.concat(ElgamalsecMPIs), ElgamalEncryptedData
).then(data => {
data = data.write();
data = util.Uint8Array2str(data.subarray(2, data.length));
data = util.Uint8Array_to_str(data.subarray(2, data.length));
const result = crypto.pkcs1.eme.decode(data, ElgamalpubMPIs[0].byteLength());
expect(result).to.equal(symmKey);

View File

@ -144,7 +144,7 @@ describe('Elliptic Curve Cryptography', function () {
it('Creating curve from oid', function (done) {
const oids = ['2A8648CE3D030107', '2B81040022', '2B81040023', '2B8104000A'];
oids.forEach(function (oid) {
expect(new elliptic_curves.Curve(openpgp.util.hex2bin(oid))).to.exist;
expect(new elliptic_curves.Curve(openpgp.util.hex_to_str(oid))).to.exist;
});
done();
});
@ -166,7 +166,7 @@ describe('Elliptic Curve Cryptography', function () {
expect(keyPair).to.exist;
const pub = keyPair.getPublic();
expect(pub).to.exist;
expect(openpgp.util.hexidump(pub)).to.equal(openpgp.util.hexidump(pair.pub));
expect(openpgp.util.Uint8Array_to_hex(pub)).to.equal(openpgp.util.Uint8Array_to_hex(pair.pub));
}
done();
});
@ -194,10 +194,10 @@ describe('Elliptic Curve Cryptography', function () {
const curve = new elliptic_curves.Curve('p256');
let key1 = curve.keyFromPrivate(key_data.p256.priv);
let key2 = curve.keyFromPublic(signature_data.pub);
const shared1 = openpgp.util.hexidump(key1.derive(key2));
const shared1 = openpgp.util.Uint8Array_to_hex(key1.derive(key2));
key1 = curve.keyFromPublic(key_data.p256.pub);
key2 = curve.keyFromPrivate(signature_data.priv);
const shared2 = openpgp.util.hexidump(key2.derive(key1));
const shared2 = openpgp.util.Uint8Array_to_hex(key2.derive(key1));
expect(shared1).to.equal(shared2);
done();
});
@ -205,7 +205,7 @@ describe('Elliptic Curve Cryptography', function () {
describe('ECDSA signature', function () {
const verify_signature = function (oid, hash, r, s, message, pub) {
if (openpgp.util.isString(message)) {
message = openpgp.util.str2Uint8Array(message);
message = openpgp.util.str_to_Uint8Array(message);
} else if (!openpgp.util.isUint8Array(message)) {
message = new Uint8Array(message);
}
@ -305,7 +305,7 @@ describe('Elliptic Curve Cryptography', function () {
describe('ECDH key exchange', function () {
const decrypt_message = function (oid, hash, cipher, priv, ephemeral, data, fingerprint) {
if (openpgp.util.isString(data)) {
data = openpgp.util.str2Uint8Array(data);
data = openpgp.util.str_to_Uint8Array(data);
} else {
data = new Uint8Array(data);
}

View File

@ -7,11 +7,11 @@ const MD5 = openpgp.crypto.hash.md5;
const { expect } = chai;
it('MD5 with test vectors from RFC 1321', function(done) {
expect(util.hexstrdump(util.Uint8Array2str(MD5(util.str2Uint8Array(''))), 'MD5("") = d41d8cd98f00b204e9800998ecf8427e')).to.equal('d41d8cd98f00b204e9800998ecf8427e');
expect(util.hexstrdump(util.Uint8Array2str(MD5(util.str2Uint8Array('abc'))), 'MD5("a") = 0cc175b9c0f1b6a831c399e269772661')).to.equal('900150983cd24fb0d6963f7d28e17f72');
expect(util.hexstrdump(util.Uint8Array2str(MD5(util.str2Uint8Array('message digest'))), 'MD5("message digest") = f96b697d7cb7938d525a2f31aaf161d0')).to.equal('f96b697d7cb7938d525a2f31aaf161d0');
expect(util.hexstrdump(util.Uint8Array2str(MD5(util.str2Uint8Array('abcdefghijklmnopqrstuvwxyz'))), 'MD5("abcdefghijklmnopqrstuvwxyz") = c3fcd3d76192e4007dfb496cca67e13b')).to.equal('c3fcd3d76192e4007dfb496cca67e13b');
expect(util.hexstrdump(util.Uint8Array2str(MD5(util.str2Uint8Array('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'))), 'MD5("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789") = d174ab98d277d9f5a5611c2c9f419d9f')).to.equal('d174ab98d277d9f5a5611c2c9f419d9f');
expect(util.hexstrdump(util.Uint8Array2str(MD5(util.str2Uint8Array('12345678901234567890123456789012345678901234567890123456789012345678901234567890'))), 'MD5("12345678901234567890123456789012345678901234567890123456789012345678901234567890") = 57edf4a22be3c955ac49da2e2107b67a')).to.equal('57edf4a22be3c955ac49da2e2107b67a');
expect(util.str_to_hex(util.Uint8Array_to_str(MD5(util.str_to_Uint8Array(''))), 'MD5("") = d41d8cd98f00b204e9800998ecf8427e')).to.equal('d41d8cd98f00b204e9800998ecf8427e');
expect(util.str_to_hex(util.Uint8Array_to_str(MD5(util.str_to_Uint8Array('abc'))), 'MD5("a") = 0cc175b9c0f1b6a831c399e269772661')).to.equal('900150983cd24fb0d6963f7d28e17f72');
expect(util.str_to_hex(util.Uint8Array_to_str(MD5(util.str_to_Uint8Array('message digest'))), 'MD5("message digest") = f96b697d7cb7938d525a2f31aaf161d0')).to.equal('f96b697d7cb7938d525a2f31aaf161d0');
expect(util.str_to_hex(util.Uint8Array_to_str(MD5(util.str_to_Uint8Array('abcdefghijklmnopqrstuvwxyz'))), 'MD5("abcdefghijklmnopqrstuvwxyz") = c3fcd3d76192e4007dfb496cca67e13b')).to.equal('c3fcd3d76192e4007dfb496cca67e13b');
expect(util.str_to_hex(util.Uint8Array_to_str(MD5(util.str_to_Uint8Array('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'))), 'MD5("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789") = d174ab98d277d9f5a5611c2c9f419d9f')).to.equal('d174ab98d277d9f5a5611c2c9f419d9f');
expect(util.str_to_hex(util.Uint8Array_to_str(MD5(util.str_to_Uint8Array('12345678901234567890123456789012345678901234567890123456789012345678901234567890'))), 'MD5("12345678901234567890123456789012345678901234567890123456789012345678901234567890") = 57edf4a22be3c955ac49da2e2107b67a')).to.equal('57edf4a22be3c955ac49da2e2107b67a');
done();
});

View File

@ -7,9 +7,9 @@ const RMDstring = openpgp.crypto.hash.ripemd;
const { expect } = chai;
it("RIPE-MD 160 bits with test vectors from https://homes.esat.kuleuven.be/~bosselae/ripemd160.html", function(done) {
expect(util.hexstrdump(util.Uint8Array2str(RMDstring(util.str2Uint8Array(''))), 'RMDstring("") = 9c1185a5c5e9fc54612808977ee8f548b2258d31')).to.equal('9c1185a5c5e9fc54612808977ee8f548b2258d31');
expect(util.hexstrdump(util.Uint8Array2str(RMDstring(util.str2Uint8Array('a'))), 'RMDstring("a") = 0bdc9d2d256b3ee9daae347be6f4dc835a467ffe')).to.equal('0bdc9d2d256b3ee9daae347be6f4dc835a467ffe');
expect(util.hexstrdump(util.Uint8Array2str(RMDstring(util.str2Uint8Array('abc'))), 'RMDstring("abc") = 8eb208f7e05d987a9b044a8e98c6b087f15a0bfc')).to.equal('8eb208f7e05d987a9b044a8e98c6b087f15a0bfc');
expect(util.hexstrdump(util.Uint8Array2str(RMDstring(util.str2Uint8Array('message digest'))), 'RMDstring("message digest") = 5d0689ef49d2fae572b881b123a85ffa21595f36')).to.equal('5d0689ef49d2fae572b881b123a85ffa21595f36');
expect(util.str_to_hex(util.Uint8Array_to_str(RMDstring(util.str_to_Uint8Array(''))), 'RMDstring("") = 9c1185a5c5e9fc54612808977ee8f548b2258d31')).to.equal('9c1185a5c5e9fc54612808977ee8f548b2258d31');
expect(util.str_to_hex(util.Uint8Array_to_str(RMDstring(util.str_to_Uint8Array('a'))), 'RMDstring("a") = 0bdc9d2d256b3ee9daae347be6f4dc835a467ffe')).to.equal('0bdc9d2d256b3ee9daae347be6f4dc835a467ffe');
expect(util.str_to_hex(util.Uint8Array_to_str(RMDstring(util.str_to_Uint8Array('abc'))), 'RMDstring("abc") = 8eb208f7e05d987a9b044a8e98c6b087f15a0bfc')).to.equal('8eb208f7e05d987a9b044a8e98c6b087f15a0bfc');
expect(util.str_to_hex(util.Uint8Array_to_str(RMDstring(util.str_to_Uint8Array('message digest'))), 'RMDstring("message digest") = 5d0689ef49d2fae572b881b123a85ffa21595f36')).to.equal('5d0689ef49d2fae572b881b123a85ffa21595f36');
done();
});

View File

@ -7,15 +7,15 @@ const { hash } = openpgp.crypto;
const { expect } = chai;
it('SHA* with test vectors from NIST FIPS 180-2', function(done) {
expect(util.hexstrdump(util.Uint8Array2str(hash.sha1(util.str2Uint8Array('abc'))), 'hash.sha1("abc") = a9993e364706816aba3e25717850c26c9cd0d89d')).to.equal('a9993e364706816aba3e25717850c26c9cd0d89d');
expect(util.hexstrdump(util.Uint8Array2str(hash.sha1(util.str2Uint8Array('abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq'))), 'hash.sha1("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq") = 84983e441c3bd26ebaae4aa1f95129e5e54670f1')).to.equal('84983e441c3bd26ebaae4aa1f95129e5e54670f1');
expect(util.hexstrdump(util.Uint8Array2str(hash.sha224(util.str2Uint8Array('abc'))), 'hash.sha224("abc") = 23097d223405d8228642a477bda255b32aadbce4bda0b3f7e36c9da7')).to.equal('23097d223405d8228642a477bda255b32aadbce4bda0b3f7e36c9da7');
expect(util.hexstrdump(util.Uint8Array2str(hash.sha224(util.str2Uint8Array('abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq'))), 'hash.sha224("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq") = 75388b16512776cc5dba5da1fd890150b0c6455cb4f58b1952522525')).to.equal('75388b16512776cc5dba5da1fd890150b0c6455cb4f58b1952522525');
expect(util.hexstrdump(util.Uint8Array2str(hash.sha256(util.str2Uint8Array('abc'))), 'hash.sha256("abc") = ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad')).to.equal('ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad');
expect(util.hexstrdump(util.Uint8Array2str(hash.sha256(util.str2Uint8Array('abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq'))), 'hash.sha256("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq") = 248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1')).to.equal('248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1');
expect(util.hexstrdump(util.Uint8Array2str(hash.sha384(util.str2Uint8Array('abc'))), 'hash.sha384("abc") = cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed8086072ba1e7cc2358baeca134c825a7')).to.equal('cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed8086072ba1e7cc2358baeca134c825a7');
expect(util.hexstrdump(util.Uint8Array2str(hash.sha384(util.str2Uint8Array('abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq'))), 'hash.sha384("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq") = 3391fdddfc8dc7393707a65b1b4709397cf8b1d162af05abfe8f450de5f36bc6b0455a8520bc4e6f5fe95b1fe3c8452b')).to.equal('3391fdddfc8dc7393707a65b1b4709397cf8b1d162af05abfe8f450de5f36bc6b0455a8520bc4e6f5fe95b1fe3c8452b');
expect(util.hexstrdump(util.Uint8Array2str(hash.sha512(util.str2Uint8Array('abc'))), 'hash.sha512("abc") = ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f')).to.equal('ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f');
expect(util.hexstrdump(util.Uint8Array2str(hash.sha512(util.str2Uint8Array('abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq'))), 'hash.sha512("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq") = 204a8fc6dda82f0a0ced7beb8e08a41657c16ef468b228a8279be331a703c33596fd15c13b1b07f9aa1d3bea57789ca031ad85c7a71dd70354ec631238ca3445')).to.equal('204a8fc6dda82f0a0ced7beb8e08a41657c16ef468b228a8279be331a703c33596fd15c13b1b07f9aa1d3bea57789ca031ad85c7a71dd70354ec631238ca3445');
expect(util.str_to_hex(util.Uint8Array_to_str(hash.sha1(util.str_to_Uint8Array('abc'))), 'hash.sha1("abc") = a9993e364706816aba3e25717850c26c9cd0d89d')).to.equal('a9993e364706816aba3e25717850c26c9cd0d89d');
expect(util.str_to_hex(util.Uint8Array_to_str(hash.sha1(util.str_to_Uint8Array('abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq'))), 'hash.sha1("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq") = 84983e441c3bd26ebaae4aa1f95129e5e54670f1')).to.equal('84983e441c3bd26ebaae4aa1f95129e5e54670f1');
expect(util.str_to_hex(util.Uint8Array_to_str(hash.sha224(util.str_to_Uint8Array('abc'))), 'hash.sha224("abc") = 23097d223405d8228642a477bda255b32aadbce4bda0b3f7e36c9da7')).to.equal('23097d223405d8228642a477bda255b32aadbce4bda0b3f7e36c9da7');
expect(util.str_to_hex(util.Uint8Array_to_str(hash.sha224(util.str_to_Uint8Array('abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq'))), 'hash.sha224("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq") = 75388b16512776cc5dba5da1fd890150b0c6455cb4f58b1952522525')).to.equal('75388b16512776cc5dba5da1fd890150b0c6455cb4f58b1952522525');
expect(util.str_to_hex(util.Uint8Array_to_str(hash.sha256(util.str_to_Uint8Array('abc'))), 'hash.sha256("abc") = ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad')).to.equal('ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad');
expect(util.str_to_hex(util.Uint8Array_to_str(hash.sha256(util.str_to_Uint8Array('abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq'))), 'hash.sha256("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq") = 248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1')).to.equal('248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1');
expect(util.str_to_hex(util.Uint8Array_to_str(hash.sha384(util.str_to_Uint8Array('abc'))), 'hash.sha384("abc") = cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed8086072ba1e7cc2358baeca134c825a7')).to.equal('cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed8086072ba1e7cc2358baeca134c825a7');
expect(util.str_to_hex(util.Uint8Array_to_str(hash.sha384(util.str_to_Uint8Array('abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq'))), 'hash.sha384("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq") = 3391fdddfc8dc7393707a65b1b4709397cf8b1d162af05abfe8f450de5f36bc6b0455a8520bc4e6f5fe95b1fe3c8452b')).to.equal('3391fdddfc8dc7393707a65b1b4709397cf8b1d162af05abfe8f450de5f36bc6b0455a8520bc4e6f5fe95b1fe3c8452b');
expect(util.str_to_hex(util.Uint8Array_to_str(hash.sha512(util.str_to_Uint8Array('abc'))), 'hash.sha512("abc") = ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f')).to.equal('ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f');
expect(util.str_to_hex(util.Uint8Array_to_str(hash.sha512(util.str_to_Uint8Array('abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq'))), 'hash.sha512("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq") = 204a8fc6dda82f0a0ced7beb8e08a41657c16ef468b228a8279be331a703c33596fd15c13b1b07f9aa1d3bea57789ca031ad85c7a71dd70354ec631238ca3445')).to.equal('204a8fc6dda82f0a0ced7beb8e08a41657c16ef468b228a8279be331a703c33596fd15c13b1b07f9aa1d3bea57789ca031ad85c7a71dd70354ec631238ca3445');
done();
});

View File

@ -14,7 +14,7 @@ describe('Oid tests', function() {
expect(oid).to.exist;
expect(oid.oid).to.exist;
expect(oid.oid).to.have.length(data.length);
expect(oid.oid).to.equal(openpgp.util.Uint8Array2str(data));
expect(oid.oid).to.equal(openpgp.util.Uint8Array_to_str(data));
});
});
it('Reading and writing', function() {
@ -25,12 +25,12 @@ describe('Oid tests', function() {
expect(oid.read(data)).to.equal(data.length);
expect(oid.oid).to.exist;
expect(oid.oid).to.have.length(data.length-1);
expect(oid.oid).to.equal(openpgp.util.Uint8Array2str(data.subarray(1)));
expect(oid.oid).to.equal(openpgp.util.Uint8Array_to_str(data.subarray(1)));
const result = oid.write();
expect(result).to.exist;
expect(result).to.have.length(data.length);
expect(result[0]).to.equal(data.length-1);
expect(openpgp.util.Uint8Array2str(result.subarray(1))).to.equal(openpgp.util.Uint8Array2str(data.subarray(1)));
expect(openpgp.util.Uint8Array_to_str(result.subarray(1))).to.equal(openpgp.util.Uint8Array_to_str(data.subarray(1)));
});
});
});

View File

@ -603,7 +603,7 @@ describe("Signature", function() {
});
it('Sign text with openpgp.sign and verify with openpgp.verify leads to same bytes cleartext and valid signatures - armored', function() {
const plaintext = openpgp.util.str2Uint8Array('short message\nnext line\n한국어/조선말');
const plaintext = openpgp.util.str_to_Uint8Array('short message\nnext line\n한국어/조선말');
const pubKey = openpgp.key.readArmored(pub_key_arm2).keys[0];
const privKey = openpgp.key.readArmored(priv_key_arm2).keys[0];
privKey.primaryKey.decrypt('hello world');
@ -623,7 +623,7 @@ describe("Signature", function() {
});
it('Sign text with openpgp.sign and verify with openpgp.verify leads to same bytes cleartext and valid signatures - not armored', function() {
const plaintext = openpgp.util.str2Uint8Array('short message\nnext line\n한국어/조선말');
const plaintext = openpgp.util.str_to_Uint8Array('short message\nnext line\n한국어/조선말');
const pubKey = openpgp.key.readArmored(pub_key_arm2).keys[0];
const privKey = openpgp.key.readArmored(priv_key_arm2).keys[0];
privKey.primaryKey.decrypt('hello world');

View File

@ -344,21 +344,21 @@ describe('X25519 Cryptography', function () {
const S = curve.keyFromSecret(vector.SECRET_KEY);
const P = curve.keyFromPublic('40'+vector.PUBLIC_KEY);
expect(S.getPublic()).to.deep.equal(P.getPublic());
const data = util.str2Uint8Array(vector.MESSAGE);
const data = util.str_to_Uint8Array(vector.MESSAGE);
const keyIntegers = [
openpgp.OID.fromClone(curve),
new openpgp.MPI(util.hex2bin('40'+vector.PUBLIC_KEY)),
new openpgp.MPI(util.hex2bin(vector.SECRET_KEY))
new openpgp.MPI(util.hex_to_str('40'+vector.PUBLIC_KEY)),
new openpgp.MPI(util.hex_to_str(vector.SECRET_KEY))
];
const msg_MPIs = [
new openpgp.MPI(util.Uint8Array2str(util.hex2Uint8Array(vector.SIGNATURE.R).reverse())),
new openpgp.MPI(util.Uint8Array2str(util.hex2Uint8Array(vector.SIGNATURE.S).reverse()))
new openpgp.MPI(util.Uint8Array_to_str(util.hex_to_Uint8Array(vector.SIGNATURE.R).reverse())),
new openpgp.MPI(util.Uint8Array_to_str(util.hex_to_Uint8Array(vector.SIGNATURE.S).reverse()))
];
return Promise.all([
signature.sign(22, undefined, keyIntegers, data).then(signed => {
const len = ((signed[0] << 8| signed[1]) + 7) / 8;
expect(util.hex2Uint8Array(vector.SIGNATURE.R)).to.deep.eq(signed.slice(2, 2 + len));
expect(util.hex2Uint8Array(vector.SIGNATURE.S)).to.deep.eq(signed.slice(4 + len));
expect(util.hex_to_Uint8Array(vector.SIGNATURE.R)).to.deep.eq(signed.slice(2, 2 + len));
expect(util.hex_to_Uint8Array(vector.SIGNATURE.S)).to.deep.eq(signed.slice(4 + len));
}),
signature.verify(22, undefined, msg_MPIs, keyIntegers, data).then(result => {
expect(result).to.be.true;
@ -391,7 +391,7 @@ describe('X25519 Cryptography', function () {
PUBLIC_KEY:
['3d4017c3e843895a92b70aa74d1b7ebc',
'9c982ccf2ec4968cc0cd55f12af4660c'].join(''),
MESSAGE: util.hex2bin('72'),
MESSAGE: util.hex_to_str('72'),
SIGNATURE:
{ R: ['92a009a9f0d4cab8720e820b5f642540',
'a2b27b5416503f8fb3762223ebdb69da'].join(''),
@ -408,7 +408,7 @@ describe('X25519 Cryptography', function () {
PUBLIC_KEY:
['fc51cd8e6218a1a38da47ed00230f058',
'0816ed13ba3303ac5deb911548908025'].join(''),
MESSAGE: util.hex2bin('af82'),
MESSAGE: util.hex_to_str('af82'),
SIGNATURE:
{ R: ['6291d657deec24024827e69c3abe01a3',
'0ce548a284743a445e3680d7db5ac3ac'].join(''),
@ -425,7 +425,7 @@ describe('X25519 Cryptography', function () {
PUBLIC_KEY:
['278117fc144c72340f67d0f2316e8386',
'ceffbf2b2428c9c51fef7c597f1d426e'].join(''),
MESSAGE: util.hex2bin([
MESSAGE: util.hex_to_str([
'08b8b2b733424243760fe426a4b54908',
'632110a66c2f6591eabd3345e3e4eb98',
'fa6e264bf09efe12ee50f8f54e9f77b1',
@ -507,7 +507,7 @@ describe('X25519 Cryptography', function () {
PUBLIC_KEY:
['ec172b93ad5e563bf4932c70e1245034',
'c35467ef2efd4d64ebf819683467e2bf'].join(''),
MESSAGE: util.hex2bin([
MESSAGE: util.hex_to_str([
'ddaf35a193617abacc417349ae204131',
'12e6fa4e89a97ea20a9eeee64b55d39a',
'2192992a274fc1a836ba3c23a3feebbd',