RSA Verification Javascript - javascript

I am trying to verify an RSA signature in Javascript but I can't seem to get it to work. I think I have to do something with my key and signatures but I am very confused.
Here is a link to this library
var publicKey = "MIIBIjBNBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAoPNkJzHqbY/6mAjJwb4zUbOiOjvmg3b8fvydYdGXdv04r6vzgn/FD5NPJM7bojAxi6sZ8vV+fYVIQey6HnrLSsdU/QXhT3p22a+kB4ym8SbKsOy2fWqL950nZCPYW/DC9txHy+ceFuKMAarFWAMJRe+MaVIbDIAAi8tMNjZ204GkmqveyAeA6JppzthAuiX69H8Zb3Hbs49CHNwLnSpKz5HBTfcgWqHkar2HlEFccvWC++Kq47MIkEcKScS/oneDb/TiL5ClOas1gMxfwiVtkFI6zNxxJOJDSTlY66oHCVCfTruk2pQbtOtwJEGrOwq6B536QL/EkeEKMgiqlpZJbQIDAQAB";
var stringToVerify = "aaa";
var signature = "hXyRmdQOCiVBNgDdGtiWF/gJwIk0Hs+MZtfEU4sFMEu05xsBjR9uymOJ/8FwhKCB0p+Kc1jqtsZxQqtxC0Du2EYyvjs0j5bbU9ZugZw0+9VHqKm0UA23djmZ1MT6nXt2ZEUEsS0La9yrfEnig/swAku1fQorsxG5FK5GFRjaacNIF+O0GOr0cbzEvlaAof6T6JFMueIw/iZykivs8XohSlghdPzoNmVueY9JF1XbtHZayau17jGhFTbeNNxbDBanPo593eZdgi5aTZMYHbxHx87cfU1sE5cjSioPQLsG9cQwVaWrrZa9BnB8IhR8Rv0NdRXYNTcVhc+sVHJN/QghNQ==";
var KJUR = require("cloud/jsrsasign-4.7.0/npm/lib/jsrsasign.js");
var verifier = new KJUR.crypto.Signature({alg: "SHA1withRSA", prov: "cryptojs/jsrsa"});
verifier.init(publicKey);
verifier.updateString(stringToVerify);
console.log(verifier.verify(signature));
Thanks in advance

You need to base 64 decode both the public key and the signature. They key and signature should then be re-encoded as hexadecimals. Then you hopefully should be able to use this method to generate a public RSAKey object.
I'm saying hopefully, as the the API description is just horrible. Personally I would not recommend to use such an API.

Related

Signing AWS API Gateway Request using Node

I've been searching for ways to restrict access to an API made for using a AWS Lambda function written on javascript.
I've found documentation on how to use AWS Signature S4, but I still do not understand it.
According to creating a signature, after applying the pseudocode I should get the signature to be placed on the header.
I've found the following code that addresses this point:
// Example of signature generator
var crypto = require("crypto-js");
function getSignatureKey(Crypto, key, dateStamp, regionName, serviceName) {
var kDate = Crypto.HmacSHA256(dateStamp, "AWS4" + key);
var kRegion = Crypto.HmacSHA256(regionName, kDate);
var kService = Crypto.HmacSHA256(serviceName, kRegion);
var kSigning = Crypto.HmacSHA256("aws4_request", kService);
return kSigning;
}
console.log(getSignatureKey(crypto,'secretkey','date','us-east-2','iam'));
Here comes my first question, I do not know what should be the output of getSignatureKey()? This is because on the documentation it is a very long string, while the output I got was {words:[x,x,x,x,x,x,x,x],sigBytes: 32},where the x are random numbers.
Moreover, after getting the signature and filling the header for the request with the "authorization" field and others, how do I filter unproper requests? Do I have to create a policy for the AWS API so it only allows signed requests? Here I guess I should follow Signing Requests.
Thanks!
Here is the simple implementation of Signed URL's. aws-cloudfront-sign package offers simpler implementation.
var cfsign = require('aws-cloudfront-sign');
var signingParams = {
keypairId: process.env.PUBLIC_KEY,
privateKeyString: process.env.PRIVATE_KEY,
// Optional - this can be used as an alternative to privateKeyString
privateKeyPath: '/path/to/private/key',
expireTime: 1426625464599
}
// Generating a signed URL
var signedUrl = cfsign.getSignedUrl(
'http://example.cloudfront.net/path/to/s3/object',
signingParams
);
https://aws.amazon.com/blogs/developer/creating-amazon-cloudfront-signed-urls-in-node-js/
Purpose of SignedURL is to serve Private Contents.
More details at,
http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/PrivateContent.html
Hope it helps.

How do I decode a BASE64, PCKS-8 representation of a private key in NetSuite or javascript?

