From a1647b02cb2c59e4da3706c71ac4f3e685d2aa25 Mon Sep 17 00:00:00 2001 From: flakjacket Date: Fri, 20 Sep 2024 15:46:04 +0200 Subject: [PATCH 1/9] Initial SM2 changes --- src/core/config/Categories.json | 3 +- src/core/operations/SM2Encrypt.mjs | 210 +++++++++++++++++++++++++++++ 2 files changed, 212 insertions(+), 1 deletion(-) create mode 100644 src/core/operations/SM2Encrypt.mjs diff --git a/src/core/config/Categories.json b/src/core/config/Categories.json index bebdd6a5..31618ab3 100644 --- a/src/core/config/Categories.json +++ b/src/core/config/Categories.json @@ -189,7 +189,8 @@ "Parse SSH Host Key", "Parse CSR", "Public Key from Certificate", - "Public Key from Private Key" + "Public Key from Private Key", + "SM2 Encrypt" ] }, { diff --git a/src/core/operations/SM2Encrypt.mjs b/src/core/operations/SM2Encrypt.mjs new file mode 100644 index 00000000..29a6bbc6 --- /dev/null +++ b/src/core/operations/SM2Encrypt.mjs @@ -0,0 +1,210 @@ +/** + * @author flakjacket95 [dflack95@gmail.com] + * @copyright Crown Copyright 2024 + * @license Apache-2.0 + */ + +import Operation from "../Operation.mjs"; +import OperationError from "../errors/OperationError.mjs"; +import { fromHex } from "../lib/Hex.mjs"; +import { toBase64 } from "../lib/Base64.mjs"; +import Utils from "../Utils.mjs"; +import Sm3 from "crypto-api/src/hasher/sm3.mjs"; +import {toHex} from "crypto-api/src/encoder/hex.mjs"; +//import { ECCurveFp } from "jsrsasign"; +import r from "jsrsasign"; + +/** + * SM2 Encrypt operation + */ +class SM2Encrypt extends Operation { + + /** + * SM2Encrypt constructor + */ + constructor() { + super(); + + this.name = "SM2 Encrypt"; + this.module = "Ciphers"; + this.description = "Encrypts a message utilizing the SM2 standard"; + this.infoURL = ""; // Usually a Wikipedia link. Remember to remove localisation (i.e. https://wikipedia.org/etc rather than https://en.wikipedia.org/etc) + this.inputType = "ArrayBuffer"; + this.outputType = "string"; + + this.args = [ + { + name: "Public Key X", + type: "string", + value: "DEADBEEF" + }, + { + name: "Public Key Y", + type: "string", + value: "DEADBEEF" + }, + { + "name": "Output Format", + "type": "option", + "value": ["C1C3C2", "C1C2C3"] + }, + { + name: "Curve", + type: "option", + "value": ["sm2p256v1"] + } + ]; + this.ecParams = null; + this.rng = new r.SecureRandom(); + /* + For any additional curve definitions utilized by SM2, add another block like the below for that curve, then add the curve name to the Curve selection dropdown + */ + r.crypto.ECParameterDB.regist( + 'sm2p256v1', // name / p = 2**256 - 2**224 - 2**96 + 2**64 - 1 + 256, + 'FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFF', // p + 'FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFC', // a + '28E9FA9E9D9F5E344D5A9E4BCF6509A7F39789F515AB8F92DDBCBD414D940E93', // b + 'FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFF7203DF6B21C6052B53BBF40939D54123', // n + '1', // h + '32C4AE2C1F1981195F9904466A39C9948FE30BBFF2660BE1715A4589334C74C7', // gx + 'BC3736A2F4F6779C59BDCEE36B692153D0A9877CC62A474002DF32E52139F0A0', // gy + [] + ) // alias + } + + /** + * @param {ArrayBuffer} input + * @param {Object[]} args + * @returns {byteArray} + */ + run(input, args) { + const [privateKeyX, privateKeyY, outputFormat, curveName] = args; + + this.outputFormat = outputFormat; + + this.ecParams = r.crypto.ECParameterDB.getByName(curveName); + + this.publicKey = this.ecParams.curve.decodePointHex("04" + privateKeyX + privateKeyY); + + if (this.publicKey.isInfinity()) { + throw new OperationError("Invalid Public Key"); + } + + var result = this.encrypt(new Uint8Array(input)) + + return result + } + + /** + * Highlight SM2 Encrypt + * + * @param {Object[]} pos + * @param {number} pos[].start + * @param {number} pos[].end + * @param {Object[]} args + * @returns {Object[]} pos + */ + highlight(pos, args) { + const [privateKeyX, privateKeyY, outputFormat, curveName] = args; + var num = pos[0].end - pos[0].start + var adjust = 128 + if (outputFormat == "C1C3C2") { + adjust = 192 + } + pos[0].start = Math.ceil(pos[0].start + adjust); + pos[0].end = Math.floor(pos[0].end + adjust + num); + return pos; + } + + encrypt(input) { + const n = this.ecParams.n + const G = this.ecParams.G + + var k = this.generatePublicKey(); + var c1 = G.multiply(k); + + var bic1X = c1.getX().toBigInteger(); + var bic1Y = c1.getY().toBigInteger(); + + var charlen = this.ecParams.keycharlen; + var hexC1X = ("0000000000" + bic1X.toString(16)).slice(- charlen); + var hexC1Y = ("0000000000" + bic1Y.toString(16)).slice(- charlen); + + const p2 = this.publicKey.multiply(k); + + var c3 = this.c3(p2, input); + + var key = this.kdf(p2, input.byteLength); + + for (let i = 0; i < input.byteLength; i++) { + input[i] ^= Utils.ord(key[i]); + } + var c2 = Buffer.from(input).toString('hex'); + + if (this.outputFormat == "C1C3C2") { + return hexC1X + hexC1Y + c3 + c2; + } else { + return hexC1X + hexC1Y + c2 + c3; + } + } + + getBigRandom(limit) { + return new r.BigInteger(limit.bitLength(), this.rng) + .mod(limit.subtract(r.BigInteger.ONE)) + .add(r.BigInteger.ONE); + } + + generatePublicKey() { + const n = this.ecParams.n; + var k = this.getBigRandom(n); + return k; + } + + kdf(p2, len) { + var biX = p2.getX().toBigInteger(); + var biY = p2.getY().toBigInteger(); + + var charlen = this.ecParams.keycharlen; + var hX = ("0000000000" + biX.toString(16)).slice(- charlen); + var hY = ("0000000000" + biY.toString(16)).slice(- charlen); + + var total = Math.ceil(len / 32) + 1; + var cnt = 1; + + var keyMaterial = "" + + while (cnt < total) { + var num = Utils.intToByteArray(cnt, 4, "big"); + var overall = fromHex(hX).concat(fromHex(hY)).concat(num) + keyMaterial += this.sm3(overall); + cnt++; + } + + return keyMaterial + } + + c3(p2, input) { + var biX = p2.getX().toBigInteger(); + var biY = p2.getY().toBigInteger(); + + var charlen = this.ecParams.keycharlen; + var hX = ("0000000000" + biX.toString(16)).slice(- charlen); + var hY = ("0000000000" + biY.toString(16)).slice(- charlen); + + var overall = fromHex(hX).concat(Array.from(input)).concat(fromHex(hY)); + + return toHex(this.sm3(overall)); + + } + + sm3(data) { + var hashData = Utils.arrayBufferToStr(Uint8Array.from(data).buffer, false); + const hasher = new Sm3(); + hasher.update(hashData); + return hasher.finalize(); + } + +} + +export default SM2Encrypt; From 99ba6b487cbbed094b79ea3252d70f201b64cb91 Mon Sep 17 00:00:00 2001 From: Dan Flack Date: Fri, 20 Sep 2024 16:20:15 +0200 Subject: [PATCH 2/9] Add comments, docs, and some additional restructuring --- src/core/operations/SM2Encrypt.mjs | 103 +++++++++++++++++++++-------- 1 file changed, 76 insertions(+), 27 deletions(-) diff --git a/src/core/operations/SM2Encrypt.mjs b/src/core/operations/SM2Encrypt.mjs index 29a6bbc6..e34288bd 100644 --- a/src/core/operations/SM2Encrypt.mjs +++ b/src/core/operations/SM2Encrypt.mjs @@ -80,11 +80,12 @@ class SM2Encrypt extends Operation { */ run(input, args) { const [privateKeyX, privateKeyY, outputFormat, curveName] = args; - this.outputFormat = outputFormat; - this.ecParams = r.crypto.ECParameterDB.getByName(curveName); - + /* + * TODO: This needs some additional length validation; and checking for errors in the decoding process + * TODO: Can probably support other public key encoding methods here as well in the future + */ this.publicKey = this.ecParams.curve.decodePointHex("04" + privateKeyX + privateKeyY); if (this.publicKey.isInfinity()) { @@ -92,7 +93,6 @@ class SM2Encrypt extends Operation { } var result = this.encrypt(new Uint8Array(input)) - return result } @@ -117,31 +117,43 @@ class SM2Encrypt extends Operation { return pos; } + /** + * Main encryption function; takes user input, processes encryption and returns the result in hex (with the components arranged as configured by the user args) + * + * @param {*} input + * @returns {string} + */ encrypt(input) { - const n = this.ecParams.n const G = this.ecParams.G - + + /* + * Compute a new, random public key along the same elliptic curve to form the starting point for our encryption process (record the resulting X and Y as hex to provide as part of the operation output) + * k: Randomly generated BigInteger + * c1: Result of dotting our curve generator point `G` with the value of `k` + */ var k = this.generatePublicKey(); var c1 = G.multiply(k); - - var bic1X = c1.getX().toBigInteger(); - var bic1Y = c1.getY().toBigInteger(); - - var charlen = this.ecParams.keycharlen; - var hexC1X = ("0000000000" + bic1X.toString(16)).slice(- charlen); - var hexC1Y = ("0000000000" + bic1Y.toString(16)).slice(- charlen); + const [hexC1X, hexC1Y] = this.getPointAsHex(c1); const p2 = this.publicKey.multiply(k); + /* + * Compute the C3 SM3 hash before we transform the array + */ var c3 = this.c3(p2, input); + /* + * Genreate a proper length encryption key, XOR iteratively, and convert newly encrypted data to hex + */ var key = this.kdf(p2, input.byteLength); - for (let i = 0; i < input.byteLength; i++) { input[i] ^= Utils.ord(key[i]); } var c2 = Buffer.from(input).toString('hex'); + /* + * Check user input specs; order the output components as selected + */ if (this.outputFormat == "C1C3C2") { return hexC1X + hexC1Y + c3 + c2; } else { @@ -149,25 +161,39 @@ class SM2Encrypt extends Operation { } } + /** + * Generates a large random number + * + * @param {*} limit + * @returns + */ getBigRandom(limit) { return new r.BigInteger(limit.bitLength(), this.rng) .mod(limit.subtract(r.BigInteger.ONE)) .add(r.BigInteger.ONE); } + /** + * Helper function for generating a large random K number; utilized for generating our initial C1 point + * TODO: Do we need to do any sort of validation on the resulting k values? + * + * @returns {BigInteger} + */ generatePublicKey() { const n = this.ecParams.n; var k = this.getBigRandom(n); return k; } + /** + * SM2 Key Derivation Function (KDF); Takes P2 point, and generates a key material stream large enough to encrypt all of the input data + * + * @param {*} p2 + * @param {*} len + * @returns {string} + */ kdf(p2, len) { - var biX = p2.getX().toBigInteger(); - var biY = p2.getY().toBigInteger(); - - var charlen = this.ecParams.keycharlen; - var hX = ("0000000000" + biX.toString(16)).slice(- charlen); - var hY = ("0000000000" + biY.toString(16)).slice(- charlen); + const [hX, hY] = this.getPointAsHex(p2); var total = Math.ceil(len / 32) + 1; var cnt = 1; @@ -180,17 +206,18 @@ class SM2Encrypt extends Operation { keyMaterial += this.sm3(overall); cnt++; } - return keyMaterial } + /** + * Calculates the C3 component of our final encrypted payload; which is the SM3 hash of the P2 point and the original, unencrypted input data + * + * @param {*} p2 + * @param {*} input + * @returns {string} + */ c3(p2, input) { - var biX = p2.getX().toBigInteger(); - var biY = p2.getY().toBigInteger(); - - var charlen = this.ecParams.keycharlen; - var hX = ("0000000000" + biX.toString(16)).slice(- charlen); - var hY = ("0000000000" + biY.toString(16)).slice(- charlen); + const [hX, hY] = this.getPointAsHex(p2); var overall = fromHex(hX).concat(Array.from(input)).concat(fromHex(hY)); @@ -198,6 +225,12 @@ class SM2Encrypt extends Operation { } + /** + * SM3 setup helper function; takes input data as an array, processes the hash and returns the result + * + * @param {*} data + * @returns {string} + */ sm3(data) { var hashData = Utils.arrayBufferToStr(Uint8Array.from(data).buffer, false); const hasher = new Sm3(); @@ -205,6 +238,22 @@ class SM2Encrypt extends Operation { return hasher.finalize(); } + /** + * Utility function, returns an elliptic curve points X and Y values as hex; + * + * @param {EcPointFp} point + * @returns {[]} + */ + getPointAsHex(point) { + var biX = point.getX().toBigInteger(); + var biY = point.getY().toBigInteger(); + + var charlen = this.ecParams.keycharlen; + var hX = ("0000000000" + biX.toString(16)).slice(- charlen); + var hY = ("0000000000" + biY.toString(16)).slice(- charlen); + return [hX, hY] + } + } export default SM2Encrypt; From 54cfb1714555c395138aa52a66351c3337512c05 Mon Sep 17 00:00:00 2001 From: Dan Flack Date: Fri, 20 Sep 2024 19:17:00 +0200 Subject: [PATCH 3/9] Initial migration to library; add decryption operation --- src/core/config/Categories.json | 3 +- src/core/lib/SM2.mjs | 232 +++++++++++++++++++++++++++++ src/core/operations/SM2Decrypt.mjs | 65 ++++++++ src/core/operations/SM2Encrypt.mjs | 175 +--------------------- 4 files changed, 306 insertions(+), 169 deletions(-) create mode 100644 src/core/lib/SM2.mjs create mode 100644 src/core/operations/SM2Decrypt.mjs diff --git a/src/core/config/Categories.json b/src/core/config/Categories.json index 31618ab3..e8b7d202 100644 --- a/src/core/config/Categories.json +++ b/src/core/config/Categories.json @@ -190,7 +190,8 @@ "Parse CSR", "Public Key from Certificate", "Public Key from Private Key", - "SM2 Encrypt" + "SM2 Encrypt", + "SM2 Decrypt" ] }, { diff --git a/src/core/lib/SM2.mjs b/src/core/lib/SM2.mjs new file mode 100644 index 00000000..69bcaca1 --- /dev/null +++ b/src/core/lib/SM2.mjs @@ -0,0 +1,232 @@ +/** + * Utilities and operations utilized for SM2 encryption and decryption + * @author flakjacket95 [dflack95@gmail.com] + * @copyright Crown Copyright 2024 + * @license Apache-2.0 + */ + +import { fromHex } from "../lib/Hex.mjs"; +import Utils from "../Utils.mjs"; +import Sm3 from "crypto-api/src/hasher/sm3.mjs"; +import {toHex} from "crypto-api/src/encoder/hex.mjs"; +import r from "jsrsasign"; + +export class SM2 { + constructor(curve, format) { + this.ecParams = null; + this.rng = new r.SecureRandom(); + /* + For any additional curve definitions utilized by SM2, add another block like the below for that curve, then add the curve name to the Curve selection dropdown + */ + r.crypto.ECParameterDB.regist( + 'sm2p256v1', // name / p = 2**256 - 2**224 - 2**96 + 2**64 - 1 + 256, + 'FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFF', // p + 'FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFC', // a + '28E9FA9E9D9F5E344D5A9E4BCF6509A7F39789F515AB8F92DDBCBD414D940E93', // b + 'FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFF7203DF6B21C6052B53BBF40939D54123', // n + '1', // h + '32C4AE2C1F1981195F9904466A39C9948FE30BBFF2660BE1715A4589334C74C7', // gx + 'BC3736A2F4F6779C59BDCEE36B692153D0A9877CC62A474002DF32E52139F0A0', // gy + [] + ) // alias + this.ecParams = r.crypto.ECParameterDB.getByName(curve); + + this.format = format; + } + + /** + * Set the public key coordinates for the SM2 class + * + * @param {string} publicKeyX + * @param {string} publicKeyY + */ + setPublicKey(publicKeyX, publicKeyY) { + console.log('Set public key') + /* + * TODO: This needs some additional length validation; and checking for errors in the decoding process + * TODO: Can probably support other public key encoding methods here as well in the future + */ + this.publicKey = this.ecParams.curve.decodePointHex("04" + publicKeyX + publicKeyY); + + if (this.publicKey.isInfinity()) { + throw new OperationError("Invalid Public Key"); + } + } + + /** + * Set the private key value for the SM2 class + * + * @param {string} privateKey + */ + setPrivateKey(privateKey) { + this.privateKey = null; //Somehow take hex input and translate back to a BigInteger??? + } + + /** + * Main encryption function; takes user input, processes encryption and returns the result in hex (with the components arranged as configured by the user args) + * + * @param {*} input + * @returns {string} + */ + encrypt(input) { + const G = this.ecParams.G + + /* + * Compute a new, random public key along the same elliptic curve to form the starting point for our encryption process (record the resulting X and Y as hex to provide as part of the operation output) + * k: Randomly generated BigInteger + * c1: Result of dotting our curve generator point `G` with the value of `k` + */ + var k = this.generatePublicKey(); + var c1 = G.multiply(k); + const [hexC1X, hexC1Y] = this.getPointAsHex(c1); + + /* + * Compute p2 (secret) using the public key, and the chosen k value above + */ + const p2 = this.publicKey.multiply(k); + + /* + * Compute the C3 SM3 hash before we transform the array + */ + var c3 = this.c3(p2, input); + + /* + * Genreate a proper length encryption key, XOR iteratively, and convert newly encrypted data to hex + */ + var key = this.kdf(p2, input.byteLength); + for (let i = 0; i < input.byteLength; i++) { + input[i] ^= Utils.ord(key[i]); + } + var c2 = Buffer.from(input).toString('hex'); + + /* + * Check user input specs; order the output components as selected + */ + if (this.format == "C1C3C2") { + return hexC1X + hexC1Y + c3 + c2; + } else { + return hexC1X + hexC1Y + c2 + c3; + } + } + /** + * Function to decrypt an SM2 encrypted message + * + * @param {*} input + */ + decrypt(input) { + /* + * + */ + var c1 = this.ecParams.curve.decodePointHex("04" + publicKeyX + publicKeyY); + + /* + * Compute the p2 (secret) value by taking the C1 point provided in the encrypted package, and multiplying by the private k value + */ + var p2 = c1.multiply(this.privateKey); + + /* + * Similar to encryption; compute sufficient length key material and XOR the input data to recover the original message + */ + var key = this.kdf(p2, input.byteLength); + for (let i = 0; i < input.byteLength; i++) { + input[i] ^= Utils.ord(key[i]); + } + console.log(input) + //var dec = Buffer.from(input).toString('hex'); + } + + + /** + * Generates a large random number + * + * @param {*} limit + * @returns + */ + getBigRandom(limit) { + return new r.BigInteger(limit.bitLength(), this.rng) + .mod(limit.subtract(r.BigInteger.ONE)) + .add(r.BigInteger.ONE); + } + + /** + * Helper function for generating a large random K number; utilized for generating our initial C1 point + * TODO: Do we need to do any sort of validation on the resulting k values? + * + * @returns {BigInteger} + */ + generatePublicKey() { + const n = this.ecParams.n; + var k = this.getBigRandom(n); + return k; + } + + /** + * SM2 Key Derivation Function (KDF); Takes P2 point, and generates a key material stream large enough to encrypt all of the input data + * + * @param {*} p2 + * @param {*} len + * @returns {string} + */ + kdf(p2, len) { + const [hX, hY] = this.getPointAsHex(p2); + + var total = Math.ceil(len / 32) + 1; + var cnt = 1; + + var keyMaterial = "" + + while (cnt < total) { + var num = Utils.intToByteArray(cnt, 4, "big"); + var overall = fromHex(hX).concat(fromHex(hY)).concat(num) + keyMaterial += this.sm3(overall); + cnt++; + } + return keyMaterial + } + + /** + * Calculates the C3 component of our final encrypted payload; which is the SM3 hash of the P2 point and the original, unencrypted input data + * + * @param {*} p2 + * @param {*} input + * @returns {string} + */ + c3(p2, input) { + const [hX, hY] = this.getPointAsHex(p2); + + var overall = fromHex(hX).concat(Array.from(input)).concat(fromHex(hY)); + + return toHex(this.sm3(overall)); + + } + + /** + * SM3 setup helper function; takes input data as an array, processes the hash and returns the result + * + * @param {*} data + * @returns {string} + */ + sm3(data) { + var hashData = Utils.arrayBufferToStr(Uint8Array.from(data).buffer, false); + const hasher = new Sm3(); + hasher.update(hashData); + return hasher.finalize(); + } + + /** + * Utility function, returns an elliptic curve points X and Y values as hex; + * + * @param {EcPointFp} point + * @returns {[]} + */ + getPointAsHex(point) { + var biX = point.getX().toBigInteger(); + var biY = point.getY().toBigInteger(); + + var charlen = this.ecParams.keycharlen; + var hX = ("0000000000" + biX.toString(16)).slice(- charlen); + var hY = ("0000000000" + biY.toString(16)).slice(- charlen); + return [hX, hY] + } +} \ No newline at end of file diff --git a/src/core/operations/SM2Decrypt.mjs b/src/core/operations/SM2Decrypt.mjs new file mode 100644 index 00000000..cf77892d --- /dev/null +++ b/src/core/operations/SM2Decrypt.mjs @@ -0,0 +1,65 @@ +/** + * @author flakjacket95 [dflack95@gmail.com] + * @copyright Crown Copyright 2024 + * @license Apache-2.0 + */ + +import Operation from "../Operation.mjs"; +import OperationError from "../errors/OperationError.mjs"; + +import { SM2 } from "../lib/SM2.mjs"; + +/** + * SM2Decrypt operation + */ +class SM2Decrypt extends Operation { + + /** + * SM2Decrypt constructor + */ + constructor() { + super(); + + this.name = "SM2 Decrypt"; + this.module = "Crypto"; + this.description = "Decrypts a message utilizing the SM2 standard"; + this.infoURL = ""; // Usually a Wikipedia link. Remember to remove localisation (i.e. https://wikipedia.org/etc rather than https://en.wikipedia.org/etc) + this.inputType = "string"; + this.outputType = "ArrayBuffer"; + this.args = [ + { + name: "Private Key", + type: "string", + value: "DEADBEEF" + }, + { + "name": "Input Format", + "type": "option", + "value": ["C1C3C2", "C1C2C3"] + }, + { + name: "Curve", + type: "option", + "value": ["sm2p256v1"] + } + ]; + } + + /** + * @param {string} input + * @param {Object[]} args + * @returns {ArrayBuffer} + */ + run(input, args) { + const [privateKey, inputFormat, curveName] = args; + + var sm2 = new SM2(curveName, inputFormat); + sm2.setPrivateKey(privateKey); + + var result = sm2.decrypt(new Uint8Array(input)) + return result + } + +} + +export default SM2Decrypt; diff --git a/src/core/operations/SM2Encrypt.mjs b/src/core/operations/SM2Encrypt.mjs index e34288bd..61dbe281 100644 --- a/src/core/operations/SM2Encrypt.mjs +++ b/src/core/operations/SM2Encrypt.mjs @@ -6,12 +6,13 @@ import Operation from "../Operation.mjs"; import OperationError from "../errors/OperationError.mjs"; + +import { SM2 } from "../lib/SM2.mjs"; + import { fromHex } from "../lib/Hex.mjs"; -import { toBase64 } from "../lib/Base64.mjs"; import Utils from "../Utils.mjs"; import Sm3 from "crypto-api/src/hasher/sm3.mjs"; import {toHex} from "crypto-api/src/encoder/hex.mjs"; -//import { ECCurveFp } from "jsrsasign"; import r from "jsrsasign"; /** @@ -54,23 +55,6 @@ class SM2Encrypt extends Operation { "value": ["sm2p256v1"] } ]; - this.ecParams = null; - this.rng = new r.SecureRandom(); - /* - For any additional curve definitions utilized by SM2, add another block like the below for that curve, then add the curve name to the Curve selection dropdown - */ - r.crypto.ECParameterDB.regist( - 'sm2p256v1', // name / p = 2**256 - 2**224 - 2**96 + 2**64 - 1 - 256, - 'FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFF', // p - 'FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFC', // a - '28E9FA9E9D9F5E344D5A9E4BCF6509A7F39789F515AB8F92DDBCBD414D940E93', // b - 'FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFF7203DF6B21C6052B53BBF40939D54123', // n - '1', // h - '32C4AE2C1F1981195F9904466A39C9948FE30BBFF2660BE1715A4589334C74C7', // gx - 'BC3736A2F4F6779C59BDCEE36B692153D0A9877CC62A474002DF32E52139F0A0', // gy - [] - ) // alias } /** @@ -79,20 +63,13 @@ class SM2Encrypt extends Operation { * @returns {byteArray} */ run(input, args) { - const [privateKeyX, privateKeyY, outputFormat, curveName] = args; + const [publicKeyX, publicKeyY, outputFormat, curveName] = args; this.outputFormat = outputFormat; - this.ecParams = r.crypto.ECParameterDB.getByName(curveName); - /* - * TODO: This needs some additional length validation; and checking for errors in the decoding process - * TODO: Can probably support other public key encoding methods here as well in the future - */ - this.publicKey = this.ecParams.curve.decodePointHex("04" + privateKeyX + privateKeyY); - if (this.publicKey.isInfinity()) { - throw new OperationError("Invalid Public Key"); - } + var sm2 = new SM2(curveName, outputFormat); + sm2.setPublicKey(publicKeyX, publicKeyY); - var result = this.encrypt(new Uint8Array(input)) + var result = sm2.encrypt(new Uint8Array(input)) return result } @@ -116,144 +93,6 @@ class SM2Encrypt extends Operation { pos[0].end = Math.floor(pos[0].end + adjust + num); return pos; } - - /** - * Main encryption function; takes user input, processes encryption and returns the result in hex (with the components arranged as configured by the user args) - * - * @param {*} input - * @returns {string} - */ - encrypt(input) { - const G = this.ecParams.G - - /* - * Compute a new, random public key along the same elliptic curve to form the starting point for our encryption process (record the resulting X and Y as hex to provide as part of the operation output) - * k: Randomly generated BigInteger - * c1: Result of dotting our curve generator point `G` with the value of `k` - */ - var k = this.generatePublicKey(); - var c1 = G.multiply(k); - const [hexC1X, hexC1Y] = this.getPointAsHex(c1); - - const p2 = this.publicKey.multiply(k); - - /* - * Compute the C3 SM3 hash before we transform the array - */ - var c3 = this.c3(p2, input); - - /* - * Genreate a proper length encryption key, XOR iteratively, and convert newly encrypted data to hex - */ - var key = this.kdf(p2, input.byteLength); - for (let i = 0; i < input.byteLength; i++) { - input[i] ^= Utils.ord(key[i]); - } - var c2 = Buffer.from(input).toString('hex'); - - /* - * Check user input specs; order the output components as selected - */ - if (this.outputFormat == "C1C3C2") { - return hexC1X + hexC1Y + c3 + c2; - } else { - return hexC1X + hexC1Y + c2 + c3; - } - } - - /** - * Generates a large random number - * - * @param {*} limit - * @returns - */ - getBigRandom(limit) { - return new r.BigInteger(limit.bitLength(), this.rng) - .mod(limit.subtract(r.BigInteger.ONE)) - .add(r.BigInteger.ONE); - } - - /** - * Helper function for generating a large random K number; utilized for generating our initial C1 point - * TODO: Do we need to do any sort of validation on the resulting k values? - * - * @returns {BigInteger} - */ - generatePublicKey() { - const n = this.ecParams.n; - var k = this.getBigRandom(n); - return k; - } - - /** - * SM2 Key Derivation Function (KDF); Takes P2 point, and generates a key material stream large enough to encrypt all of the input data - * - * @param {*} p2 - * @param {*} len - * @returns {string} - */ - kdf(p2, len) { - const [hX, hY] = this.getPointAsHex(p2); - - var total = Math.ceil(len / 32) + 1; - var cnt = 1; - - var keyMaterial = "" - - while (cnt < total) { - var num = Utils.intToByteArray(cnt, 4, "big"); - var overall = fromHex(hX).concat(fromHex(hY)).concat(num) - keyMaterial += this.sm3(overall); - cnt++; - } - return keyMaterial - } - - /** - * Calculates the C3 component of our final encrypted payload; which is the SM3 hash of the P2 point and the original, unencrypted input data - * - * @param {*} p2 - * @param {*} input - * @returns {string} - */ - c3(p2, input) { - const [hX, hY] = this.getPointAsHex(p2); - - var overall = fromHex(hX).concat(Array.from(input)).concat(fromHex(hY)); - - return toHex(this.sm3(overall)); - - } - - /** - * SM3 setup helper function; takes input data as an array, processes the hash and returns the result - * - * @param {*} data - * @returns {string} - */ - sm3(data) { - var hashData = Utils.arrayBufferToStr(Uint8Array.from(data).buffer, false); - const hasher = new Sm3(); - hasher.update(hashData); - return hasher.finalize(); - } - - /** - * Utility function, returns an elliptic curve points X and Y values as hex; - * - * @param {EcPointFp} point - * @returns {[]} - */ - getPointAsHex(point) { - var biX = point.getX().toBigInteger(); - var biY = point.getY().toBigInteger(); - - var charlen = this.ecParams.keycharlen; - var hX = ("0000000000" + biX.toString(16)).slice(- charlen); - var hY = ("0000000000" + biY.toString(16)).slice(- charlen); - return [hX, hY] - } - } export default SM2Encrypt; From 857d3b6d17bcfcd0da1eb68f959abe23948849c1 Mon Sep 17 00:00:00 2001 From: Dan Flack Date: Fri, 20 Sep 2024 21:00:05 +0200 Subject: [PATCH 4/9] Fully functional encrypt/decrypt --- src/core/lib/SM2.mjs | 41 +++++++++++++++++++++--------- src/core/operations/SM2Decrypt.mjs | 3 ++- 2 files changed, 31 insertions(+), 13 deletions(-) diff --git a/src/core/lib/SM2.mjs b/src/core/lib/SM2.mjs index 69bcaca1..74b8639d 100644 --- a/src/core/lib/SM2.mjs +++ b/src/core/lib/SM2.mjs @@ -5,6 +5,7 @@ * @license Apache-2.0 */ +import OperationError from "../errors/OperationError.mjs"; import { fromHex } from "../lib/Hex.mjs"; import Utils from "../Utils.mjs"; import Sm3 from "crypto-api/src/hasher/sm3.mjs"; @@ -42,7 +43,6 @@ export class SM2 { * @param {string} publicKeyY */ setPublicKey(publicKeyX, publicKeyY) { - console.log('Set public key') /* * TODO: This needs some additional length validation; and checking for errors in the decoding process * TODO: Can probably support other public key encoding methods here as well in the future @@ -59,8 +59,8 @@ export class SM2 { * * @param {string} privateKey */ - setPrivateKey(privateKey) { - this.privateKey = null; //Somehow take hex input and translate back to a BigInteger??? + setPrivateKey(privateKeyHex) { + this.privateKey = new r.BigInteger(privateKeyHex, 16); } /** @@ -115,10 +115,21 @@ export class SM2 { * @param {*} input */ decrypt(input) { - /* - * - */ - var c1 = this.ecParams.curve.decodePointHex("04" + publicKeyX + publicKeyY); + var c1X = input.slice(0, 64); + var c1Y = input.slice(64, 128); + + var c3 = "" + var c2 = "" + + if (this.format == "C1C3C2") { + c3 = input.slice(128,192); + c2 = input.slice(192); + } else { + c2 = input.slice(128, -64); + c3 = input.slice(-64); + } + c2 = Uint8Array.from(fromHex(c2)) + var c1 = this.ecParams.curve.decodePointHex("04" + c1X + c1Y); /* * Compute the p2 (secret) value by taking the C1 point provided in the encrypted package, and multiplying by the private k value @@ -128,12 +139,18 @@ export class SM2 { /* * Similar to encryption; compute sufficient length key material and XOR the input data to recover the original message */ - var key = this.kdf(p2, input.byteLength); - for (let i = 0; i < input.byteLength; i++) { - input[i] ^= Utils.ord(key[i]); + var key = this.kdf(p2, c2.byteLength); + + for (let i = 0; i < c2.byteLength; i++) { + c2[i] ^= Utils.ord(key[i]); + } + + var check = this.c3(p2, c2); + if (check === c3) { + return c2.buffer; + } else { + throw new OperationError("Decryption Error -- Computed Hashes Do Not Match"); } - console.log(input) - //var dec = Buffer.from(input).toString('hex'); } diff --git a/src/core/operations/SM2Decrypt.mjs b/src/core/operations/SM2Decrypt.mjs index cf77892d..57e263d1 100644 --- a/src/core/operations/SM2Decrypt.mjs +++ b/src/core/operations/SM2Decrypt.mjs @@ -56,7 +56,8 @@ class SM2Decrypt extends Operation { var sm2 = new SM2(curveName, inputFormat); sm2.setPrivateKey(privateKey); - var result = sm2.decrypt(new Uint8Array(input)) + + var result = sm2.decrypt(input); return result } From 9eff9e501872e8a41c9e18e38905dd4874ad3a9a Mon Sep 17 00:00:00 2001 From: Dan Flack Date: Fri, 20 Sep 2024 21:07:24 +0200 Subject: [PATCH 5/9] Set default paramater indices --- src/core/operations/SM2Decrypt.mjs | 6 ++++-- src/core/operations/SM2Encrypt.mjs | 6 ++++-- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/src/core/operations/SM2Decrypt.mjs b/src/core/operations/SM2Decrypt.mjs index 57e263d1..dcacdc3f 100644 --- a/src/core/operations/SM2Decrypt.mjs +++ b/src/core/operations/SM2Decrypt.mjs @@ -35,12 +35,14 @@ class SM2Decrypt extends Operation { { "name": "Input Format", "type": "option", - "value": ["C1C3C2", "C1C2C3"] + "value": ["C1C3C2", "C1C2C3"], + "defaultIndex": 0 }, { name: "Curve", type: "option", - "value": ["sm2p256v1"] + "value": ["sm2p256v1"], + "defaultIndex": 0 } ]; } diff --git a/src/core/operations/SM2Encrypt.mjs b/src/core/operations/SM2Encrypt.mjs index 61dbe281..fe20e957 100644 --- a/src/core/operations/SM2Encrypt.mjs +++ b/src/core/operations/SM2Encrypt.mjs @@ -47,12 +47,14 @@ class SM2Encrypt extends Operation { { "name": "Output Format", "type": "option", - "value": ["C1C3C2", "C1C2C3"] + "value": ["C1C3C2", "C1C2C3"], + "defaultIndex": 0 }, { name: "Curve", type: "option", - "value": ["sm2p256v1"] + "value": ["sm2p256v1"], + "defaultIndex": 0 } ]; } From 84ce8e6f307c826a5bda17083822a5050d442931 Mon Sep 17 00:00:00 2001 From: flackjacket95 Date: Sat, 21 Sep 2024 11:33:41 +0200 Subject: [PATCH 6/9] Add tests --- tests/operations/index.mjs | 1 + tests/operations/tests/SM2.mjs | 135 +++++++++++++++++++++++++++++++++ 2 files changed, 136 insertions(+) create mode 100644 tests/operations/tests/SM2.mjs diff --git a/tests/operations/index.mjs b/tests/operations/index.mjs index 40ce7a2e..289fadc9 100644 --- a/tests/operations/index.mjs +++ b/tests/operations/index.mjs @@ -139,6 +139,7 @@ import "./tests/SetIntersection.mjs"; import "./tests/SetUnion.mjs"; import "./tests/Shuffle.mjs"; import "./tests/SIGABA.mjs"; +import "./tests/SM2.mjs"; import "./tests/SM4.mjs"; // import "./tests/SplitColourChannels.mjs"; // Cannot test operations that use the File type yet import "./tests/StrUtils.mjs"; diff --git a/tests/operations/tests/SM2.mjs b/tests/operations/tests/SM2.mjs new file mode 100644 index 00000000..278d46a7 --- /dev/null +++ b/tests/operations/tests/SM2.mjs @@ -0,0 +1,135 @@ +/** + * SM2 Tests + * + * @author flakjacket95 [dflack95@gmail.com] + * @copyright Crown Copyright 2024 + * @license Apache-2.0 + */ +import TestRegister from "../../lib/TestRegister.mjs"; + +/* Plaintexts */ + +const SMALL_PLAIN = "I am a small plaintext" +const LARGE_PLAIN = "I am a larger plaintext, that will require the encryption KDF to generate a much larger key to properly encrypt me" + +/* Test Key Parameters */ +const PUBLIC_X = "f7d903cab7925066c31150a92b31e548e63f954f92d01eaa0271fb2a336baef8" +const PUBLIC_Y = "fb0c45e410ef7a6cdae724e6a78dbff52562e97ede009e762b667d9b14adea6c" +const PRIVATE_K = "e74a72505084c3269aa9b696d603e3e08c74c6740212c11a31e26cdfe08bdf6a" + +const CURVE = "sm2p256v1" + +/* Decryption Test Ciphertext*/ + +const CIPHERTEXT_1 = "9a31bc0adb4677cdc4141479e3949572a55c3e6fb52094721f741c2bd2e179aaa87be6263bc1be602e473be3d5de5dce97f8248948b3a7e15f9f67f64aef21575e0c05e6171870a10ff9ab778dbef24267ad90e1a9d47d68f757d57c4816612e9829f804025dea05a511cda39371c22a2828f976f72e" +const CIPHERTEXT_2 = "d3647d68568a2e7a4f8e843286be7bf2b4d80256697d19a73df306ae1a7e6d0364d942e23d2340606e7a2502a838b132f9242587b2ea7e4c207e87242eea8cae68f5ff4da2a95a7f6d350608ae5b6777e1d925bf9c560087af84aba7befba713130106ddb4082d803811bca3864594722f3198d58257fe4ba37f4aa540adf4cb0568bddd2d8140ad3030deea0a87e3198655cc4d22bfc3d73b1c4afec2ff15d68c8d1298d97132cace922ee8a4e41ca288a7e748b77ca94aa81dc283439923ae7939e00898e16fe5111fbe1d928d152b216a" +const CIPHERTEXT_3 = "5f340eeb4398fa8950ee3408d0e3fe34bf7728c9fdb060c94b916891b5c693610274160b52a7132a2bf16ad5cdb57d1e00da2f3ddbd55350729aa9c268b53e40c05ccce9912daa14406e8c132e389484e69757350be25351755dcc6c25c94b3c1a448b2cf8c2017582125eb6cf782055b199a875e966" +const CIPHERTEXT_4 = "0649bac46c3f9fd7fb3b2be4bff27414d634651efd02ca67d8c802bbc5468e77d035c39b581d6b56227f5d87c0b4efbea5032c0761139295ae194b9f1fce698f2f4b51d89fa5554171a1aad2e61fe9de89831aec472ecc5ab178ebf4d2230c1fb94fca03e536b87b9eba6db71ba9939260a08ffd230ca86cb45cf754854222364231bdb8b873791d63ad57a4b3fa5b6375388dc879373f5f1be9051bc5072a8afbec5b7b034e4907aa5bb4b6b1f50e725d09cb6a02e07ce20263005f6c9157ce05d3ea739d231d4f09396fb72aa680884d78" + + +TestRegister.addTests([ + { + name: "SM2 Decrypt: Small Input; Format One", + input: CIPHERTEXT_1, + expectedOutput: SMALL_PLAIN, + recipeConfig: [ + { + "op": "SM2 Decrypt", + "args": [PRIVATE_K, "C1C3C2", CURVE] + } + ] + }, + { + name: "SM2 Decrypt: Large Input; Format One", + input: CIPHERTEXT_2, + expectedOutput: LARGE_PLAIN, + recipeConfig: [ + { + "op": "SM2 Decrypt", + "args": [PRIVATE_K, "C1C3C2", CURVE] + } + ] + }, + { + name: "SM2 Decrypt: Small Input; Format Two", + input: CIPHERTEXT_3, + expectedOutput: SMALL_PLAIN, + recipeConfig: [ + { + "op": "SM2 Decrypt", + "args": [PRIVATE_K, "C1C2C3", CURVE] + } + ] + }, + { + name: "SM2 Decrypt: Large Input; Format Two", + input: CIPHERTEXT_4, + expectedOutput: LARGE_PLAIN, + recipeConfig: [ + { + "op": "SM2 Decrypt", + "args": [PRIVATE_K, "C1C2C3", CURVE] + } + ] + }, + { + name: "SM2 Encrypt And Decrypt: Small Input; Format One", + input: SMALL_PLAIN, + expectedOutput: SMALL_PLAIN, + recipeConfig: [ + { + "op": "SM2 Encrypt", + "args": [PUBLIC_X, PUBLIC_Y, "C1C3C2", CURVE], + }, + { + "op": "SM2 Decrypt", + "args": [PRIVATE_K, "C1C3C2", CURVE] + } + ] + }, + { + name: "SM2 Encrypt And Decrypt: Large Input; Format One", + input: LARGE_PLAIN, + expectedOutput: LARGE_PLAIN, + recipeConfig: [ + { + "op": "SM2 Encrypt", + "args": [PUBLIC_X, PUBLIC_Y, "C1C3C2", CURVE], + }, + { + "op": "SM2 Decrypt", + "args": [PRIVATE_K, "C1C3C2", CURVE] + } + ] + }, + { + name: "SM2 Encrypt And Decrypt: Small Input; Format Two", + input: SMALL_PLAIN, + expectedOutput: SMALL_PLAIN, + recipeConfig: [ + { + "op": "SM2 Encrypt", + "args": [PUBLIC_X, PUBLIC_Y, "C1C2C3", CURVE], + }, + { + "op": "SM2 Decrypt", + "args": [PRIVATE_K, "C1C2C2", CURVE] + } + ] + }, + { + name: "SM2 Encrypt And Decrypt: Large Input; Format Two", + input: LARGE_PLAIN, + expectedOutput: LARGE_PLAIN, + recipeConfig: [ + { + "op": "SM2 Encrypt", + "args": [PUBLIC_X, PUBLIC_Y, "C1C2C3", CURVE], + }, + { + "op": "SM2 Decrypt", + "args": [PRIVATE_K, "C1C2C3", CURVE] + } + ] + }, +]); From 0f16fa0ce167f67b1b839477efd2055ed43a3c97 Mon Sep 17 00:00:00 2001 From: Dan Flack Date: Sat, 21 Sep 2024 11:47:01 +0200 Subject: [PATCH 7/9] Updates for linter --- src/core/lib/SM2.mjs | 45 ++++++++++++++++++++++++++------------------ 1 file changed, 27 insertions(+), 18 deletions(-) diff --git a/src/core/lib/SM2.mjs b/src/core/lib/SM2.mjs index 74b8639d..575f93ea 100644 --- a/src/core/lib/SM2.mjs +++ b/src/core/lib/SM2.mjs @@ -12,7 +12,16 @@ import Sm3 from "crypto-api/src/hasher/sm3.mjs"; import {toHex} from "crypto-api/src/encoder/hex.mjs"; import r from "jsrsasign"; +/** + * SM2 Class for encryption and decryption operations + */ export class SM2 { + /** + * Constructor for SM2 class; sets up with the curve and the output format as specified in user args + * + * @param {*} curve + * @param {*} format + */ constructor(curve, format) { this.ecParams = null; this.rng = new r.SecureRandom(); @@ -20,15 +29,15 @@ export class SM2 { For any additional curve definitions utilized by SM2, add another block like the below for that curve, then add the curve name to the Curve selection dropdown */ r.crypto.ECParameterDB.regist( - 'sm2p256v1', // name / p = 2**256 - 2**224 - 2**96 + 2**64 - 1 + "sm2p256v1", // name / p = 2**256 - 2**224 - 2**96 + 2**64 - 1 256, - 'FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFF', // p - 'FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFC', // a - '28E9FA9E9D9F5E344D5A9E4BCF6509A7F39789F515AB8F92DDBCBD414D940E93', // b - 'FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFF7203DF6B21C6052B53BBF40939D54123', // n - '1', // h - '32C4AE2C1F1981195F9904466A39C9948FE30BBFF2660BE1715A4589334C74C7', // gx - 'BC3736A2F4F6779C59BDCEE36B692153D0A9877CC62A474002DF32E52139F0A0', // gy + "FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFF", // p + "FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFC", // a + "28E9FA9E9D9F5E344D5A9E4BCF6509A7F39789F515AB8F92DDBCBD414D940E93", // b + "FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFF7203DF6B21C6052B53BBF40939D54123", // n + "1", // h + "32C4AE2C1F1981195F9904466A39C9948FE30BBFF2660BE1715A4589334C74C7", // gx + "BC3736A2F4F6779C59BDCEE36B692153D0A9877CC62A474002DF32E52139F0A0", // gy [] ) // alias this.ecParams = r.crypto.ECParameterDB.getByName(curve); @@ -38,9 +47,9 @@ export class SM2 { /** * Set the public key coordinates for the SM2 class - * - * @param {string} publicKeyX - * @param {string} publicKeyY + * + * @param {string} publicKeyX + * @param {string} publicKeyY */ setPublicKey(publicKeyX, publicKeyY) { /* @@ -56,17 +65,17 @@ export class SM2 { /** * Set the private key value for the SM2 class - * - * @param {string} privateKey + * + * @param {string} privateKey */ setPrivateKey(privateKeyHex) { this.privateKey = new r.BigInteger(privateKeyHex, 16); } - + /** * Main encryption function; takes user input, processes encryption and returns the result in hex (with the components arranged as configured by the user args) - * - * @param {*} input + * + * @param {*} input * @returns {string} */ encrypt(input) { @@ -111,8 +120,8 @@ export class SM2 { } /** * Function to decrypt an SM2 encrypted message - * - * @param {*} input + * + * @param {*} input */ decrypt(input) { var c1X = input.slice(0, 64); From f61bdf06c69f34dbaa19b3abd10e69187ca89371 Mon Sep 17 00:00:00 2001 From: Dan Flack Date: Sat, 21 Sep 2024 12:00:37 +0200 Subject: [PATCH 8/9] Additional linter corrections --- src/core/lib/SM2.mjs | 104 ++++++++++++++--------------- src/core/operations/SM2Decrypt.mjs | 8 +-- src/core/operations/SM2Encrypt.mjs | 23 +++---- tests/operations/tests/SM2.mjs | 22 +++--- 4 files changed, 74 insertions(+), 83 deletions(-) diff --git a/src/core/lib/SM2.mjs b/src/core/lib/SM2.mjs index 575f93ea..e8156410 100644 --- a/src/core/lib/SM2.mjs +++ b/src/core/lib/SM2.mjs @@ -19,8 +19,8 @@ export class SM2 { /** * Constructor for SM2 class; sets up with the curve and the output format as specified in user args * - * @param {*} curve - * @param {*} format + * @param {*} curve + * @param {*} format */ constructor(curve, format) { this.ecParams = null; @@ -39,7 +39,7 @@ export class SM2 { "32C4AE2C1F1981195F9904466A39C9948FE30BBFF2660BE1715A4589334C74C7", // gx "BC3736A2F4F6779C59BDCEE36B692153D0A9877CC62A474002DF32E52139F0A0", // gy [] - ) // alias + ); // alias this.ecParams = r.crypto.ECParameterDB.getByName(curve); this.format = format; @@ -79,15 +79,15 @@ export class SM2 { * @returns {string} */ encrypt(input) { - const G = this.ecParams.G + const G = this.ecParams.G; /* * Compute a new, random public key along the same elliptic curve to form the starting point for our encryption process (record the resulting X and Y as hex to provide as part of the operation output) * k: Randomly generated BigInteger * c1: Result of dotting our curve generator point `G` with the value of `k` */ - var k = this.generatePublicKey(); - var c1 = G.multiply(k); + const k = this.generatePublicKey(); + const c1 = G.multiply(k); const [hexC1X, hexC1Y] = this.getPointAsHex(c1); /* @@ -98,21 +98,21 @@ export class SM2 { /* * Compute the C3 SM3 hash before we transform the array */ - var c3 = this.c3(p2, input); + const c3 = this.c3(p2, input); /* * Genreate a proper length encryption key, XOR iteratively, and convert newly encrypted data to hex */ - var key = this.kdf(p2, input.byteLength); + const key = this.kdf(p2, input.byteLength); for (let i = 0; i < input.byteLength; i++) { input[i] ^= Utils.ord(key[i]); } - var c2 = Buffer.from(input).toString('hex'); + const c2 = Buffer.from(input).toString("hex"); /* * Check user input specs; order the output components as selected */ - if (this.format == "C1C3C2") { + if (this.format === "C1C3C2") { return hexC1X + hexC1Y + c3 + c2; } else { return hexC1X + hexC1Y + c2 + c3; @@ -124,37 +124,37 @@ export class SM2 { * @param {*} input */ decrypt(input) { - var c1X = input.slice(0, 64); - var c1Y = input.slice(64, 128); + const c1X = input.slice(0, 64); + const c1Y = input.slice(64, 128); - var c3 = "" - var c2 = "" + let c3 = ""; + let c2 = ""; - if (this.format == "C1C3C2") { - c3 = input.slice(128,192); + if (this.format === "C1C3C2") { + c3 = input.slice(128, 192); c2 = input.slice(192); } else { c2 = input.slice(128, -64); c3 = input.slice(-64); } - c2 = Uint8Array.from(fromHex(c2)) - var c1 = this.ecParams.curve.decodePointHex("04" + c1X + c1Y); + c2 = Uint8Array.from(fromHex(c2)); + const c1 = this.ecParams.curve.decodePointHex("04" + c1X + c1Y); /* * Compute the p2 (secret) value by taking the C1 point provided in the encrypted package, and multiplying by the private k value */ - var p2 = c1.multiply(this.privateKey); + const p2 = c1.multiply(this.privateKey); /* * Similar to encryption; compute sufficient length key material and XOR the input data to recover the original message */ - var key = this.kdf(p2, c2.byteLength); + const key = this.kdf(p2, c2.byteLength); for (let i = 0; i < c2.byteLength; i++) { c2[i] ^= Utils.ord(key[i]); } - var check = this.c3(p2, c2); + const check = this.c3(p2, c2); if (check === c3) { return c2.buffer; } else { @@ -165,9 +165,9 @@ export class SM2 { /** * Generates a large random number - * - * @param {*} limit - * @returns + * + * @param {*} limit + * @returns */ getBigRandom(limit) { return new r.BigInteger(limit.bitLength(), this.rng) @@ -177,51 +177,51 @@ export class SM2 { /** * Helper function for generating a large random K number; utilized for generating our initial C1 point - * TODO: Do we need to do any sort of validation on the resulting k values? - * + * TODO: Do we need to do any sort of validation on the resulting k values? + * * @returns {BigInteger} */ generatePublicKey() { const n = this.ecParams.n; - var k = this.getBigRandom(n); + const k = this.getBigRandom(n); return k; } /** * SM2 Key Derivation Function (KDF); Takes P2 point, and generates a key material stream large enough to encrypt all of the input data - * - * @param {*} p2 - * @param {*} len + * + * @param {*} p2 + * @param {*} len * @returns {string} */ kdf(p2, len) { const [hX, hY] = this.getPointAsHex(p2); - var total = Math.ceil(len / 32) + 1; - var cnt = 1; + const total = Math.ceil(len / 32) + 1; + let cnt = 1; - var keyMaterial = "" + let keyMaterial = ""; while (cnt < total) { - var num = Utils.intToByteArray(cnt, 4, "big"); - var overall = fromHex(hX).concat(fromHex(hY)).concat(num) + const num = Utils.intToByteArray(cnt, 4, "big"); + const overall = fromHex(hX).concat(fromHex(hY)).concat(num); keyMaterial += this.sm3(overall); cnt++; } - return keyMaterial + return keyMaterial; } /** * Calculates the C3 component of our final encrypted payload; which is the SM3 hash of the P2 point and the original, unencrypted input data - * - * @param {*} p2 - * @param {*} input - * @returns {string} + * + * @param {*} p2 + * @param {*} input + * @returns {string} */ c3(p2, input) { const [hX, hY] = this.getPointAsHex(p2); - var overall = fromHex(hX).concat(Array.from(input)).concat(fromHex(hY)); + const overall = fromHex(hX).concat(Array.from(input)).concat(fromHex(hY)); return toHex(this.sm3(overall)); @@ -229,12 +229,12 @@ export class SM2 { /** * SM3 setup helper function; takes input data as an array, processes the hash and returns the result - * - * @param {*} data + * + * @param {*} data * @returns {string} */ sm3(data) { - var hashData = Utils.arrayBufferToStr(Uint8Array.from(data).buffer, false); + const hashData = Utils.arrayBufferToStr(Uint8Array.from(data).buffer, false); const hasher = new Sm3(); hasher.update(hashData); return hasher.finalize(); @@ -242,17 +242,17 @@ export class SM2 { /** * Utility function, returns an elliptic curve points X and Y values as hex; - * + * * @param {EcPointFp} point * @returns {[]} */ getPointAsHex(point) { - var biX = point.getX().toBigInteger(); - var biY = point.getY().toBigInteger(); + const biX = point.getX().toBigInteger(); + const biY = point.getY().toBigInteger(); - var charlen = this.ecParams.keycharlen; - var hX = ("0000000000" + biX.toString(16)).slice(- charlen); - var hY = ("0000000000" + biY.toString(16)).slice(- charlen); - return [hX, hY] + const charlen = this.ecParams.keycharlen; + const hX = ("0000000000" + biX.toString(16)).slice(- charlen); + const hY = ("0000000000" + biY.toString(16)).slice(- charlen); + return [hX, hY]; } -} \ No newline at end of file +} diff --git a/src/core/operations/SM2Decrypt.mjs b/src/core/operations/SM2Decrypt.mjs index dcacdc3f..916056c3 100644 --- a/src/core/operations/SM2Decrypt.mjs +++ b/src/core/operations/SM2Decrypt.mjs @@ -5,7 +5,6 @@ */ import Operation from "../Operation.mjs"; -import OperationError from "../errors/OperationError.mjs"; import { SM2 } from "../lib/SM2.mjs"; @@ -55,12 +54,11 @@ class SM2Decrypt extends Operation { run(input, args) { const [privateKey, inputFormat, curveName] = args; - var sm2 = new SM2(curveName, inputFormat); + const sm2 = new SM2(curveName, inputFormat); sm2.setPrivateKey(privateKey); - - var result = sm2.decrypt(input); - return result + const result = sm2.decrypt(input); + return result; } } diff --git a/src/core/operations/SM2Encrypt.mjs b/src/core/operations/SM2Encrypt.mjs index fe20e957..a3ba08d9 100644 --- a/src/core/operations/SM2Encrypt.mjs +++ b/src/core/operations/SM2Encrypt.mjs @@ -5,16 +5,9 @@ */ import Operation from "../Operation.mjs"; -import OperationError from "../errors/OperationError.mjs"; import { SM2 } from "../lib/SM2.mjs"; -import { fromHex } from "../lib/Hex.mjs"; -import Utils from "../Utils.mjs"; -import Sm3 from "crypto-api/src/hasher/sm3.mjs"; -import {toHex} from "crypto-api/src/encoder/hex.mjs"; -import r from "jsrsasign"; - /** * SM2 Encrypt operation */ @@ -68,11 +61,11 @@ class SM2Encrypt extends Operation { const [publicKeyX, publicKeyY, outputFormat, curveName] = args; this.outputFormat = outputFormat; - var sm2 = new SM2(curveName, outputFormat); + const sm2 = new SM2(curveName, outputFormat); sm2.setPublicKey(publicKeyX, publicKeyY); - var result = sm2.encrypt(new Uint8Array(input)) - return result + const result = sm2.encrypt(new Uint8Array(input)); + return result; } /** @@ -85,11 +78,11 @@ class SM2Encrypt extends Operation { * @returns {Object[]} pos */ highlight(pos, args) { - const [privateKeyX, privateKeyY, outputFormat, curveName] = args; - var num = pos[0].end - pos[0].start - var adjust = 128 - if (outputFormat == "C1C3C2") { - adjust = 192 + const outputFormat = args[2]; + const num = pos[0].end - pos[0].start; + let adjust = 128; + if (outputFormat === "C1C3C2") { + adjust = 192; } pos[0].start = Math.ceil(pos[0].start + adjust); pos[0].end = Math.floor(pos[0].end + adjust + num); diff --git a/tests/operations/tests/SM2.mjs b/tests/operations/tests/SM2.mjs index 278d46a7..a3d6fd2c 100644 --- a/tests/operations/tests/SM2.mjs +++ b/tests/operations/tests/SM2.mjs @@ -1,6 +1,6 @@ /** * SM2 Tests - * + * * @author flakjacket95 [dflack95@gmail.com] * @copyright Crown Copyright 2024 * @license Apache-2.0 @@ -9,22 +9,22 @@ import TestRegister from "../../lib/TestRegister.mjs"; /* Plaintexts */ -const SMALL_PLAIN = "I am a small plaintext" -const LARGE_PLAIN = "I am a larger plaintext, that will require the encryption KDF to generate a much larger key to properly encrypt me" +const SMALL_PLAIN = "I am a small plaintext"; +const LARGE_PLAIN = "I am a larger plaintext, that will require the encryption KDF to generate a much larger key to properly encrypt me"; /* Test Key Parameters */ -const PUBLIC_X = "f7d903cab7925066c31150a92b31e548e63f954f92d01eaa0271fb2a336baef8" -const PUBLIC_Y = "fb0c45e410ef7a6cdae724e6a78dbff52562e97ede009e762b667d9b14adea6c" -const PRIVATE_K = "e74a72505084c3269aa9b696d603e3e08c74c6740212c11a31e26cdfe08bdf6a" +const PUBLIC_X = "f7d903cab7925066c31150a92b31e548e63f954f92d01eaa0271fb2a336baef8"; +const PUBLIC_Y = "fb0c45e410ef7a6cdae724e6a78dbff52562e97ede009e762b667d9b14adea6c"; +const PRIVATE_K = "e74a72505084c3269aa9b696d603e3e08c74c6740212c11a31e26cdfe08bdf6a"; -const CURVE = "sm2p256v1" +const CURVE = "sm2p256v1"; /* Decryption Test Ciphertext*/ -const CIPHERTEXT_1 = "9a31bc0adb4677cdc4141479e3949572a55c3e6fb52094721f741c2bd2e179aaa87be6263bc1be602e473be3d5de5dce97f8248948b3a7e15f9f67f64aef21575e0c05e6171870a10ff9ab778dbef24267ad90e1a9d47d68f757d57c4816612e9829f804025dea05a511cda39371c22a2828f976f72e" -const CIPHERTEXT_2 = "d3647d68568a2e7a4f8e843286be7bf2b4d80256697d19a73df306ae1a7e6d0364d942e23d2340606e7a2502a838b132f9242587b2ea7e4c207e87242eea8cae68f5ff4da2a95a7f6d350608ae5b6777e1d925bf9c560087af84aba7befba713130106ddb4082d803811bca3864594722f3198d58257fe4ba37f4aa540adf4cb0568bddd2d8140ad3030deea0a87e3198655cc4d22bfc3d73b1c4afec2ff15d68c8d1298d97132cace922ee8a4e41ca288a7e748b77ca94aa81dc283439923ae7939e00898e16fe5111fbe1d928d152b216a" -const CIPHERTEXT_3 = "5f340eeb4398fa8950ee3408d0e3fe34bf7728c9fdb060c94b916891b5c693610274160b52a7132a2bf16ad5cdb57d1e00da2f3ddbd55350729aa9c268b53e40c05ccce9912daa14406e8c132e389484e69757350be25351755dcc6c25c94b3c1a448b2cf8c2017582125eb6cf782055b199a875e966" -const CIPHERTEXT_4 = "0649bac46c3f9fd7fb3b2be4bff27414d634651efd02ca67d8c802bbc5468e77d035c39b581d6b56227f5d87c0b4efbea5032c0761139295ae194b9f1fce698f2f4b51d89fa5554171a1aad2e61fe9de89831aec472ecc5ab178ebf4d2230c1fb94fca03e536b87b9eba6db71ba9939260a08ffd230ca86cb45cf754854222364231bdb8b873791d63ad57a4b3fa5b6375388dc879373f5f1be9051bc5072a8afbec5b7b034e4907aa5bb4b6b1f50e725d09cb6a02e07ce20263005f6c9157ce05d3ea739d231d4f09396fb72aa680884d78" +const CIPHERTEXT_1 = "9a31bc0adb4677cdc4141479e3949572a55c3e6fb52094721f741c2bd2e179aaa87be6263bc1be602e473be3d5de5dce97f8248948b3a7e15f9f67f64aef21575e0c05e6171870a10ff9ab778dbef24267ad90e1a9d47d68f757d57c4816612e9829f804025dea05a511cda39371c22a2828f976f72e"; +const CIPHERTEXT_2 = "d3647d68568a2e7a4f8e843286be7bf2b4d80256697d19a73df306ae1a7e6d0364d942e23d2340606e7a2502a838b132f9242587b2ea7e4c207e87242eea8cae68f5ff4da2a95a7f6d350608ae5b6777e1d925bf9c560087af84aba7befba713130106ddb4082d803811bca3864594722f3198d58257fe4ba37f4aa540adf4cb0568bddd2d8140ad3030deea0a87e3198655cc4d22bfc3d73b1c4afec2ff15d68c8d1298d97132cace922ee8a4e41ca288a7e748b77ca94aa81dc283439923ae7939e00898e16fe5111fbe1d928d152b216a"; +const CIPHERTEXT_3 = "5f340eeb4398fa8950ee3408d0e3fe34bf7728c9fdb060c94b916891b5c693610274160b52a7132a2bf16ad5cdb57d1e00da2f3ddbd55350729aa9c268b53e40c05ccce9912daa14406e8c132e389484e69757350be25351755dcc6c25c94b3c1a448b2cf8c2017582125eb6cf782055b199a875e966"; +const CIPHERTEXT_4 = "0649bac46c3f9fd7fb3b2be4bff27414d634651efd02ca67d8c802bbc5468e77d035c39b581d6b56227f5d87c0b4efbea5032c0761139295ae194b9f1fce698f2f4b51d89fa5554171a1aad2e61fe9de89831aec472ecc5ab178ebf4d2230c1fb94fca03e536b87b9eba6db71ba9939260a08ffd230ca86cb45cf754854222364231bdb8b873791d63ad57a4b3fa5b6375388dc879373f5f1be9051bc5072a8afbec5b7b034e4907aa5bb4b6b1f50e725d09cb6a02e07ce20263005f6c9157ce05d3ea739d231d4f09396fb72aa680884d78"; TestRegister.addTests([ From ae9054dc37d842f0131a500c3b63f8ced957b587 Mon Sep 17 00:00:00 2001 From: Dan Flack Date: Sun, 22 Sep 2024 18:58:36 +0200 Subject: [PATCH 9/9] Remove highlighting and correct one module mismatch --- src/core/operations/SM2Decrypt.mjs | 5 +++++ src/core/operations/SM2Encrypt.mjs | 28 ++++++---------------------- 2 files changed, 11 insertions(+), 22 deletions(-) diff --git a/src/core/operations/SM2Decrypt.mjs b/src/core/operations/SM2Decrypt.mjs index 916056c3..39657110 100644 --- a/src/core/operations/SM2Decrypt.mjs +++ b/src/core/operations/SM2Decrypt.mjs @@ -4,6 +4,7 @@ * @license Apache-2.0 */ +import OperationError from "../errors/OperationError.mjs"; import Operation from "../Operation.mjs"; import { SM2 } from "../lib/SM2.mjs"; @@ -54,6 +55,10 @@ class SM2Decrypt extends Operation { run(input, args) { const [privateKey, inputFormat, curveName] = args; + if (privateKey.length !== 64) { + throw new OperationError("Input private key must be in hex; and should be 32 bytes"); + } + const sm2 = new SM2(curveName, inputFormat); sm2.setPrivateKey(privateKey); diff --git a/src/core/operations/SM2Encrypt.mjs b/src/core/operations/SM2Encrypt.mjs index a3ba08d9..b1e5f901 100644 --- a/src/core/operations/SM2Encrypt.mjs +++ b/src/core/operations/SM2Encrypt.mjs @@ -4,6 +4,7 @@ * @license Apache-2.0 */ +import OperationError from "../errors/OperationError.mjs"; import Operation from "../Operation.mjs"; import { SM2 } from "../lib/SM2.mjs"; @@ -20,7 +21,7 @@ class SM2Encrypt extends Operation { super(); this.name = "SM2 Encrypt"; - this.module = "Ciphers"; + this.module = "Crypto"; this.description = "Encrypts a message utilizing the SM2 standard"; this.infoURL = ""; // Usually a Wikipedia link. Remember to remove localisation (i.e. https://wikipedia.org/etc rather than https://en.wikipedia.org/etc) this.inputType = "ArrayBuffer"; @@ -61,33 +62,16 @@ class SM2Encrypt extends Operation { const [publicKeyX, publicKeyY, outputFormat, curveName] = args; this.outputFormat = outputFormat; + if (publicKeyX.length !== 64 || publicKeyY.length !== 64) { + throw new OperationError("Invalid Public Key - Ensure each component is 32 bytes in size and in hex"); + } + const sm2 = new SM2(curveName, outputFormat); sm2.setPublicKey(publicKeyX, publicKeyY); const result = sm2.encrypt(new Uint8Array(input)); return result; } - - /** - * Highlight SM2 Encrypt - * - * @param {Object[]} pos - * @param {number} pos[].start - * @param {number} pos[].end - * @param {Object[]} args - * @returns {Object[]} pos - */ - highlight(pos, args) { - const outputFormat = args[2]; - const num = pos[0].end - pos[0].start; - let adjust = 128; - if (outputFormat === "C1C3C2") { - adjust = 192; - } - pos[0].start = Math.ceil(pos[0].start + adjust); - pos[0].end = Math.floor(pos[0].end + adjust + num); - return pos; - } } export default SM2Encrypt;