Skip to content

Instantly share code, notes, and snippets.

@ElectricImpSampleCode
Last active September 10, 2018 14:47
Show Gist options
  • Save ElectricImpSampleCode/7c9a1f6b527909492d61c25638560506 to your computer and use it in GitHub Desktop.
Save ElectricImpSampleCode/7c9a1f6b527909492d61c25638560506 to your computer and use it in GitHub Desktop.
Electric Imp crypto.verify() example
// CONSTANTS
// Full 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-----";
// The public key must be extracted from the private key file:
// $ openssl rsa -pubout < rsa.key > rsa.pub
const RSA_PUBLIC_KEY_PEM = @"
-----BEGIN PUBLIC KEY-----
...
-----END PUBLIC KEY-----";
// FUNCTIONS
function decodePem(pemString) {
local lines = split(pemString, "\n");
local start = -1;
local end = -1;
foreach (index, line in lines) {
if (line == "-----BEGIN PUBLIC KEY-----" || line == "-----BEGIN RSA PRIVATE KEY-----") start = index + 1;
if (line == "-----END PUBLIC KEY-----" || 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;
}
// START OF RUNTIME
local message = "Hello, World!";
local mode = crypto.RSASSA_PKCS1_SHA256;
// NOTE 'message' and 'signuture would
crypto.sign(mode, message, decodePem(RSA_PRIVATE_KEY_PEM), function(error, signature) {
if (error) {
server.error(error);
return;
}
crypto.verify(mode, message, signature, decodePem(RSA_PUBLIC_KEY_PEM), function(error, isVerified) {
if (error) {
server.error(error);
return;
}
server.log("Message is " + (isVerified ? "valid" : "invalid"));
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment