Skip to content

Instantly share code, notes, and snippets.

@abechanta
Last active August 31, 2019 15:06
Show Gist options
  • Select an option

  • Save abechanta/019ca62f49b0e4e20e0cf62b3dac878d to your computer and use it in GitHub Desktop.

Select an option

Save abechanta/019ca62f49b0e4e20e0cf62b3dac878d to your computer and use it in GitHub Desktop.
Simple Authentication Sample on Node.js
const crypto = require("crypto");
const fs = require("fs");
function getSignature(type, pkey, data) {
var pkey = fs.readFileSync(pkey);
var data = new Buffer.from(JSON.stringify(data));
const signer = crypto.createSign(type).update(data);
const signature = signer.sign(pkey, "base64");
return signature;
}
const now = Math.round(new Date().getTime() / 1000);
const claimData = {
"exp": now + 5 * 60,
"server_state": "WErVieau7umEw1k2aRYOqXL-syCeRzZ3M4UBClLeZ2k",
"sub": "qwertyuiopas",
"iat": now + 0,
"aud": "deadbeef00deadbeef",
"iss": "https://www.example.com",
};
const signature = getSignature("RSA-SHA256", "sample.pem", claimData);
const encryptedClaimData = {
claim: claimData,
signature: signature,
};
console.log(JSON.stringify(encryptedClaimData));
const crypto = require("crypto");
const fs = require("fs");
function verifySignature(type, cert, data, signature) {
var cert = fs.readFileSync(cert);
var data = new Buffer.from(JSON.stringify(data));
const verifier = crypto.createVerify(type).update(data);
const verified = verifier.verify(cert, signature, "base64");
return verified;
}
const input = fs.readFileSync(process.stdin.fd, "utf8");
const inputData = JSON.parse(input);
const verified = verifySignature("RSA-SHA256", "sample.crt", inputData["claim"], inputData["signature"]);
console.log(verified);
const fs = require("fs");
const input = fs.readFileSync(process.stdin.fd, "utf8");
const inputData = JSON.parse(input);
inputData["claim"]["exp"] += 1;
console.log(JSON.stringify(inputData));
#!/bin/sh
openssl genrsa -out sample.pem
openssl req -new -key sample.pem -out sample.csr
openssl x509 -req -days 31 -in sample.csr -signkey sample.pem -out sample.crt
cat << EOS
Key-pair and Certification are created.
1)
Now, you can add a signature against some json object.
Type:
> node cert-creater.js
2)
Then, you can verify the json object if it's modified or not.
Type:
> node cert-creater.js | node cert-verifier.js
This outputs 'true' because it's not modified.
3)
After then, you can tell that the json object is modified.
Type:
> node cert-creater.js | node cheater.js | node cert-verifier.js
This outputs 'false' because 'cheater.js' modifies 'exp' field.
EOS
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment