Skip to content

Instantly share code, notes, and snippets.

@CrowdHailer CrowdHailer/sign.js
Last active Mar 13, 2019

Embed
What would you like to do?
Web crypto to erlang/Elixir
// NEEDS TO RUN IN SECURE (HTTPS) CONTEXT.
async function run() {
// New key pair
var keyPair = await window.crypto.subtle.generateKey(
{
name: "ECDSA",
namedCurve: "P-521"
},
true,
["sign", "verify"]
);
// Format public key
var publicPEM = spkiToPEM(await window.crypto.subtle.exportKey(
"spki",
keyPair.publicKey
));
console.log(publicPEM)
// Encode message
var message = "abc";
var encoder = new TextEncoder();
var bytes = (encoder).encode(message);
var signature = await window.crypto.subtle.sign(
{
name: "ECDSA",
hash: {name: "SHA-256"},
},
keyPair.privateKey,
bytes
);
var encodedSignature = window.btoa(arrayBufferToString(signature));
console.log(encodedSignature);
}
// https://stackoverflow.com/questions/40314257/export-webcrypto-key-to-pem-format
function spkiToPEM(keydata){
var keydataS = arrayBufferToString(keydata);
var keydataB64 = window.btoa(keydataS);
var keydataB64Pem = formatAsPem(keydataB64);
return keydataB64Pem;
}
function arrayBufferToString( buffer ) {
var binary = '';
var bytes = new Uint8Array( buffer );
var len = bytes.byteLength;
for (var i = 0; i < len; i++) {
binary += String.fromCharCode( bytes[ i ] );
}
return binary;
}
function formatAsPem(str) {
var finalString = '-----BEGIN PUBLIC KEY-----\n';
while(str.length > 0) {
finalString += str.substring(0, 64) + '\n';
str = str.substring(64);
}
finalString = finalString + "-----END PUBLIC KEY-----";
return finalString;
}
run();
// Example out put for encodedSignature and publicPEM included below
message = "abc"
encoded_signature = "AOqjfvb1P0fYdbnq+f3XsbOR/Lylq4csC5e1Ks4cKRTcWKQyH4CVr/XRHCmZDEWOpaA8gwuM3Z3qD21vMaixySUPASTDnd1J8shNx51MCbONIReTNuH53kzxykLpf0riSyMbEBQtie4/pxlrolUOsDja2f/ikgM/lGXtCTXz2faV4m2Y"
public_PEM = "-----BEGIN PUBLIC KEY-----
MIGbMBAGByqGSM49AgEGBSuBBAAjA4GGAAQB7PNQVbADLNyobtijE5NVZUvHs74h
iMntCbp0C8pdU1IQRWlAfDeEs/iuxA32VARw9Q5/0mim8Si8JcpCJnhS0u8AESMf
Ux3WqzHhB33t4q3iPsJbM7zmN91QNnbYErrGqEDCmSruPpKw1iK5dJ3/xQZbkpmR
ztoVwrZoCoGUu+WTqEI=
-----END PUBLIC KEY-----"
signature = Base.decode64(encoded_signature)
[key_entry] = :public_key.pem_decode(public_PEM)
public_key = :public_key.pem_entry_decode(key_entry)
:public_key.verify(
message,
:sha256,
signature,
public_key
)
# returns false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.