Skip to content

Instantly share code, notes, and snippets.

@ElectricImpSampleCode
Last active September 10, 2018 14:45
Show Gist options
  • Save ElectricImpSampleCode/e9571bcce78fb9d2469019b4512a309a to your computer and use it in GitHub Desktop.
Save ElectricImpSampleCode/e9571bcce78fb9d2469019b4512a309a to your computer and use it in GitHub Desktop.
Electric Imp imp API crypto.sign() PKCS#8 example
// CONSTANTS
// Full PKCS#8 key omitted but can be generated with:
// $ openssl req -x509 -nodes -newkey rsa:2048 -batch -keyout key.pem
const RSA_PRIVATE8_KEY_PEM = @"
-----BEGIN PRIVATE KEY-----
...
-----END PRIVATE KEY-----";
function decodePrivatePem(pemString) {
local lines = split(pemString, "\n");
local start = -1;
local end = -1;
foreach (index, line in lines) {
if (line == "-----BEGIN PRIVATE KEY-----") start = index + 1;
if (line == "-----END 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_PRIVATE8_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