Last active
September 10, 2018 14:45
-
-
Save ElectricImpSampleCode/e133fdd2398b83b4f964004190ff2b9c to your computer and use it in GitHub Desktop.
Electric Imp imp API crypto.sign() PKCS#1 example
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
// CONSTANTS | |
// Full PKCS#1 key omitted but can be generated with: | |
// $ openssl genrsa -out rsa.key 2048 | |
const RSA_PRIVATE_KEY_PEM = @" | |
-----BEGIN RSA PRIVATE KEY----- | |
... | |
-----END RSA PRIVATE KEY----- | |
"; | |
function decodePrivatePem(pemString) { | |
local lines = split(pemString, "\n"); | |
local start = -1; | |
local end = -1; | |
foreach (index, line in lines) { | |
if (line == "-----BEGIN RSA PRIVATE KEY-----") start = index + 1; | |
if (line == "-----END RSA PRIVATE KEY-----") end = index; | |
} | |
if (start != -1 && end > start) { | |
local all = lines.slice(start, end).reduce(@(a, b) a + b); | |
return http.base64decode(all); | |
} | |
return null; | |
} | |
function hexString(aBlob) { | |
local str = ""; | |
foreach (byte in aBlob) str += format("%02x", byte); | |
return str; | |
} | |
local mode = crypto.RSASSA_PKCS1_SHA256; | |
local message = "Hello, World!"; | |
local key = decodePrivatePem(RSA_PRIVATE_KEY_PEM); | |
crypto.sign(mode, message, key, function(error, signature) { | |
if (error) { | |
server.error(error); | |
return; | |
} | |
server.log("Signature:"); | |
server.log(hexString(signature)); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment