JavaScript save JSON response to other file extension with nice format - javascript

I've written some code to generate CSR as well as the private key.
The response to <textarea> is formatted nicely with a newline (if you know what the proper CSR/Private key looks like).
I have a problem with saving the private key to .pfx file type, where it will not be formatted nicely.
Here's how it looks like in the browser when placed into a <textarea>:
-----BEGIN PRIVATE KEY-----
MIIEowIBAAKCAQEAsUM5i1BX1NWS1CGsou86LN3oRcfkA63FdqneDLi36602dxQO
pSPabp8lqR+LgIWq/nIxShbZgc5YwlmhylrqYm1jdHXUQlNhBjsJE6Y0SwybXD9k
ERyWgFfaFLeUjUTXax01/M9oh4JQ+o4pWz+cw3oUjklH5iviLx34bZMq0k5azLus
312FRgA1x2AKG4QWUwTijTISYZ4mtLDTli2iqWVvPpLi87hLKTAMmLdJZ8hJkXOJ
QYRALpiERwX4lhckh1xnr/NfzE+QY0zxGwmvE4Uk0MqT7liUfqPnXiMLIIGuC/pt
xf2SXQBv/A9eus2jI0gM627iyvbDdkw0E1B+5QIDAQABAoIBAQCjpZM/aSnc5FsM
GhZ9yWsktqzTlymKt+dfmIzVo8av/hYVMuAeVw42KBilnOi1+zEUfKnCY3vkGXLZ
4dO6s9pEigZSIuGVZdJh5SiJClymmHnpXOBt572NuQ0tKRosnUxep/YKchRnXciS
t6G4iu6XjGHjxgVpmkPTCdEqn73drkf4jeQQrXWJQeOFH3b0e7XwvkoBKrjn6Tu3
uUURrNmeZRQnCGaj51wn8KYejCS7ReL071MdhwgJesCJzTpZFJ+HpLJSZI8FJQpd
pzX8rZ+4UfXMd1bcSaLMpgRZJrzGLx5uugO2sgTFelF6rzcg+yD+/JOETzSE3Am1
L5TA7MA1AoGBAPsxFTGAwg3Vvwg2xrSBAaUu2Vu8R3mvCRp2fjX1Q9CUM5vJpkqH
8h1xX3miVsGF//+W0yoSzVxcoPEALre5kiEQrmKYtXCaL6b4JY3BHJrUl4yIh0iO
1luFitq/T4R2flmshESd4SolqvdrpTVg3vryj9v9X75sIFlssdV3slZDAoGBALSn
3coa/8Dha5v+qBnWkHZcVGe/q9OOGJWloAbgI/S9TjcKqwe5u+EtvS2S3MurDbE6
uUBC85wCqjDelc36mn84f0YXDDy6vtZp0HoErGL7/wXL5zn52iRmVvF31vU1ahcK
2TT62MYQ8aCr7nNczvG8iF43hbfCd5c5yWDekwe3AoGAQ6REAMCbgP4+IwgdGh5j
QwgKoBljZfEskmO2OPGDAXfnLdxvW0KggC03eJmuow5ikYEb/Ah0JJsM+9kAu5jN
MPo8+3AD6/6ZNm08L6ABA/CbnsxlIbTVJHAhpCZAU3tVKvC57YBWUfMyxs3F/0nG
wezvsF3amnyjeXE7sjA5ZeECgYBzsendTCssaHEVByK64WnFE15OzzaIlsDx3Y89
t//u9emIYIGlwfIrxLIZ5KsYmCR9syD+oaIH8MDz6SjBMFQPU6xWw93naqVbBYsp
CaMpBT+Og8ZCn9tvYkcd/2SfxyR5O05dmqSHPESyZEmigfZaZCZlSGOPirAyHiT0
r7YzwwKBgAQSh1wgnlOaadkKHzItrXf9i9dUaAzuUYj/B/EpZR+y5ckXFuohpczE
rQ4yJIgvynxKJW7r2AVS0ad/fbgh5YNCaykB8HDhP1ZQY8ng1ae6VoHRQiLZAdKx
cAqWIvwWEjAFFbHixt4d3OChDlubpeB3p24MlWycc1H63L4RKAto
-----END PRIVATE KEY-----
How it looks like in the file:
"-----BEGIN PRIVATE KEY-----\nMIIEowIBAAKCAQEAsUM5i1BX1NWS1CGsou86LN3oRcfkA63FdqneDLi36602dxQO\npSPabp8lqR+LgIWq/nIxShbZgc5YwlmhylrqYm1jdHXUQlNhBjsJE6Y0SwybXD9k\nERyWgFfaFLeUjUTXax01/M9oh4JQ+o4pWz+cw3oUjklH5iviLx34bZMq0k5azLus\n312FRgA1x2AKG4QWUwTijTISYZ4mtLDTli2iqWVvPpLi87hLKTAMmLdJZ8hJkXOJ\nQYRALpiERwX4lhckh1xnr/NfzE+QY0zxGwmvE4Uk0MqT7liUfqPnXiMLIIGuC/pt\nxf2SXQBv/A9eus2jI0gM627iyvbDdkw0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r7YzwwKBgAQSh1wgnlOaadkKHzItrXf9i9dUaAzuUYj/B/EpZR+y5ckXFuohpczE\nrQ4yJIgvynxKJW7r2AVS0ad/fbgh5YNCaykB8HDhP1ZQY8ng1ae6VoHRQiLZAdKx\ncAqWIvwWEjAFFbHixt4d3OChDlubpeB3p24MlWycc1H63L4RKAto\n-----END PRIVATE KEY-----"
My CSR code:
var csrResult = (JSON.parse(csr))
var csrResultResdata = JSON.parse(csrResult["resdata"]["csrgen"]["context"])
var csrResultResdataCSR = csrResultResdata["csr"]
var csrSpliter = csrResultResdataCSR.split("\n\n")
var csrOnly = csrSpliter[0]
var privateKeyOnly = csrSpliter[1]
var exportName = "private_key"
downloadObjectAsJson(privateKeyOnly, exportName)
My save as file code:
function downloadObjectAsJson(exportObj, exportName){
var dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(exportObj));
var downloadAnchorNode = document.createElement('a');
downloadAnchorNode.setAttribute("href", dataStr);
downloadAnchorNode.setAttribute("download", exportName + ".pfx");
downloadAnchorNode.click();
downloadAnchorNode.remove();
}
I need help on format the file content.
The original response from API is:
{
"result": {
"code": "0",
"msg": "Command completed successfully"
},
"resdata": {
"csrgen": {
"context": "{\"csr\":\"-----BEGIN NEW CERTIFICATE REQUEST-----\\nMIICtjCCAZ4CAQAwcTELMAkGA1UEBhMCTVkxETAPBgNVBAgTCFNlbGFuZ29yMRUw\\nEwYDVQQHEwxQdWNob25nIEpheWExDzANBgNVBAoMBuerpeWNqzEPMA0GA1UECwwG\\n56ul5Y2rMRYwFAYDVQQDEw1hYmMudGt0YW4uY29tMIIBIjANBgkqhkiG9w0BAQEF\\nAAOCAQ8AMIIBCgKCAQEAj3SON7mz0TZwFHAfy/m3vKICH2BjaZdWJWi7ZPLo2uYC\\n6070cU7hd5iM8+q7VEYSUJb8XisuGpKSakx0xWXuXkJfrciR9P5dypEWAUle3e+z\\nHaQMhu9eJu7W0do96f8WLJoy/T1jYIF6p2hhwRy368FrUtWGJQ+6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nSWxOg\\ncVhmamk/w1L67RtzwJ69S6sTECwfnHDlOBLJwCTtVzGTfHZQ1QBctNnyZ1sHUetd\\nwX5QuEO1vsI/T7jpozg0PGr+5BE5r1kr6VjvPBe+WOhO/4X1wUFt\\n-----END PRIVATE KEY-----\",\"status\":\"Success\"}"
}
}
}