I'm working on a suitescript to integrate NetSuite with the Walmart Marketplace APIs. And, as the another OP here says it right their documentation pretty much says if you don't use Java you're on your own.
I'm looking for a way to do the same either in suitescript or javascript.
Instruction from Walmart's API documentation:
Sign the byte array representation of this data by:
Decoding the Base 64, PKCS-8 representation of your private key. Note that the key is encoded using PKCS-8. Libraries in various languages offer the ability to specify that the key is in this format and not in other conflicting formats such as PKCS-1. Use this byte representation of your key to sign the data using SHA-256 With RSA. Encode the resulting signature using Base 64.
And, a java code from their documentation to do the same:
public static String signData(String stringToBeSigned, String encodedPrivateKey) {
String signatureString = null;
try {
byte[] encodedKeyBytes = Base64.decodeBase64(encodedPrivateKey);
PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(encodedKeyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
PrivateKey myPrivateKey = kf.generatePrivate(privSpec);
Signature signature = Signature.getInstance("SHA256withRSA");
signature.initSign(myPrivateKey);
byte[] data = stringToBeSigned.getBytes("UTF-8");
signature.update(data);
byte[] signedBytes = signature.sign();
signatureString = Base64.encodeBase64String(signedBytes);
} catch (Exception e) {
e.printStackTrace();
}
return signatureString;
}
For reference, here's the similar thing asked for dot net. Any help would be appreciated.
I tried developing a SAML connector in Javascript once and found several libraries that deal with different key file formats etc. I got fairly far along but the time to run some of the scripts was incredible (imagine trying to login but the process taking two minutes to decide your login was valid)
At that point I switched to an external system and managed the SSO with Netsuite's inbound SSO.
It doesn't look like things have improved that much with NS in the crypto department even with SS 2.0.
I'd tend to package this into two parts. Generate your files in Suitescript and pass them through a java based web service that handles the signing requirements. Minimizes the amount of Java you have to write and keeps your transaction extraction/formatting scripts under easy control.
I found a library (jsrsasign) that will do the Walmart signature from NetSuite server side in under 4 seconds! (Marketplace has gone to OAuth2, but I'm stuck with signing as a Drop Ship Vendor)
/**
*#NApiVersion 2.x
*#NScriptType ScheduledScript
*/
define(['N/log', 'N/https', '../lib/jsrsasign-master/jsrsasign-all-min'],
function(log, https) {
function execute(context) {
var pkcs8Der = {Your Walmart Private Key};
var pkcs8Pem = [
'-----BEGIN PRIVATE KEY-----',
pkcs8Der.match(/.{0,64}/g).join('\n'),
'-----END PRIVATE KEY-----'
].join('\n');
var tStamp = Date.now()
var stringToSign = [
tStamp,
{Your Walmart Comsumer Id},
{Request URL},
{Request Method (All Caps)}
].join('\n') + '\n';
var sig = new KJUR.crypto.Signature({"alg": "SHA256withRSA"});
sig.init(pkcs8Pem);
var sigVal = hextob64(sig.signString(stringToSign));
log.audit({title: 'Signature', details: sigVal});
log.audit({title: 'Timestamp', details: tStamp});
}
return {
execute: execute,
};
}
);
I had to add the following code to the jsrsasign-all-min.js library file for the Scheduled Script to load the module:
var navigator = {}, window = undefined;

Encrypting with EasyRSA in PHP and Decrypting with Node-RSA in JS

Problem
I'm trying to create a simple trustless file sharing application. I'm using EasyRSA (https://github.com/paragonie/EasyRSA) to create a key-pair and then encrypt my data with the public key. I'm sending the private key to my JS wherein I'm using Node-RSA (https://github.com/rzcoder/node-rsa). Here, I try to decrypt using the previously created private key. But this happens:
Error
Uncaught Error: Error during decryption (probably incorrect key). Original error: Error: Incorrect data or key
at NodeRSA.module.exports.NodeRSA.$$decryptKey (drop.js:23265)
at NodeRSA.module.exports.NodeRSA.decrypt (drop.js:23213)
at window.onload (drop.js:22270)
My JS code looks something like this:
var NodeRSA = require('node-rsa');
window.onload = function() {
var key_val = $('#key').val();
var ciphertext = $('#encrypted').val();
var key = new NodeRSA();
key.importKey($('#key').val(), 'pkcs1');
var ciphertext_base = key.encrypt(ciphertext, 'base64');
var decrypted_base = key.decrypt(btoa(ciphertext));
console.log(decrypted);
}
I think this has got something to do with the incompatibility between the formats/key-sizes/algos used to create the keys. If someone could help me 'hack' this and make it work, I would be very grateful to you.

Being unable to sign an Buffer with ECDH private key in Node.js

I'm getting a 'error:0D07209B:asn1 encoding routines:ASN1_get_object:too long' when trying to sign a object with a PrivateKey I generated, in Node.js.
The buf is a simple object encoded with node-cbor
var ecdh = crypto.createECDH('secp256k1')
ecdh.generateKeys()
var sign = crypto.createSign('RSA-SHA256')
sign.update(buf)
var buf_signed = sign.sign('-----BEGIN PRIVATE KEY-----\n' +
ecdh.getPrivateKey('base64') +
'\n-----END PRIVATE KEY-----' +
'\n-----BEGIN CERTIFICATE-----' +
'\n-----END CERTIFICATE-----', 'binary')
Would the Certificate be strictly necessary? Am I missing any information in the PEM string?
Any help is appreciated, thank you :)
It turns out I was missing that for EC Digital Signing, the right way to do it is using ECDSA.
Node.js doesn't implement it natively, but this module makes a good job of doing so:
https://www.npmjs.com/package/ecdsa

SJCL key generation

for my website "moneyart.info" I want to generate ECC public and private keys with JavaScript library sjcl. I tried following code:
*
crypto_keys = sjcl.ecc.elGamal.generateKeys(256);
var public_key = crypto_keys.pub.get();
var secret_key = crypto_keys.sec.get();
var public_key_hex = sjcl.codec.hex.fromBits(public_key.x) + sjcl.codec.hex.fromBits(public_key.y);
var secret_key_hex = sjcl.codec.hex.fromBits(secret_key);
alert(secret_key_hex);*
I get the error message:
TypeError: sjcl.ecc is undefined
I think I have to construct a class with new, but I dont know which one.
I found the mistake: ecc.elGamal is no standard sjcl function. I have to compile the sjcl.js file manually with additional functionality included. blog.peramid.es

Categories

Resources