Can I create signature like code below in Nodejs?
# Load PRIVATE key
private_key = OpenSSL::PKey::RSA.new(File.read(Rails.root + ENV['EPAY_PRIVATE_KEY']))
# Sign your data
signMessage = private_key.sign(OpenSSL::Digest::SHA1.new, message)
# Base64 message
baseMessage = Base64.encode64(signMessage.to_s)
You should be able to do the same thing in Node.js, creating a signature is quite easy, for example:
const crypto = require('crypto');
const fs = require('fs');
const privateKey = fs.readFileSync('./private-key.pem', 'utf8');
const message = "some message data";
const sign = crypto.createSign('SHA1');
sign.update(message);
sign.end();
const signature = sign.sign(privateKey);
console.log("Signature: ", signature.toString('base64'));
This creates a base64 encoded SHA1 signature of the message.
Related
good afternoon colleagues, please see if you can give me a light
example 1
void conect(void) {
esp_mqtt_client_handle_t mqttClient;
const char *certificate;
certificate =
"-----BEGIN CERTIFICATE-----\n"
"MIIDrzCCApegAwIBAgIQCDvgVpBCRrGhdWrJWZHHSjANBgkqhkiG9w0BAQUFADBh\n"
"MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3\n"
"d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBD\n"
"QTAeFw0wNjExMTAwMDAwMDBaFw0zMTExMTAwMDAwMDBaMGExCzAJBgNVBAYTAlVT\n"
"MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j\n"
"b20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IENBMIIBIjANBgkqhkiG\n"
"9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4jvhEXLeqKTTo1eqUKKPC3eQyaKl7hLOllsB\n"
"CSDMAZOnTjC3U/dDxGkAV53ijSLdhwZAAIEJzs4bg7/fzTtxRuLWZscFs3YnFo97\n"
"nh6Vfe63SKMI2tavegw5BmV/Sl0fvBf4q77uKNd0f3p4mVmFaG5cIzJLv07A6Fpt\n"
"43C/dxC//AH2hdmoRBBYMql1GNXRor5H4idq9Joz+EkIYIvUX7Q6hL+hqkpMfT7P\n"
"T19sdl6gSzeRntwi5m3OFBqOasv+zbMUZBfHWymeMr/y7vrTC0LUq7dBMtoM1O/4\n"
"gdW7jVg/tRvoSSiicNoxBN33shbyTApOB6jtSj1etX+jkMOvJwIDAQABo2MwYTAO\n"
"BgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUA95QNVbR\n"
"TLtm8KPiGxvDl7I90VUwHwYDVR0jBBgwFoAUA95QNVbRTLtm8KPiGxvDl7I90VUw\n"
"DQYJKoZIhvcNAQEFBQADggEBAMucN6pIExIK+t1EnE9SsPTfrgT1eXkIoyQY/Esr\n"
"hMAtudXH/vTBH1jLuG2cenTnmCmrEbXjcKChzUyImZOMkXDiqw8cvpOp/2PV5Adg\n"
"06O/nVsJ8dWO41P0jmP6P6fbtGbfYmbW0W5BjfIttep3Sp+dWOIrWcBAI+0tKIJF\n"
"PnlUkiaY4IBIqDfv8NZ5YBberOgOzW6sRBc4L0na4UU+Krk2U886UAb3LujEV0ls\n"
"YSEY1QSteDwsOoBrp+uvFRTp2InBuThs4pFsiv9kuXclVzDAGySj4dzp30d8tbQk\n"
"CAUw7C29C79Fv1C5qfPrmAESrciIxpg0X40KPMbp1ZWVbd4=\n"
"-----END CERTIFICATE-----\n"
esp_mqtt_client_config_t mqttConfig = {};
mqttConfig.uri = "mqtts://broker.emqx.io";
mqttConfig.port = 8883;
mqttConfig.cert_pem = certificate;
mqttConfig.username = "";
mqttConfig.password = "";
mqttConfig.keepalive = 60;
mqttConfig.client_id = "test";
mqttClient = esp_mqtt_client_init(&mqttConfig);
esp_mqtt_client_start(mqttClient);
}
the code above works perfectly but when I change the certificate variable to std::string it gives an error
below is the change and the error
example 2
void conect(void) {
esp_mqtt_client_handle_t mqttClient;
std::string certificate;
certificate =
"-----BEGIN CERTIFICATE-----\n"
"MIIDrzCCApegAw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Diqw8cvpOp/2PV5Adg\n"
"06O/nVsJ8dWO41P0jmP6P6fbtGbfYmbW0W5BjfIttep3Sp+dWOIrWcBAI+0tKIJF\n"
"PnlUkiaY4IBIqDfv8NZ5YBberOgOzW6sRBc4L0na4UU+Krk2U886UAb3LujEV0ls\n"
"YSEY1QSteDwsOoBrp+uvFRTp2InBuThs4pFsiv9kuXclVzDAGySj4dzp30d8tbQk\n"
"CAUw7C29C79Fv1C5qfPrmAESrciIxpg0X40KPMbp1ZWVbd4=\n"
"-----END CERTIFICATE-----\n"
esp_mqtt_client_config_t mqttConfig = {};
mqttConfig.uri = "mqtts://broker.emqx.io";
mqttConfig.port = 8883;
mqttConfig.cert_pem = certificate.c_str();
mqttConfig.username = "";
mqttConfig.password = "";
mqttConfig.keepalive = 60;
mqttConfig.client_id = "test";
mqttClient = esp_mqtt_client_init(&mqttConfig);
esp_mqtt_client_start(mqttClient);
}
when this certificate variable is set to std::string it gives an error:
E (5021) esp-tls-mbedtls: mbedtls_x509_crt_parse returned -0x2180
E (5021) esp-tls-mbedtls: Failed to set client configurations, returned [0x8015] (ESP_ERR_MBEDTLS_X509_CRT_PARSE_FAILED)
E (5031) esp-tls: create_ssl_handle failed
E (5031) esp-tls: Failed to open new connection
E (5041) TRANSPORT_BASE: Failed to open a new connection
E (5051) MQTT_CLIENT: Error transport connect
mqttConfig.cert_pem accepts const char * but converting a string variable gives the above error and if I create the variable as const char * it works as per example 1
can someone please guide me what could be going on
const char *p = certificate.c_str();
mqttConfig.cert_pem = p;
Thank you very much
Just starting with Deno, I am trying to figure out how to calculate a binary file checksum. It seems to me that the problem is not with the methods provided by the hash module of the standard library, but with the file streaming method and/or the type of the chunks feeding the hash.update method.
I have been trying a few alternatives, related to file opening and chunk types,with no success. A simple example is in the following:
import {createHash} from "https://deno.land/std#0.80.0/hash/mod.ts";
const file= new File(["my_big_folder.tar.gz"], "./my_big_folder.tar.gz");
const iterator = file.stream() .getIterator();
const hash = createHash("md5");
for await( let chunk of iterator){
hash.update(chunk);
}
console.log(hash.toString()); //b35edd0be7acc21cae8490a17c545928
This code compiles and runs with no errors, pity that the result is different from what I get running the functions of the crypto module provided by node and the md5sum provided by linux coreutils. Any suggestion ?
nodejs code:
const crypto = require('crypto');
const fs = require('fs');
const hash = crypto.createHash('md5');
const file = './my_big_folder.tar.gz';
const stream = fs.ReadStream(file);
stream.on('data', data=> { hash.update(data); });
stream.on('end', ()=> {
console.log(hash.digest('hex')); //c18f5eac67656328f7c4ec5d0ef5b96f
});
The same result in bash:
$ md5sum ./my_big_folder.tar.gz
$ c18f5eac67656328f7c4ec5d0ef5b96f ./my_big_folder.tar.gz
on Windows 10 this can be used:
CertUtil -hashfile ./my_big_folder.tar.gz md5
The File API isn't used to read a File in Deno, to do that you need to use the Deno.open API and then turn it into an iterable like this
import {createHash} from "https://deno.land/std#0.80.0/hash/mod.ts";
const hash = createHash("md5");
const file = await Deno.open(new URL(
"./BigFile.tar.gz",
import.meta.url, //This is needed cause JavaScript paths are relative to main script not current file
));
for await (const chunk of Deno.iter(file)) {
hash.update(chunk);
}
console.log(hash.toString());
Deno.close(file.rid);
import { crypto, toHashString } from 'https://deno.land/std#0.176.0/crypto/mod.ts';
const getFileBuffer = (filePath: string) => {
const file = Deno.openSync(filePath);
const buf = new Uint8Array(file.statSync().size);
file.readSync(buf);
file.close();
return buf;
};
const getMd5OfBuffer = (data: BufferSource) => toHashString(crypto.subtle.digestSync('MD5', data));
export const getFileMd5 = (filePath: string) => getMd5OfBuffer(getFileBuffer(filePath));
I'm trying to use iOS swift (client side) to encrypt some data before sending it to node.js server to decrypt it. However, while decrypting in node.js I'm hitting:
Error: error:04099079:rsa routines:RSA_padding_check_PKCS1_OAEP_mgf1:oaep decoding error
at Object.privateDecrypt (internal/crypto/cipher.js:53:12)
at decrypt (/Users/iosbeta/Documents/RSA/RSANode/testRsa.js:20:28)
at Object.<anonymous> (/Users/RSANode/testRsa.js:36:13)
at Module._compile (internal/modules/cjs/loader.js:777:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:788:10)
at Module.load (internal/modules/cjs/loader.js:643:32)
at Function.Module._load (internal/modules/cjs/loader.js:556:12)
at Function.Module.runMain (internal/modules/cjs/loader.js:840:10)
at internal/main/run_main_module.js:17:11 {
library: 'rsa routines',
function: 'RSA_padding_check_PKCS1_OAEP_mgf1',
reason: 'oaep decoding error',
code: 'ERR_OSSL_RSA_OAEP_DECODING_ERROR'
}
I've tried to encrypt and decrypt using only node.js code and it works. However, I couldn't get it to work after encrypting using iOS and decrypt using node.js. Here's how I generate the cert, encryption and decryption in node.js:
// ****************************************************************************************************************
// For generating keys
// ****************************************************************************************************************
const { writeFileSync } = require('fs')
const { generateKeyPairSync } = require('crypto')
function generateKeys() {
const { privateKey, publicKey } = generateKeyPairSync('rsa', {
modulusLength: 4096,
publicKeyEncoding: {
type: 'pkcs1',
format: 'pem',
},
privateKeyEncoding: {
type: 'pkcs1',
format: 'pem',
cipher: 'aes-256-cbc',
passphrase: '',
},
})
writeFileSync('private.pem', privateKey)
writeFileSync('public.pem', publicKey)
}
// ****************************************************************************************************************
// For encrypting and decrypting
// ****************************************************************************************************************
const crypto = require('crypto')
const path = require('path')
const fs = require('fs')
function encrypt(toEncrypt, relativeOrAbsolutePathToPublicKey) {
const absolutePath = path.resolve(relativeOrAbsolutePathToPublicKey)
const publicKey = fs.readFileSync(absolutePath, 'utf8')
const buffer = Buffer.from(toEncrypt, 'utf8')
const encrypted = crypto.publicEncrypt(publicKey, buffer)
return encrypted.toString('base64')
}
function decrypt(toDecrypt, relativeOrAbsolutePathtoPrivateKey) {
const absolutePath = path.resolve(relativeOrAbsolutePathtoPrivateKey)
const privateKey = fs.readFileSync(absolutePath, 'utf8')
const buffer = Buffer.from(toDecrypt, 'base64')
const decrypted = crypto.privateDecrypt(
{
key: privateKey.toString(),
passphrase: '',
},
buffer,
)
return decrypted.toString('utf8')
}
This is the iOS swift code for creating encryption using the public pem cert and SwiftyRSA framework:
import SwiftyRSA
func createEncryption(){
do {
let publicKey = try PublicKey(pemNamed: "public")
let clear = try ClearMessage(string: "Clear Text", using: .utf8)
let encrypted = try clear.encrypted(with: publicKey, padding: .PKCS1)
// Then you can use:
let data = encrypted.data
let base64String = encrypted.base64String
print(base64String)
} catch {
// handle other errors
print(error)
}
}
This is my public.pem file:
-----BEGIN RSA PUBLIC KEY-----
MIICCgKCAgEA2CtJRRthGDNTfbO1SO0MZWMKNC8YWA4ziAbrnYcdURGycg+RnfDw
hLb28kmPD2h6da/35LuklZHfGhgQSV1g288mdhKQILS9qjKI0/d0HRXxeOiOHiOl
zKhTHh+IsXRMQWrk8V2esnyNZVQ/rqr7t1YxQxGyp+eFoyH7//re9Kc8/hc9DRtq
+vcXKrX8m0K3M6t4fu9KH8iN0xlSeT9ufIrl//2/Omneic7ifZGNIVF+Grr8gpw4
CPYw1v8z6KjV8+5UhAmtiGjT2Jfcb8v9TKv6mBzYY15cvjAToWYxZaN3BPHx4yj5
7zdvewF4gIDM0O+XO9xShGCk213V4jdGyv21jaeMNqG6cmizzOHOZimpdy52cWou
ycBiIHQJrbSwGfxLtJt7D+DNLQibF35e3nQFYb+wiqtENRQJdUrZ37WmNPkpzlvY
dfYEfxWbgyckTmtCkqV6k2repYtbwb/l4AhYp/DgOPrV9waNTJqkNmy1fpfx8Azv
BLsII0MdXO5Ji1boAi3bf+IVuWlMVj5be4h/IJ2p0DGXiPh6cNWpmEXm1BoNrZ3B
GcnrAVp1Aa4FRR1kJUaHb47qVtStg2lyw0q+bwqE2vcGtRwEXWKIOQuXU9G7Z/Ug
CTHQunmMNWxMRQM+oZaxApv7F6ktUkj7nEz7P+a9ATRZNRA+71GtKecCAwEAAQ==
-----END RSA PUBLIC KEY-----
This is my private.pem file:
-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: AES-256-CBC,D6F812707BED2D64ECE71D7FA6DDFF3F
OA7X9RmaQpV+LfIOctMR4j644NPBLAckrAVe+VXcWdIrKQDRkaH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5SFotCgDSd20yV8ysCAbIMPmtVZdeHIwmsElVnCnbNrDuwOGu
4slotnuzuDALvBjj1NH7veu8pH9yKWNTcCix+IALb6SygzJgXO7oFd/SpZS/juzb
4bqzE0uIx6fLcLoleL4ZzC5S7Y8V0S82RxBcqXabA1njSQeSTfTA7g83p2n3QoRJ
Ux3eRF7DjHrDQF4vY10Gd0m7yLoRQOv8ryjhNu4iyp/8p2A3yntoUE9dpBCxFs/c
+bSxxzYD9yYV4APXMmhhMGY9nLNuqiR8y5KGl3VR9y7/0Ay0zSqjsY/w4JfGU7w1
SSgJIUKpoEzKfC7ihhq1Vb/O0ER+OYOAa5JQq03DNg0HrMDy6KpTua1lmGZHDwt2
9weI++KXD4IuLSK3bgYjgl169m7mrlYqOaPItQ2KOjb827P2F8SUrEUm8L5pvbu0
v0u46GAryNTkNv6Wxojuy50FnDPJrMVA+dl3ks0HemzBG4UzadbZiqC9Xn6Fj+/s
VVEr6BEL8s6duZI+USm+seKwFftUysAeu3lzf3y7irSQOqUEsC/lHGAvQqZsDSKO
1ypbf+YYFdBRzOY1iGKXcXjEXQQApKhciizL/35W+/JaIVppqS41/Z3DANXDm8cO
mHujAqj8wI3nrPBK9yjLUE/PmkpizxJq0YkCL040BvbOVp85rcl7hJXDqlCw1QE5
Ml2sVEJTkTBaZZIg9Sw5wIfgfwLADqTxuaICj5TXZ4dVjnU1pCfTdEhUiSqWlXRu
OsR2uC1yJOtW7c2Gc/7tCfQNJ041RdyTJ0aPgd+lsUbzR+NFtHqB/2jwBVYMGxjY
TkrxJZkd+u8vX2Ihw1heVwUvfKoVQCd1+MBwG/8nYe9SLSdHPNvZhuNtIsciQAUC
UMe++BUxA/KAQlRA7rUcclrgIj9ZEpSwD1S/S9leJ/KRW+5ZsSO6UCb+Io+KMRmV
-----END RSA PRIVATE KEY-----
Update:
Managed to solve it by adding the padding type param in Node.js
function decrypt(toDecrypt, relativeOrAbsolutePathtoPrivateKey) {
const absolutePath = path.resolve(relativeOrAbsolutePathtoPrivateKey)
const privateKey = fs.readFileSync(absolutePath, 'utf8')
const buffer = Buffer.from(toDecrypt, 'base64')
const decrypted = crypto.privateDecrypt(
{
key: privateKey.toString(),
passphrase: '',
padding:crypto.constants.RSA_PKCS1_PADDING
},
buffer,
)
return decrypted.toString('utf8')
}
I am trying to sign data using Blackberry cryptography but generated signature is not getting verify by the server side(PHP)
I tried this -
RSACryptoSystem rsaCryptoSystem = new RSACryptoSystem(1024);
// Create an RSA key pair.
RSAKeyPair rsaKeyPair = new RSAKeyPair( rsaCryptoSystem );
// Create the necessary RSA key pair for signing and verifying.
RSACryptoSystem cryptoSystem = new RSACryptoSystem(1024);
RSAKeyPair keyPair = new RSAKeyPair( cryptoSystem );
// Create the digest and the salt value.
SHA1Digest digest = new SHA1Digest();
byte[] salt = RandomSource.getBytes( digest.getDigestLength() );
// Create the RSASignatureSigner passing in a digest algorithm
// and PSS signature formatter.
PSSSignatureSigner signer =
new PSSSignatureSigner( rsaKeyPair.getRSAPrivateKey(), digest, salt );
signer.update( stringToSign.getBytes() );
// Encode the signature using X509.
EncodedSignature encSignature = SignatureEncoder.encode( signer,"X509" );
String signedIdentifier = Base64.encode(encSignature.getEncodedSignature());
Please help
Change your code with
byte[] dataBytes = stringToSign.getBytes();
PKCS1SignatureSigner signer = new PKCS1SignatureSigner(rsaKeyPair.getRSAPrivateKey());
signer.update(dataBytes, 0, dataBytes.length);
byte[] signatureBytes = new byte[signer.getLength()];
signer.sign(signatureBytes, 0);
String signedIdentifier = Base64.encode(signatureBytes);
I am trying to generate a JWT in Apex on Force.com but keep getting a 400 "error" : "invalid_grant". I've tried numerous variations, but just can't get a valid response. My clientEmailAddress is correct (eg ###developer.gserviceaccount.com). I extracted the value of my Private Key using openSSL. I wrote a method to base64URL encode based on other posts on the board. Any help would be greatly appreciated.
public static String base64URLencode(Blob input){
String output = encodingUtil.base64Encode(input);
output = output.replace('+', '-');
output = output.replace('/', '_');
while ( output.endsWith('=')){
output = output.subString(0,output.length()-1);
}
return output;
}
public static void generateJWT(){
Long rightNow = (dateTime.now().getTime()/1000)+1;
JSONGenerator gen = JSON.createGenerator(false);
gen.writeStartObject();
gen.writeStringField('iss',clientEmailAddress);
gen.writeStringField('scope','https:\\/\\/www.googleapis.com\\/auth\\/prediction');
gen.writeStringField('aud','https:\\/\\/accounts.google.com\\/o\\/oauth2\\/token');
gen.writeNumberField('exp',rightNow+300);
gen.writeNumberField('iat',rightNow);
String claimSet = gen.getAsString().trim();
String header = '{"alg":"RS256","typ":"JWT"}';
String signatureInput = base64URLencode(blob.valueOf(header))+'.'+base64URLencode(blob.valueOf(claimSet));
Blob signature = crypto.sign('RSA', blob.valueOf(signatureInput), encodingUtil.base64decode(privatekey));
String jwt = signatureInput+'.'+base64URLencode(signature);
http h = new http();
httpRequest req = new httpRequest();
req.setHeader('Content-Type','application/x-www-form-urlencoded');
req.setMethod('POST');
req.setBody('grant_type='+encodingUtil.urlEncode('urn:ietf:params:oauth:grant-type:jwt-bearer','UTF-8')+'&assertion='+encodingUtil.urlEncode(jwt,'UTF-8'));
req.setEndpoint('https://accounts.google.com/o/oauth2/token');
httpResponse res = h.send(req);
}
I think the method name is Base64encode but not base64urlencode