create C# 256 bit AES encryption like cryptoJS - javascript

im trying to encrpyt a payload in c#.
i have the code in Javascript and im trying to create same encryption in C#, having hard time to recreate the same encryption.
given javascript code (cannot be changed):
var data =
{
'username':username,
'password':password,
'isPersistent':'false'
};
var encrypted = CryptoJS.AES.encrypt(JSON.stringify(data),token, { format: JsonFormatter });
var body = {
payload: JSON.parse(encrypted.toString()),
token: token
}
debugger
$.post(url, body).success(resultFunction)
i want to create the same encryption in c#
Dictionary<string, string> data = new Dictionary<string, string>();
data.Add("username", username);
data.Add("password", password);
data.Add("isPersistent", "false");
string token = "7e4bac048ef766e83f0ec8c079e1f90c2eb690a9";
string serializedData = json_serialize(data);
string encrypted = EncryptText(serializedData, token);
Dictionary<string, string> body = new Dictionary<string, string>();
body.Add("payload", json_deserialize(encrypted));
body.Add("token", token);
var loginWebRequest = createWebRequest(address, "POST", json_serialize(body));
i have several issue here, in js you can specify the format of encryption and then use JSON.parse.
it seems it cannot be done in c#.
i used the methods from http://www.codeproject.com/Articles/769741/Csharp-AES-bits-Encryption-Library-with-Salt.
is there anyway i can create the same code snippet in c#?
Thanks!

The code from this post: openssl using only .NET classes is compatible with CryptoJS AES.
Test:
JS:
var encrypted = CryptoJS.AES.encrypt("abc12345","7e4bac048ef766e83f0ec8c079e1f90c2eb690a9");
encrypted.toString(); //output: "U2FsdGVkX18eGD2hSe9UyGgTk5NGKFmvWq/3c5IYHoQ="
C#:
var p = new Protection();
var s = p.OpenSSLDecrypt("U2FsdGVkX18eGD2hSe9UyGgTk5NGKFmvWq/3c5IYHoQ=", "7e4bac048ef766e83f0ec8c079e1f90c2eb690a9");
Console.WriteLine(s);//output: "abc12345"

Related

How do i get RSACryptoServiceProvider to verify a message using public key and signature

I generated a private and public key in javascript like this.
import crypto from "crypto";
/*export const { publicKey, privateKey } = crypto.generateKeyPairSync("rsa", {
modulusLength: 2048,
});*/
const pair = crypto.generateKeyPairSync("rsa", { modulusLength: 2048 });
export const privateKey = pair.privateKey.export({
type: "pkcs1",
format: "pem",
});
export const publicKey = pair.publicKey.export({
type: "pkcs1",
format: "pem",
});
Then i use the private key to create a signature for a jsonfile like this, and the public key to verify it before i return the signature.
//Lav signatur
const signate = crypto.createSign("SHA384");
signate.update(Buffer.from(licenseRelationship, "utf-8"));
const signature = signate.sign(privateKey, "hex");
const verifier = crypto.createVerify("SHA384");
// verificer signature, besked
verifier.update(Buffer.from(licenseRelationship, "utf-8"));
const verificationResult = verifier.verify(publicKey, signature, "hex");
This works perfectly, and then i return the json and the signature as a http response.
I recieve it in c# code and store the two components so im can use them later on request.
Upon request i fetch the two components and want to use the signature to check if the json has been tampered with.
I also has the public key in this code.
I do it like this.
string licenseRelationshipJson = licenseRelationshipDAO.getLicenseRelationshipWithoutSignatureAsJson(licenseRelationship);
byte[] signature = Encoding.UTF8.GetBytes(licenseRelationship.signature);
byte[] licenseRelationshipJsonAsArray = Encoding.UTF8.GetBytes(licenseRelationshipJson);
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(2048);
result = rsa.VerifyData(licenseRelationshipJsonAsArray, signature,
HashAlgorithmName.SHA384, RSASignaturePadding.Pkcs1);
if (result)
{
log.write("Message verified ", null);
} else
{
log.write("Message not Verified ", null);
}
All debug code and exception handling removed.
I'm a crypto virgin, and am trying to understand this. But i must have misunderstood something serious.
I have the public key as a string (not base64 encoded)
Ive checked the json, and it is the exact same bytes when signed in Javascript as when being verified in c#
The public key is not used in this process. That has to be wrong i think ?
How do i get the public key into the RWACryptoServiceProvider ?
Im sure im using RWACryptoServiceProvider wrong.
EDIT....:
Ive tried this instead, but still to no avail.
string licenseRelationshipJson = licenseRelationshipDAO.getLicenseRelationshipWithoutSignatureAsJson(licenseRelationship);
byte[] signature = Encoding.UTF8.GetBytes(licenseRelationship.signature);
byte[] licenseRelationshipJsonAsArray = Encoding.UTF8.GetBytes(licenseRelationshipJson);
byte[] asBytes = Encoding.ASCII.GetBytes(DataStorage.Instance.PUBLIC_KEY);
char[] publicKeyAsArray = Encoding.ASCII.GetChars(asBytes);
ReadOnlySpan<char> publicKeyChars = publicKeyAsArray;
RSA rsa = RSA.Create();
try
{
rsa.ImportFromPem(publicKeyChars);
result = rsa.VerifyData(licenseRelationshipJsonAsArray, signature, HashAlgorithmName.SHA384, RSASignaturePadding.Pkcs1);
} catch (CryptographicException cex)
{
log.write("Something went wrong with the crypto verification process", cex);
}
.
.
.
Thankyou for your time.

Javscript store data from json file into map?

I´m quite new to Javascript, but know a lot about Java. Im trying to learn the basics by doing little projects, for understanding the language and code. In Java, i worked a lot with storing data from maps in json-files and, when you start the programm, the json file loads the data into the map.
An example for Java:
public Map<Integer, Client> example = new HashMap<>();
Herefor the Client class :
public class Client {
private String username;
private String password;
private String host;
public Client(String username, String password, String host) {
this.username = username;
this.password = password;
this.host = host;
}
public String getPassword() {
return password;
}
public String getHost() {
return host;
}
public String getUsername() {
return username;
}
}
I want to do the same thing, but now in Javascript. My map looks like that:
var price= new Map();
Like the Java example above, I want to load such a Map into a json file and want to load the data from the json file into my map.
Could somebody proivde me with a good example of code, how to store data from json in my map ? Even a link for a tutorial would be great!
In JS it's more common to use plain objects instead of Map().
For example, let's say you have the same Client class:
class Client {
constructor(username, password, host) {
this.username = username;
this.password = password;
this.host = host;
}
}
const client1 = new Client('username1', 'password1', 'localhost');
const client2 = new Client('username2', 'password2', 'localhost');
Your price map (int to Client) would look like this:
const price = {
1: client1,
2: client2
};
Now, you can use serialize it to json:
const json = JSON.stringify(price);
Or parse it from json:
const price = JSON.parse(json);
However, if you really want to use Map, here's a tutorial for it.

HMAC256 from C# to Javascript returns different results

I want to create a HMAC256 key from a string with a HMAC key based on my C# project in Javascript. however, each project has different results and can't seem to find a way to make the results identical.
C# PROJECT
private string CalculateHMAC(string hmacKey, string signingstring) {
byte[] key = PackH(hmacKey) //returns 32 bit array;
byte[] data = Encoding.UTF8.GetBytes(signingstring);
try {
using(HMACSHA256 hmac = new HMACSHA256(key)) {
// Compute the hmac on input data bytes
byte[] rawHmac = hmac.ComputeHash(data);
// Base64-encode the hmac
return Convert.ToBase64String(rawHmac);
}
} catch (Exception e) {
throw new Exception("Failed to generate HMAC : " + e.Message);
}
}
JAVASCRIPT CODE
var hash = CryptoJS.HmacSHA256(byteString, hmacKeyinString);
var msg = hash.toString(CryptoJS.enc.Base64);
Thank you in advance.
Using CryptoJS in my javascript project
fixed with this line of code
var wordsKey = CryptoJS.enc.Hex.parse('yourkey');
var hash = CryptoJS.HmacSHA256(convertString, wordsKey);
var hashInBase64 = CryptoJS.enc.Base64.stringify(hash);

Different behaviors from Decryption method in java

i am using decryption alogirthm RSA with public and private keys from certification .
var encrypt = new JSEncrypt();
var publicKey = "example";
encrypt.setPublicKey(publicKey);
var data = encrypt.encrypt(value);
console.log(data);
return data;
public static String getDecrypted(String data, String Key)
throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException,
IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
Cipher cipher = Cipher.getInstance("RSA");
PrivateKey pk = KeyFactory.getInstance("RSA")
.generatePrivate(new PKCS8EncodedKeySpec(Base64.decodeBase64(Key.getBytes())));
cipher.init(Cipher.DECRYPT_MODE, pk);
// byte[] encryptedbytes =
// cipher.doFinal(Base64.encodeBase64(data.getBytes()));
return new String(cipher.doFinal(Base64.decodeBase64(data)));
}
i am using front end encryption and in main method encryption . the encrypted values from two sides are getting correctly . but when i call it from web
i get another values like that
EAQ�žÃqÈ›#Á¢éz¡?�4zsHD-U€�
KÉ¢a`Õ³=jö`›=šúFhU;••˜ü®2¿¶žñÛ¤lÉê×)§?]¾–`n_üÙ&1ï)ðeÈž‹x¯ø¬#;ýp& Ê*í~ý¾´çVõF¯±ë©yṉ̃©w_f'úH⬒#™G™|¦ý¹j"Ìç8=ŽRÉž[££4™s#àâ
and the value at the end

HMAC C# and JavaScript

Having trouble getting C# and Javascript to generate the same HMAC:
C#:
string data = String.Format("{0}{1}{2}{3}{4}{5}", APPId, requestHttpMethod, requestUri, requestTimeStamp, nonce, requestContentBase64String);
var secretKeyBytes = Convert.FromBase64String(sharedKey);
byte[] signature = Encoding.UTF8.GetBytes(data);
using (HMACSHA256 hmac = new HMACSHA256(secretKeyBytes))
{
byte[] signatureBytes = hmac.ComputeHash(signature);
return (incomingBase64Signature.Equals(Convert.ToBase64String(signatureBytes), StringComparison.Ordinal));
}
Produces: apZUyGrS23BcEd2q5guGS4uQWVvcCvaDXIjCrLn/Hp4=
Javascript:
var signatureRawData = "".concat(appId, requestHttpMethod, requestUri, requestTimeStamp, nonce, requestContentBase64String);
var hash = CryptoJS.HmacSHA256(signatureRawData, apiKey);
var hashInBase64 = CryptoJS.enc.Base64.stringify(hash);
Produces: mFZyyKT03OOThRnt/9dG/0x+jRde3jCMvI6Rd0eKhEE=
Where is the apiKey in the c# code? Is it sharedKey? Is sercretKeyBytes a string, char[], or byte[]? I suspect secrtetKeyBytes is being converted to a string which is the cause of the issue.

Categories

Resources