Created
September 16, 2022 22:03
-
-
Save hertzg/e6457b4f1924efd4289dca9489b67c7f to your computer and use it in GitHub Desktop.
Create RSA Public Key Object form modulus and exponent components using node Crypto
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { createPublicKey } from "node:crypto"; | |
const length = (n) => { | |
if (n < 0x80) { | |
return [n]; | |
} else if (n < 0x100) { | |
return [0x81, n]; | |
} else if (n < 0x10000) { | |
return [0x82, n >>> 8, n & 255]; | |
} else if (n < 0x1000000) { | |
return [0x83, n >>> 16, (n >>> 8) & 255, n & 255]; | |
} | |
throw new Error("too big"); | |
}; | |
export const createRsaPublicKeyFromComponents = (modulus, exponent) => { | |
const modulusBytes = [0x02, ...length(modulus.length), ...modulus]; | |
const exponentBytes = [0x02, ...length(exponent.length), ...exponent]; | |
return createPublicKey({ | |
key: Buffer.from([ | |
0x30, // SEQUENCE | |
...length(modulusBytes.length + exponentBytes.length), | |
...modulusBytes, | |
...exponentBytes, | |
]), | |
format: "der", | |
type: "pkcs1", | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment