ECDSA JSON Web Signature format

used e.g. by JWT
This commit is contained in:
CPlusSharp 2024-04-14 16:11:11 +02:00
parent 7e7195c291
commit 21ac516248
4 changed files with 105 additions and 8 deletions

View file

@ -6,6 +6,8 @@
import Operation from "../Operation.mjs";
import OperationError from "../errors/OperationError.mjs";
import { fromBase64 } from "../lib/Base64.mjs";
import { toHexFast } from "../lib/Hex.mjs";
import r from "jsrsasign";
/**
@ -33,6 +35,7 @@ class ECDSAVerify extends Operation {
"Auto",
"ASN.1 HEX",
"P1363 HEX",
"JSON Web Signature",
"Raw JSON"
]
},
@ -85,22 +88,39 @@ class ECDSAVerify extends Operation {
}
if (inputFormat === "Auto") {
if (input.substring(0, 2) === "30" && r.ASN1HEX.isASN1HEX(input)) {
inputFormat = "ASN.1 HEX";
} else {
inputFormat = "P1363 HEX";
const hexRegex = /^[a-f\d]{2,}$/gi;
if (hexRegex.test(input)) {
if (input.substring(0, 2) === "30" && r.ASN1HEX.isASN1HEX(input)) {
inputFormat = "ASN.1 HEX";
} else {
inputFormat = "P1363 HEX";
}
}
}
let inputBase64;
if (inputFormat === "Auto") {
try {
inputBase64 = fromBase64(input, "A-Za-z0-9-_", false);
inputFormat = "JSON Web Signature";
} catch {}
}
// convert to ASN.1 signature
let signatureASN1Hex;
switch (inputFormat) {
case "Auto":
throw new OperationError("Signature format could not be detected");
case "ASN.1 HEX":
signatureASN1Hex = input;
break;
case "P1363 HEX":
signatureASN1Hex = r.KJUR.crypto.ECDSA.concatSigToASN1Sig(input);
break;
case "JSON Web Signature":
if (!inputBase64) inputBase64 = fromBase64(input, "A-Za-z0-9-_");
signatureASN1Hex = r.KJUR.crypto.ECDSA.concatSigToASN1Sig(toHexFast(inputBase64));
break;
case "Raw JSON": {
if (!inputJson) inputJson = JSON.parse(input);
if (!inputJson.r) {