Why are you storing your PFX file as JSON formatted? Just remove the JSON.stringify and output it as plain text, seeing as what you're passing in is just a basic string anyway. All that stringify does is wrap it in quote marks and encode the newlines.
var dataStr = "data:text/plain;charset=utf-8," + exportObj;
Here is a JSbin of it working correctly: http://jsbin.com/lipaxuhidi/edit?html,js,output

Related

TripleDES Java Encryprion to Javascript Decryption

I am using Java to encrypt a text payload with Triple DES. First I create an ephemeral key that I will use for encrypting the payload:
private byte[] createEphemeralKey() throws Exception {
KeyGenerator keygen = KeyGenerator.getInstance("DESede");
keygen.init(168);
return keygen.generateKey().getEncoded();
}
Then I encrypt my payload with said key:
private String encryptTripleDES(byte[] ephemeralKey, String payload) throws Exception {
Cipher cipher = Cipher.getInstance("DESede/ECB/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(ephemeralKey, "DESede"));
byte[] plainTextBytes = payload.getBytes();
byte[] cipherText = cipher.doFinal(plainTextBytes);
return Base64.getEncoder().encodeToString(cipherText);
}
Also need a padding function to ensure the data length is divisable by 8:
private String adjustPadding(String input, int blockSize) {
int len = input.length() % blockSize;
int paddingLength = (len == 0) ? 0 : (blockSize - len);
while (paddingLength > 0) {
input += "F";
paddingLength--;
}
return input;
}
And here is my process end to end:
String data = "Marnus"
byte[] = ephemeralKey = createEphemeralKey();
String adjustedData = adjustPadding (data,8);
String encryptedPayload = encryptTripleDES(ephemeralKey, adjustedData);
String encodedKey = Base64.getEncoder().encodeToString(ephemeralKey)
So I take the 2 variables encryptedPayload and encodedKey, that are both Base64 encoded string, and send it off via HTTP to node express app.
In the Javascript side of things, I use node-forge - Here is the part of my express app that does the decryption:
let nodeBuffer = Buffer.from(data, 'base64')
let input = forge.util.createBuffer(nodeBuffer.toString('binary'))
// 3DES key and IV sizes
let keySize = 24;
let ivSize = 8;
let derivedBytes = forge.pbe.opensslDeriveBytes(ephemeralKey, null, keySize + ivSize);
let buffer = forge.util.createBuffer(derivedBytes);
let key = buffer.getBytes(keySize)
let iv = buffer.getBytes(ivSize)
let decipher = forge.cipher.createDecipher('3DES-ECB', key)
decipher.start({iv: iv})
decipher.update(input)
console.log('decipher result', decipher.finish())
let decryptedResult = decipher.output.data;
Here is an Triples DES example in the node-forge docs:
A few notes:
I create a node-forge buffer from a regular buffer since I don't have a input file like the examples gives. Here is how the docs states one should create one buffer from the other:
*I use base64 as that is what I used in the java side to encode the data that was sent.
Then, I dont have a salt so I left the 2'nd param null in opensslDeriveBytes as specified in the docs I should do.
Thirdly, I am also not sure if my keysize of 24 is correct?
My results
So doing an end to end test yields the following:
In my Java app, the test data was "Marnus", the encryptedPayload was ez+RweSAd+4= and the encodedKey was vCD9mBnWHPEBiQ0BGv7gc6GUCOoBgLCu.
Then in my javascript code data was obviously ez+RweSAd+4=(encryptedPayload) and the ephemeralKey was vCD9mBnWHPEBiQ0BGv7gc6GUCOoBgLCu(encodedKey).
After the decryption ran, the value of decryptedResult was ©ýÕ?µ{', which is obviously just garbage since it was not encoded yet, but I cant figure out which encoding to use?
I tried using forge.util.encode64(decipher.output.data), but that just gave me qf3VP7UYeyc=, which is not right.
For what it's worth, here is the type that decipher.output
With a lot more tweaking and testing different options, I got it working - and the good news is I managed to get it all working with the built in crypto library in nodejs (v12.18.4).
First things first, the JAVA side just needs a change to the key size (from 168 to 112), the rest remains the same - see below example as one single method (should be split up in final implementation of course for testability and usability):
//Some data:
String payload = "{\"data\":\"somedata\"}";
// Create Key
KeyGenerator keygen = KeyGenerator.getInstance("DESede");
keygen.init(112);
byte[] ephemeralKey = keygen.generateKey().getEncoded();
// Adjust the data, see adjustPadding method in the question for details.
String data = adjustPadding (payload,8);
// Wil now be "{"data":"somedata"}FFFFF", can just chop off extra in JS if need be. When sending JSON one knows the end of the object will always be "}"
// Do Encrypt
Cipher cipher = Cipher.getInstance("DESede/ECB/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(ephemeralKey, "DESede"));
byte[] plainTextBytes = data.getBytes();
byte[] cipherText = cipher.doFinal(plainTextBytes);
String encryptedPayload = Base64.getEncoder().encodeToString(cipherText);
//Lastly, Base64 the key so you can transport it too
String encodedKey = Base64.getEncoder().encodeToString(ephemeralKey)
on the Javascript side of things we keep it simple:
// I'm using TS, so change the import if you do plain JS
import crypto = require('crypto')
//need bytes from the base64 payload
let buff = Buffer.from(ephemeralKey, 'base64')
const decipher = crypto.createDecipheriv('des-ede3', buff, null)
decipher.setAutoPadding(false)
let decrypted = decipher.update(data, 'base64', 'utf8')
decrypted += decipher.final('utf8')
console.log(decrypted)
//{"data":"somedata"}FFFFF"

python decrypt a text encrypted in jsencrypt

In a web form the answers (packed in a jsonstring) are encrypted in several steps. First a random key is generated. Second the random key is used for AES encryption of the jsonstring. The random key is encrypted as well. Both are send in the body of a mail.
// Generate Random key
var rand_key = ('0000' + Math.random().toString(36).replace('.', '')).substr(-10);
console.log('rand_key', rand_key)
//var pubkey = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBALDjeFwFNhMCjMwcRVVKG1VvfsntEVPR3lNTujJnNk1+iSqZ4Tl5Lwq9GbwO+qlYVwXHNmeqG7rkEhL9uyDIZVECAwEAAQ=="
// rsa_key_public07012016.bin
//var pubkey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCv8FVei4Q2ehmYsSCv/uODSojIOGHwfQe686S1cEH5i/1mGME5ZzNqyy0d+lhMRD0tr7Sje7JoCEC/XRIZaiKJjpl1+3RXotf/Cx3bd9H7WtitshZB1m38ZZFsrX4oigMpUPFbCefMeBS4hvvNnmtl08lQGhfIXdXeflZsgWRHtQIDAQAB";
// my_pub_key.pem
var pubkey ="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA38gtENP9/hpirSCIsPh6CAVm0UmME4XBlPyK8yhwk079EUJpNzlEhu9HKcA/B7Fxo2lNoY9Tb9e+PYtJ6+VOB4+Y6zgGMX7cchYmumKRTbbQ6FNfBE5Q8XnOAUlgC7gNrs0e5lW7JH1kWlK+eTT4TANT7F3US09aXmym+fZaRInbXmJujGnDIbRIIbzr5FE82EeMpw2TqRWV466wz5EeFWSSQ8EqV1pSox8B1ywb6cnB/Vofs2qR9Zf2efi9TMcSGm/ij/p9IZcbLeep9qfGsv29lbLNMfwNwQyH0JU27eAM4tPdirceZPxfD6iiILmKzN253BMoAeQCp6us53CnGQIDAQAB"
// Make form_data a JSON string
var jsonstring = JSON.stringify(form_data);
// Create AES encrypted object
var aes_encrypted_json = CryptoJS.AES.encrypt(jsonstring, rand_key);
// Encrypt rand_key
var encrypt = new JSEncrypt();
//console.log('encrypt obj', encrypt);
encrypt.setPublicKey(pubkey);
var encrypted_rand_key = encrypt.encrypt(rand_key);
//var encrypted = encrypt.encrypt(jsonstring);
console.log('encypted', encrypted_rand_key);
var mail_body = encrypted_rand_key + aes_encrypted_json
console.log('body', mail_body)
var mailto_string = "mailto:info#xyz.com?subject=FORM&body=" + encodeURIComponent(mail_body);
$('#mailtosend').attr('href', mailto_string);
At the recipient mail server side I want to decrypt the random generated key and the jsonstring using a private key using the pycryptodome package.
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
from base64 import *
def decrypt(key, text):
if type(key) == str:
key = key.encode()
if type(text) == str:
text = text.encode()
rsakey = RSA.importKey(key)
rsakey = PKCS1_v1_5.new(rsakey)
d = rsakey.decrypt(text, 'bolloux')
return d
# rand_key am2mhiwwmi
text = "ZvcrluUmZLY3lRRw01W9mQnhMn7zzpIWn1Bo3csM/ZZ0pWY/8H2dCB9fZDi9/cmp0UtIqDXhLd7SIwyxqrFgPcHUuEHlZl0WQcjSty8PjadG2Abulk1XqEQV4u0Gb/bFGDBMcf5tV1G0d4FFcBPE8r8inrxUjSj2CSffVL8gIGq3ZfY5g7t5FOZV8npBCEONgOLKYnzIiHrHUuXWsOaMAqxMFOLd5DTDLKAkyMybDClsLW9ka+CvWd5fnZBCvO2ziehFp7b9PG4QPSnQpdC8jNLGZB2h0FI8YQD6IyUwmVluUbAlPMqwd6A2CBdGCbfbMChaA5R7bJgKkYhPOQTjaQ=="
text = b64decode(text.encode())
with open('my_priv_key.pem', 'rb') as f:
key = f.read()
decrypt(key, text)
I run into a encoding problem. "UnicodeDecodeError: 'ascii' codec can't decode byte 0xf7 in position 1: ordinal not in range(128)" The encoding is complicating the issue beyond my capabilities.
My questions:
1. How can I resolve the encoding problem ?
2. How can I make the decryption work ?
Thanks
The issue is more than likely caused by b64decode(text) returning a str that contains values such as \xf7 and then attempting to .encode() those values within your decrypt function. encode will use the default encoding which in this case is ascii. I would personally remove the calls to encode unless you specifically have a reason you are doing so.

Progressive HMAC SHA256 in Objective-C

I need to generate a hash using HMAC SHA256. I am using the following code in JavaScript. I need an equivalent code in Objective-C.
function serialize( obj ) {
return Object.keys(obj).reduce(function(a,k){a.push(k+'='+encodeURIComponent(obj[k]));return a},[]).join('&')
}
var query = {
Action : 'MyAction',
SignatureMethod : 'HmacSHA256',
};
var hmac = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, 'MYVALUE');
var queryString = ['POST', 'm.service.it', '/api/v2', serialize(sorted)].join('\n');
hmac.update(queryString);
query.Signature = CryptoJS.enc.Base64.stringify(hmac.finalize());
How implement this in Objective-C?
HMAC-SHA256 sample code:
+ (NSData *)hmacSha256:(NSData *)dataIn
key:(NSData *)key
{
NSMutableData *macOut = [NSMutableData dataWithLength:CC_SHA256_DIGEST_LENGTH];
CCHmac( kCCHmacAlgSHA256,
key.bytes,
key.length,
dataIn.bytes,
dataIn.length,
macOut.mutableBytes);
return macOut;
}
Notes:
Add Security.framework to the project
Common Crypto must be included:
#import <CommonCrypto/CommonCrypto.h>
This is data in and out, add any conversions to desired representations before and after.
Conversions could be string to data on input and data to Base64 on output:
NSData *data = [#"string" dataUsingEncoding:NSUTF8StringEncoding];
NSString *string = [data base64EncodedStringWithOptions:0];

Sign Key HMAC SHA1 with Javascript

For some reason I am not able to create a signature from a private key in JS. Using this online help from google:
https://m4b-url-signer.appspot.com/
URL:https://google.maps.com/maps/api/geocode/json?address=New+York&client=test
Example Key (fake for the purposes of the exercise)
Key: QNade5DtdJKKZbidTsrIgONupc4=
(Result) Signature: XDsiH5JAY7kJLgA1K2PWlhTdO1k=
However, my javascript code:
var keyString = 'QNade5DtdJKKZbidTsrIgONupc4=';
console.log(keyString)
var urlString = encodeURIComponent('/maps/api/geocode/json?address=New+York&client=test');
console.log(urlString)
// We need to decode private key to binary
var decoded_key_words = CryptoJS.enc.Utf8.parse(keyString);
var decoded_key = CryptoJS.enc.Base64.stringify(decoded_key_words);
console.log(decoded_key);
var signature = CryptoJS.HmacSHA1(decoded_key,urlString);
console.log(signature);
// Encode binary signature to base 64
var encoded_signature = CryptoJS.enc.Base64.stringify(signature);
console.log(encoded_signature)
Gives me a signature:
bOenVNeXI6xI1xlSa77oqGKssyY=
I can't seem to figure out what I'm doing wrong. Am I decoding base64 incorrectly?
For the record, this worked:
<script src="sha.js"></script>
var url = '/maps/api/geocode/json?address=New+York&client=test';
var key = 'QNade5DtdJKKZbidTsrIgONupc4='
var hmacObj = new jsSHA(url, 'TEXT');
var hmacOutput = hmacObj.getHMAC(key,'B64','SHA-1','B64');
console.log(hmacOutput)
Giving me:
XDsiH5JAY7kJLgA1K2PWlhTdO1k=

Data Encryption using RSA in javascript

I am using RSA Encryption using JSBN
When I write following code, I am getting error - " 'null' is not an object (evaluating 'this.n.bitLength')" on 92th line(var m = pkcs1pad2(text,(this.n.bitLength()+7)>>3);) in rsa.js file - http://www-cs-students.stanford.edu/~tjw/jsbn/rsa.js
var rsa = new RSAKey();
var pk = "----BEGIN PUBLIC KEY----\r\n"+
"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCqGKukO1De7zhZj6+H0qtjTkVxwTCpvKe4eCZ0\r\n"+
"FPqri0cb2JZfXJ/DgYSF6vUpwmJG8wVQZKjeGcjDOL5UlsuusFncCzWBQ7RKNUSesmQRMSGkVb1/\r\n"+
"3j+skZ6UtW+5u09lHNsj6tQ51s1SPrCBkedbNf0Tp0GbMJDyR4e9T04ZZwIDAQAB\r\n"+
"----END PUBLIC KEY----";
rsa.setPublic(pk);
var data = rsa.encrypt('hello world');
List of files included :
jsbn.js,
prng4.js,
rng.js,
rsa.js

Categories

Resources