SHA1 varies in java and javascript for same input - javascript

Facing an issue while creating SHA1 from javascript and java. The problem is both are different. It is used for validating the client request to web server. That means client send a based64 encoded security key to server and server regenerate the same key and equate both are same. Please find below code for generating secret keys in client and server.
Server
MessageDigest mDigest = null;
try {
mDigest = MessageDigest.getInstance("SHA1");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
String input = value1 + value1 + server_key;
byte[] result = mDigest.digest(input.getBytes());
String secret = Base64.encodeToString(result, Base64.NO_WRAP);
...
//comparison logic goes here
...
Client (java script)
var input = value1 + value2 + server_key;
//http://code.google.com/p/crypto-js/
var hash = CryptoJS.SHA1(input);
var encoded = base64Encode(hash.toString());
//WEB SERVICE INVOCATION FROM JAVASCRIPT GIES HERE.
The values value1, value1, server_key will be available in both client and server. The issue we are facing is, the SHA1 generated in both client and server is not matching. I understand the issue is in java its using getBytes() and in javascript using string value for generating SHA1. The CryptoJS.SHA1 does not support bytearray as parameter. We cannot change the server code as it is used by many client applications. Any help will be much appreciated.
In Java ->
byte[] result = mDigest.digest(input.getBytes());
and in JavaScript ->
var hash = CryptoJS.SHA1(input);.
I belief this is the problem. In java the parameter is a bytearray and output is also a bytearray. But in javascript the parameter is var (string) and return is also var (string). I 've also compared the output of CryptoJS.SHA1 with some online SHA1 generating tools. The comparison is true. I am not an expert in this area. If you can explain more, it will be more helpful.

I managed it to do in another way. My application is a cordova based application. So generated the sha1 and encoded it from java and objC and invoked it using cordova plugins.

Related

Decrypting OAEP RSA In JavaScript (Like PHP's openssl_private_decrypt)

I'm currently encrypting data in PHP as follows:
//$sMessage is the input to encrypt.
//$sPublicKey is the public key in PEM format.
openssl_public_encrypt($sMessage, $sEncrypted, $PublicKey, OPENSSL_PKCS1_OAEP_PADDING);
//$sEncrypted will now store the resulting text.
Here's an example of the code used to generate the key in PHP:
$aConfig = array(
"digest_alg" => "sha256",
"private_key_bits" => 4096,
"private_key_type" => OPENSSL_KEYTYPE_RSA,
);
$res = openssl_pkey_new($aConfig);
//$sPassPhrase is the pass phrase.
openssl_pkey_export($res, $sPrivateKey, $sPassPhrase);
//$sPrivateKey is the key (in PEM format).
And my decryption is using a private key that's protected by a pass phrase.
//$sPrivateKeyWithPassPhrase is the protected private key in PEM format.
//$sPassPhrase is the pass phrase to protect the key.
$newRes = openssl_pkey_get_private($sPrivateKeyWithPassPhrase, $sPassPhrase);
//$sEncrypted is the encrypted text (ciphertext).
openssl_private_decrypt($sEncrypted, $sDecrypted, $newRes, OPENSSL_PKCS1_OAEP_PADDING);
//$sDecrypted is the decrypted text (plaintext)
I've also found out how to decrypt with Python using the cryptography library (which you can learn about here):
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
#passphrase is the pass phrase
passphrase_bytes = bytes(passphrase, 'utf-8')
#privatekey is the encrypted private key
private_key = serialization.load_pem_private_key(
privatekey,
password=passphrase_bytes,
)
#ciphertext is the text to be decrypted
plaintext = private_key.decrypt(
ciphertext,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA1()),
algorithm=hashes.SHA1(),
label=None
)
)
#plaintext will be the decrypted result.
However, I've been struggling to find a comparable function in JavaScript.
The best answer I found so far was this one: RSA Encryption Javascript
However, it doesn't seem like keys are in PEM format and when I go to the pidCrypt homepage to get more documentation, it's a 404 error.
I found this one as well: PHP's openssl_sign Equivalent in Node JS
The NodeJS library in general seems to have the right functions but when I went through the NodeJS documentation the Quick Start Guide seems to suggest that in order to use NodeJS I have to first install software and set up a web server. According to how to run node.js client on browser, it's not possible "Node.js is not browser javascript. There are many parts of it that use OS features not available in a browser context." (I'm hoping for something I can run in a native browser on the client-side.)
Someone suggested in a comment that I could use WebCrypto. After some struggle to figure out where to download it, I found it's actually native to the browsers (which was a pleasant surprise). However, I haven't been able to figure out how to import a PEM key from the documentation, and when I went to generate a key then export it, the only available formats were "jwk" (some sort of JavaScript object), "spki" (some kind of array buffer), and "pkcs8" (which I only got DOMException: key is not extractable). Nothing looks remotely like the OpenSSL PEM format. (I believe this is PKCS1.)
When I did "crypto.subtle.importKey" it wanted 5 different parameters (format, keyData, algorithm, extractable, keyUsages). None of those accept the PEM string. After a bit of struggle I did find SubtleCrypto importKey from PEM which confirmed that it's possible if you do fancy manipulation to import a PEM public key, however that's for public keys in PEM format and I have no idea how to handle pass phrases (and really I'd rather not program that all by hand). Then I found How can I import an RSA private key in PEM format for use with WebCrypto? and Javascript, crypto.subtle : how to import RSA private key? however those basically told me it's not possible unless I go and convert the private key to PKCS8 using a command line OpenSSL (that also has to be installed separately and I remember was a huge pain to get on Windows). And once I get past that hurdle, I'm still not sure how I would go about getting an equivalent pass phrase protection in PKCS8. I'm hoping there's something similar that ideally supports PKCS1 to do the same as the PHP and Python code above, and I can run it 100% in the native browser. (Importing more JavaScript code is okay.)
I'd ideally like to find a simple working JavaScript example for OpenSSL RSA decryption, equivalent to the PHP or Python ones above. If I have the private key PEM string, the pass phrase, and the cipher text it can give back the plaintext.
Thank you very much! I appreciate all your help a ton and you can save me many hours!
PKCS#1 Versus PKCS#8
Note that while private keys generated without pass phrases in PHP are PKCS#1, the private key generated from PHP with a pass phrase is actually PKCS#8 (see this link for how to determine which standard applies to a private key).
Third Party Library Required
In order to work with PEM-format keys, a custom JavaScript library (or other custom code) is required. There are various libraries at this link which you can look at. Many are not maintained anymore.
This example uses the Forge JavaScript library, but you could also use a different library.
Installing/Importing Forge
While there are various ways to build the Forge environment, the easiest is to add the following HTML code prior to where you need to do encryption/decryption:
<script src="https://cdn.jsdelivr.net/npm/node-forge#0.7.0/dist/forge.min.js"></script>
Performing RSA Decryption
The following JavaScript code will perform decryption using the Forge library with a private key that's passphrase-protected:
// Import an PKCS#8 encrypted key from PHP
//sEncPkcs8Pem = The encrypted PEM key in a string.
//sPassPhrase = A pass phrase string to use for decryption.
//bCipherText = The encrypted cipher text (string of bytes).
var encryptedPrivateKeyInfo = forge.pki.encryptedPrivateKeyFromPem(sEncPkcs8Pem);
var privateKeyInfo = forge.pki.decryptPrivateKeyInfo(encryptedPrivateKeyInfo, sPassPhrase);
var pkcs8Pem = forge.pki.privateKeyInfoToPem(privateKeyInfo);
var privateKey = forge.pki.privateKeyFromPem(pkcs8Pem);
var sDecrypted = privateKey.decrypt(bCipherText, 'RSA-OAEP');
//sDecrypted will store the result.
Full Working Example
The following is a full working example with a 4096-bit key. The JavaScript imports an encrypted private key (PKCS#8 format, PEM encoded) and successfully decrypts a ciphertext.
The encrypted key and ciphertext were both generated using the posted PHP code.
The JavaScript library applied is forge.
<script src="https://cdn.jsdelivr.net/npm/node-forge#0.7.0/dist/forge.min.js"></script>
<p style="font-family:'Courier New', monospace;" id="pt"></p>
<script>
var encPkcs8Pem = `-----BEGIN ENCRYPTED PRIVATE KEY-----
MIIJnDBOBgkqhkiG9w0BBQ0wQTApBgkqhkiG9w0BBQwwHAQIxjk2j/jhKPECAggA
MAwGCCqGSIb3DQIJBQAwFAYIKoZIhvcNAwcECMWHokN4f1pIBIIJSGsi3CbrV4Uf
QL70dh+nKI0+PbSKlpx4CJZVARiTonO26+YathAgo/F6TKY+MZAfctuAg38EDo6u
zyjPxkrz8Ha1rIhBioFg4Tyem4s/16F4dVw9D4+dy/ORCk7PvbCg++lCCt3lVAqF
Q+zX8X9ygXza+PyHlJzAi6o2MQsoxC37cBvhLmPGSbVFPBAhSmfsWqct7StMp872
jIk/2x1xt0gZlSIayefLUEc/OP1sBXoBeFEFF3nxZrpMaCixElEyMKWHaQPDberm
gkbuvwCmwC/rFCO4BG4GLcgWzQ8msYBIE0wS+QoLzBqE+RrAXPgTpFto2/S/SZ2U
2zRiyXtDG6AK0yBBj9IJcSUHbNO7JvBsbxg9LO8Y+HxkwPQkQSF4CABsuFXeZ75a
eXs2AaptSmj5rjHHRoYKPB1Gsi7IkLa0q9otDCA2veDZRyh1OAhasZ382F3KQvGa
z8JQ0sahKLDUWdb9R0KVnEVurCnz4gutthMwXyfBJrAO9W9q0f3R40OOQvWxhTzX
cre04g8ihlYE39JdCWL09yctBXaDbG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fyO0mWU1LyELykwjsZ/9KdFDlvksI9vFJ7zI
PWIUpW7EOKdLTHunXZu6Dn59fQqJYLFVlf4FgJTT4/YshIS0Nu+MeS45HQY7G3Up
QHXJ2TjHXVHV4amajkCLhSgaP7C59i8L9f+spWCu5v/8KKx6XLLbO6izI8TpWPW/
7rAysCmd9uNTTzJtUQJoBVZ1r8p7xoQXtkegqyE5/zsldIzSeC8/yr+XaZ2CK7zo
NIdwzqjFtpkcvsCQT3xLmGvLWJM9Jai1Hpfuhaggl9z7lo/i2rTsSIJRPa1BrSnm
+ntlsNo3r+RSoI+Tmi1MKzz2p+X4rXlD0tfPGm/yzuBXx8mtbZVX5yBNEI2l+EwN
EqPR5qHuobYfK8aZ7juB+AHoVlrGM26Q1PghHOFPc1dZVm3K+fThl19t/jdVve6Q
6NKAggLjuyEU4f+MELA8fwq7/66wqfgWIcBdGpn0npI23nx24jlfiKmmacBrKAHM
ij9mm4GhutigIoP4Wx/NUA==
-----END ENCRYPTED PRIVATE KEY-----`; // 4096 bit key!
// Import an PKCS#8 encrypted key from PHP
var encryptedPrivateKeyInfo = forge.pki.encryptedPrivateKeyFromPem(encPkcs8Pem);
var privateKeyInfo = forge.pki.decryptPrivateKeyInfo(encryptedPrivateKeyInfo, prompt("Enter pass phrase", "testkey"));
var pkcs8Pem = forge.pki.privateKeyInfoToPem(privateKeyInfo);
var privateKey = forge.pki.privateKeyFromPem(pkcs8Pem);
// Decrypt ciphertext from PHP
var ciphertext = forge.util.decode64("lHIspL7aAlnbUdQn6VVY2AS3Ybs/H0fK7N4owfPe6OtzMmX88XOI+2FyEnNyCal6krnfdHYa2JWeWAsyLf484sT2BmvNPxWyYsrnpulKog0lhkeUFppGdhdOHCf7KU47L5p6uYtZmv926ACfhwqMo4M66n/Gkliocol+esavVcfZcjuAw+ELnYkx/TufinR772jBLxVWueGyGcEokI9osDCDpXptmJqpiNRzIrf2kHdk2F/bXRPyE+vrQKFzbyMSpBj3xKtsYDiJ5xDq0qtYY+GCRJNMucPFqOTiFN18EE3z8y/tq5n9Ae/VS8wMxn51rB5JBRmYg3vlM4JLolqNnP3t8OD+DqAeavYjAnairLV0esxzjdkUDpfmFrsYBZWfe5rMzO55drDdsQpGI9LGeX5/TUQpqJWBNZ7QXnbxEiQ2ATXH+ToaeZe3mMkPKuogKM2aEViLzdYB0plbQnoWPAG4OH9pYPGj1KYwdQG5UoF0Ew6Y93uSG3uJ6mcdZZ9gJA0+hpVHOchuAvtZ+vuIV4tzWGfvvnAND54U5sS95EGRj8w/ukgswgOfg/k9iKN3Xlh5N23BYyoLajZVN92cVw6I3XpNOWjlHcO04EhLXaxIeaEMsYYqq3GDBtxpbXfARVjokMeKkKUKNwVscpVneq6WXGtfiMGwXpF8MfoGigE=");
var decrypted = privateKey.decrypt(ciphertext, 'RSA-OAEP');
document.getElementById("pt").innerHTML = "Decrypted: " + decrypted;
</script>
Note: I'd like to give credit to Topaco for their considerable help and original answer, which this one is based off of.

Cryptographic key to JSON Web Key using javascript

I am a newbie in JavaScript or GatewayScript. I have a requirement where I need to convert the content of a .pem (which is in DataPower under local:///cert or can be added into a crypto object) to JWK.
Could anyone help me with the starting point on how to develop a javascript to
refer the crypto key object from DataPower (example crypto key
object JWKCryptoCertObj)
Decrypt the crypto key object (example
JWKCryptoCertObj.pem)
Convert the content of the key to JSON Web Key (jwk.readCertificate())
So far I have got to know that jwk.readCertificate() can help me to convert a key object to a JWK.
I have tried the below piece of code to fetch it:
var jwk = require('jwk');
var myJWK = jwk.readCertificate('cerjwk');
console.log(myJWK);
However, I get the below error in DataPower:
3:13:17 AM mpgw error 1277869681 error 0x00d30003 mpgw (PortTest): Rejected by filter; SOAP fault sent
3:13:17 AM multistep error 1277869681 request 0x80c00009 mpgw (PortTest): request PortTest_Policy_rule_1 #2 gatewayscript: Transforming the content of INPUT. The transformation local:///jwk.js is applied. The results are stored in testop. failed: Internal Error
3:13:17 AM gatewayscript error 1277869681 request 0x85800007 mpgw (PortTest): GatewayScript processing Error 'Error: Named certificate 'cerjwk' not found In file 'gatewayscript:///modules/jwk.js' line:428, stack:Error: Named certificate 'cerjwk' not found at Object.readCertificate (gatewayscript:///modules/jwk.js:428:18) at Object. (local:///jwk.js:5:17) at Script.execute (gatewayscript:///datapower.js:155:24) at Object. (gatewayscript:///datapower.js:582:55)'
3:13:17 AM crypto error 1277869681 request 0x8580005c mpgw (PortTest): Named certificate 'cerjwk' not found
Could anyone help me with the issue here? Thanks in advance!!
There is no need to convert the certificate. Just add it into a Crypto Key object and use the name (e.g. "crykey-my-key") of the object in the call, e.g.:
const jwk = require('jwk');
const myKeyJWK = jwk.readCertificate('crykey-my-key');
It finally worked, the thing that was needed to be changed was the cert, instead of the key.
Here is the working code:
var ctx = session.name('INPUT')|| session.createContext('INPUT');
var hm = require('header-metadata');
//var headers = hm.current;
var sm = require('service-metadata');
var uriIn=sm.getVar("var://service/URI");
var jwk = require('jwk');
var myJWK = jwk.readCertificate('qa.developer.citigroup.net');
//headers.set('X-new-header', myJWK);
//headers.set('Content-Type','application/json');
console.log(myJWK);
ctx.setVariable('yourjwk',myJWK);
session.output.write(myJWK);

Transferring strings containing emotions to server

On my website whenever a user enters a mobile emoji like 😀 into an input field it will be saved as ?? in my database.
Those emojis are encoded in utf8mb4, so I already updated my database collation to utf8mb4_general_ci.
While the emoticons can be saved successfully now when transfering the message containing a emoji from a client to my server, it still get's somewhere changed into ?? and I am now trying to figure out where and how to solve it.
Sending the message to my server happens in this ajax call:
function updateStatus() {
var status = $("#status").val();
jsRoutes.controllers.Userdata.updateStatus( status ).ajax({
success : function(data) {
$("#profil").cftoaster({content: data});
},
error : function(err) {
$("#profil").cftoaster({content: err.responseText});
}
});
}
On serverside I am using java based Play Framework 2.4.4.
This is the beginning of the method which is called in the ajax call:
public static Result updateStatus(String status) {
String receivedName = Application.getSessionUser();
Logger.debug("RecvStatus: " + status);
...
}
The Logger output already is ?? for an emoticon.
The route looks like this:
PUT /status/ controllers.Userdata.updateStatus(status: String)
EDIT:
To make sure the transfer from client to server is alright I am now transferring the actual unicode values, I change my server function like this
Logger.debug("RecvStatus: " + status);
status = status.replace("\\","");
String[] arr = status.split("u");
status = "";
for(int i = 1; i < arr.length; i++){
int hexVal = Integer.parseInt(arr[i], 16);
status += (char)hexVal;
}
Logger.debug("RecvStatus: " + status);
and get the following output:
[debug] application - RecvStatus: \ud83d\ude01
[debug] application - RecvStatus: ?
which means the problem is probably with java
So for anyone having a similiar problem here my workaround.
First I tried to convert the String in java to base64 and store it this way. Unfortunately after decoding the base64 the unicode information still got lost and ?? was shown instead of emoticons.
What I than did was converting the received String into unicode and than into base64, and when I load the Strings from the database I first decode base64 and then convert the unicode information into an actual String. This way the emoticons are stored and afterwards shown correctly.

create hash equivalent to python call using javascript on browser

I'm trying to create hash for calling thesubdb api they've given the python implementation of their hash generation method.
My project needs me to create hash on the go on browser and then pass it to my php backend and then call subdbapi using php.
But for that first of all I need to create hash of video file on my browser using javascript.
I'm using the new html 5 file api to read local file on users computer and create hash for same.
var md5 = CryptoJS.MD5(binary).toString();
console.log(md5);
above is my javascript code.
This does not match the output of the python code that they've given which is :
def get_hash(name):
readsize = 64 * 1024
with open(name, 'rb') as f:
size = os.path.getsize(name)
data = f.read(readsize)
f.seek(-readsize, os.SEEK_END)
data += f.read(readsize)
return hashlib.md5(data).hexdigest()
i'm sure i'm missing something fundamental in my javascript code.
thanks in advance.

Parameter retrieval for HTTP PUT requests under IIS5.1 and ASP-classic?

I'm trying to implement a REST interface under IIS5.1/ASP-classic (XP-Pro development box). So far, I cannot find the incantation required to retrieve request content variables under the PUT HTTP method.
With a request like:
PUT http://localhost/rest/default.asp?/record/1336
Department=Sales&Name=Jonathan%20Doe%203548
how do I read Department and Name values into my ASP code?
Request.Form appears to only support POST requests. Request.ServerVariables only gets me to header information. Request.QueryString doesn't get me to the content either...
Based on the replies from AnthonyWJones and ars I went down the BinaryRead path and came up with the first attempt below:
var byteCount = Request.TotalBytes;
var binContent = Request.BinaryRead(byteCount);
var myBinary = '';
var rst = Server.CreateObject('ADODB.Recordset');
rst.Fields.Append('myBinary', 201, byteCount);
rst.Open();
rst.AddNew();
rst('myBinary').AppendChunk(binContent);
rst.update();
var binaryString = rst('myBinary');
var contentString = binaryString.Value;
var parameters = {};
var pairs = HtmlDecode(contentString).split(/&/);
for(var pair in pairs) {
var param = pairs[pair].split(/=/);
parameters[param[0]] = decodeURI(param[1]);
}
This blog post by David Wang, and an HtmlDecode() function taken from Andy Oakley at blogs.msdn.com, also helped a lot.
Doing this splitting and escaping by hand, I'm sure there are a 1001 bugs in here but at least I'm moving again. Thanks.
Unfortunately ASP predates the REST concept by quite some years.
If you are going RESTFull then I would consider not using url encoded form data. Use XML instead. You will be able to accept an XML entity body with:-
Dim xml : Set xml = CreateObject("MSXML2.DOMDocument.3.0")
xml.async = false
xml.Load Request
Otherwise you will need to use BinaryRead on the Request object and then laboriously convert the byte array to text then parse the url encoding yourself along with decoding the escape sequences.
Try using the BinaryRead method in the Request object:
http://www.w3schools.com/ASP/met_binaryread.asp
Other options are to write an ASP server component or ISAPI filter:
http://www.codeproject.com/KB/asp/cookie.aspx

Categories

Resources