I am trying to implement AES/ECB/NoPadding with cryptojs.
On the Java side I have this:
public static String encrypt(String input, String key) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
return DatatypeConverter.printHexBinary(cipher.doFinal(padToMultipleOf32(input.getBytes())));
}
public static byte[] padToMultipleOf32(final byte[] bytes) {
int n16 = ((bytes.length + 31) / 32);
int paddedLen = n16 * 32;
byte[] result = new byte[paddedLen];
for (int i = 0; i < bytes.length; i++) {
result[i] = bytes[i];
}
for (int i = bytes.length; i < paddedLen; i++) {
result[i] = 0x00;
}
System.out.println(new String(result).length());
return result;
}
Running Test.encrypt("test", "4g2ef21zmmmhe678")
Gives me: C24F53DDEAD357510A27AA283C74BBF4638B3F81F8EB44652D424D7C32897525
How would I do the same in cryptojs, what I have currently doesnt work:
var pwd = CryptoJS.AES.encrypt("test", "4g2ef21zmmmhe678", {
mode : CryptoJS.mode.ECB,
padding : CryptoJS.pad.NoPadding
});
expect(pwd.ciphertext.toString(CryptoJS.enc.Base64)).toEqual("C24F53DDEAD357510A27AA283C74BBF4638B3F81F8EB44652D424D7C32897525");
Please help
The documentation of CryptoJS says that when passing a plain passphrase (i.e. a String) to encrypt () , it will automatically generate a 256 bit key (Java implements the 128 bit version) using that password as the seed.
To prevent that you can use this function to directly convert your passphrase to a key:
var key = CryptoJS.enc.Utf8.parse("password");
Possibly you will also have to synchronize the encodings of the ciphertexts. See here for a detailed example on how to perform interoperable encryption with Java and CryptoJS.
Related
This is the function used to encrypt in java
public static String encryptionFunction(String fieldValue, String pemFileLocation) {
try {
// Read key from file
String strKeyPEM = "";
BufferedReader br = new BufferedReader(new FileReader(pemFileLocation));
String line;
while ((line = br.readLine()) != null) {
strKeyPEM += line + "\n";
}
br.close();
String publicKeyPEM = strKeyPEM;
System.out.println(publicKeyPEM);
publicKeyPEM = publicKeyPEM.replace("-----BEGIN PUBLIC KEY-----\n", "");
publicKeyPEM = publicKeyPEM.replace("-----END PUBLIC KEY-----", "").replaceAll("\\s", "");;
byte[] encoded = Base64.getDecoder().decode(publicKeyPEM);
// byte[] encoded = Base64.decode(publicKeyPEM);
KeyFactory kf = KeyFactory.getInstance("RSA");
PublicKey pubKey = (PublicKey) kf.generatePublic(new X509EncodedKeySpec(encoded));
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
byte[] cipherData = cipher.doFinal(fieldValue.getBytes());
if (cipherData == null) {
return null;
}
int len = cipherData.length;
String str = "";
for (int i = 0; i < len; i++) {
if ((cipherData[i] & 0xFF) < 16) {
str = str + "0" + java.lang.Integer.toHexString(cipherData[i] & 0xFF);
} else {
str = str + java.lang.Integer.toHexString(cipherData[i] & 0xFF);
}
}
return str.trim();
} catch (Exception e) {
System.out.println("oops2");
System.out.println(e);
}
return null;
}
I want the equivalent of this in javascript/Nodejs, i tried this:
import * as NodeRSA from 'node-rsa';
private encryptionFunction(fieldValue: string , pemkey: string) : string {
const rsa = new NodeRSA(pemkey);
const encrypted= rsa.encrypt(fieldValue , 'hex')
return encrypted
}
But the output size of both functions is the same, but apparently the encryption type is wrong.
Node-RSA applies OAEP (here) as padding by default, so the PKCS#1 v1.5 padding used in the Java code must be explicitly specified. This has to be added after key import and before encryption:
rsa.setOptions({ encryptionScheme: 'pkcs1' });
Alternatively, the padding can be specified directly during key import:
const rsa = new NodeRSA(pemkey, { encryptionScheme: 'pkcs1' });
With this change, both codes are functionally identical.
Regarding testing: Keep in mind that RSA encryption is not deterministic, i.e. given the same input (key, plaintext), each encryption provides a different ciphertext. Therefore, the ciphertexts of both (functionally identical) codes will be different even if the input is identical. So this is not a bug, but the expected behavior.
How then can the equivalence of both codes be proved? E.g. by decrypting both ciphertexts with the same code/tool.
I'm triying to Encrypt string with C# and decrypt it using Angular crypto-js library but it's giving me different output.
I tried different c# aes encryption implementations but crypto-js library can't decrypt the encrypted data in c#. Thank you for any help.
Here is my code
Program.cs
static void Main()
{
var r = EncryptString("exampleString", "examplePassword");
Console.Write(r);
}
public static string EncryptString(string plainText, string passPhrase)
{
if (string.IsNullOrEmpty(plainText))
{
return "";
}
// generate salt
byte[] key, iv;
var salt = new byte[8];
var rng = new RNGCryptoServiceProvider();
rng.GetNonZeroBytes(salt);
DeriveKeyAndIv(passPhrase, salt, out key, out iv);
// encrypt bytes
var encryptedBytes = EncryptStringToBytesAes(plainText, key, iv);
// add salt as first 8 bytes
var encryptedBytesWithSalt = new byte[salt.Length + encryptedBytes.Length + 8];
Buffer.BlockCopy(Encoding.ASCII.GetBytes("Salted__"), 0, encryptedBytesWithSalt, 0, 8);
Buffer.BlockCopy(salt, 0, encryptedBytesWithSalt, 8, salt.Length);
Buffer.BlockCopy(encryptedBytes, 0, encryptedBytesWithSalt, salt.Length + 8, encryptedBytes.Length);
// base64 encode
return Convert.ToBase64String(encryptedBytesWithSalt);
}
private static void DeriveKeyAndIv(string passPhrase, byte[] salt, out byte[] key, out byte[] iv)
{
// generate key and iv
var concatenatedHashes = new List<byte>(48);
var password = Encoding.UTF8.GetBytes(passPhrase);
var currentHash = new byte[0];
var md5 = MD5.Create();
bool enoughBytesForKey = false;
// See http://www.openssl.org/docs/crypto/EVP_BytesToKey.html#KEY_DERIVATION_ALGORITHM
while (!enoughBytesForKey)
{
var preHashLength = currentHash.Length + password.Length + salt.Length;
var preHash = new byte[preHashLength];
Buffer.BlockCopy(currentHash, 0, preHash, 0, currentHash.Length);
Buffer.BlockCopy(password, 0, preHash, currentHash.Length, password.Length);
Buffer.BlockCopy(salt, 0, preHash, currentHash.Length + password.Length, salt.Length);
currentHash = md5.ComputeHash(preHash);
concatenatedHashes.AddRange(currentHash);
if (concatenatedHashes.Count >= 48)
enoughBytesForKey = true;
}
key = new byte[32];
iv = new byte[16];
concatenatedHashes.CopyTo(0, key, 0, 32);
concatenatedHashes.CopyTo(32, iv, 0, 16);
md5.Clear();
}
static byte[] EncryptStringToBytesAes(string plainText, byte[] key, byte[] iv)
{
// Check arguments.
if (plainText == null || plainText.Length <= 0)
throw new ArgumentNullException("plainText");
if (key == null || key.Length <= 0)
throw new ArgumentNullException("key");
if (iv == null || iv.Length <= 0)
throw new ArgumentNullException("iv");
// Declare the stream used to encrypt to an in memory
// array of bytes.
MemoryStream msEncrypt;
// Declare the RijndaelManaged object
// used to encrypt the data.
RijndaelManaged aesAlg = null;
try
{
// Create a RijndaelManaged object
// with the specified key and IV.
aesAlg = new RijndaelManaged { Mode = CipherMode.CBC, KeySize = 256, BlockSize = 128, Key = key, IV = iv };
// Create an encryptor to perform the stream transform.
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
// Create the streams used for encryption.
msEncrypt = new MemoryStream();
using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (var swEncrypt = new StreamWriter(csEncrypt))
{
//Write all data to the stream.
swEncrypt.Write(plainText);
swEncrypt.Flush();
swEncrypt.Close();
}
}
}
finally
{
// Clear the RijndaelManaged object.
aesAlg?.Clear();
}
// Return the encrypted bytes from the memory stream.
return msEncrypt.ToArray();
}
Simply decrypting it using crypto-js
let CryptoJS = require('crypto-js');
let r = CryptoJS.AES.decrypt('exampleString', 'examplePassword').toString();
The example code is attempting to decrypt the original unencrypted string, which looks to be a mistake perhaps created when trying to simplify the example code for posting the question? Either way the steps required are not too difficult, but the toString() call needs to be replaced.
var data = "U2FsdGVkX1/Zvh/5BnLfUgfbg5ROSD7Aohumr9asPM8="; // Output from C#
let r2 = CryptoJS.enc.Utf8.stringify(CryptoJS.AES.decrypt(data, 'examplePassword'));
console.log(r2);
I'm creating a react-native application, where I need to encrypt with TripleDES using ECB mode and Pkcs7 padding.
I have an Android Java piece of code that do the encrypt algorithm i want to replicate.
In react-native I added "CryptoJS" from https://github.com/brix/crypto-js and I called CryptoJS.enc.TripleDES.encrypt() method but it returns a different result than expected.
This is Android code i want to reach:
private static byte[] encrypt(String message, String privateKeyMobile) throws Exception {
final MessageDigest md = MessageDigest.getInstance("MD5");
final byte[] digestOfPassword = md.digest(privateKeyMobile.getBytes("utf-8"));
final byte[] keyBytes = new byte[24];
int q;
for (q = 0; q < 24 && q < digestOfPassword.length; q++) {
keyBytes[q] = digestOfPassword[q];
}
if (q < 24) {
for (int u = q; u < 24; u++)
keyBytes[u] = 0;
}
for (int j = 0, k = 16; j < 8;) {
keyBytes[k++] = keyBytes[j++];
}
final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
final Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS7Padding");
cipher.init(Cipher.ENCRYPT_MODE, key);
final byte[] plainTextBytes = message.getBytes("utf-8");
return cipher.doFinal(plainTextBytes);
}
This one is my react-native code:
encrypt(message, key) {
let md5key = CryptoJS.enc.MD5(key);
var ciphertext = TripleDES.encrypt(message, md5key, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
});
return ciphertext;
}
The two functions returns different outputs.
This php code makes same work as Java code:
https://webtools.workontech.com/triple-des-encryption-online
Other online TripleDES tools return the same react-native result.
I am trying to convert one JavaScript encryption function in C#. But not getting the valid output. Can someone help me with this issue.
Below is my JavaScript function for encryption
function encryptPassword()
{
var password="samplepassword"; mod="ce33b5600160ba9354a0e56ee3e43369e9a824e0f88e20ad52bbde015cc8c8fed57aa2d65c4eb13dc099f38718fcbc471e60bb4d82a5e05b6a64c5dc8d2e17ca44c205a6c54540d4884285808e829043b2f11838dc5d603750616bf5fd711d810b50f7a468e31d0cfc5b70e6a72fe887a2e26db44c3868a86febb5e4c5f6c27000b202a0460488db3eac48f1ee80e7ca6bb8a9af2b985c28aa25ecdc74e485abd20311c21add507e8c65c3d11d743ebbd76c44933bb68981e1171376d1ddf33607fa2116cb747f0c3f238bae5b01878004157cfef9c8cdd697ee39759625f84abd89469a8b8cd9eabb2e79fd9269ab4e62670d6ec8b5b1f6d986385b2394bfdb";
var rsa = new RSAKey();
rsa.setPublic(mod, "10001");
var res = rsa.encrypt(password);
if(res) {
document.getElementById('password').value=res;
return true;
}
else
{
return false;
}
}
Below is my C# implementation for the same. But somehow I am not getting the proper output. C# generated output is not validated at server side.
C# code
public static string EncryptRSAx(string public_keyHex, uint exp, string data)
{
byte[] bytes = new byte[public_keyHex.Length / 2];
for (int i = 0; i < public_keyHex.Length - 1; i += 2)
{
bytes[i / 2] = byte.Parse(public_keyHex.Substring(i, 2), System.Globalization.NumberStyles.HexNumber);
}
string public_key = Convert.ToBase64String(bytes);
return RSAEncrypt(public_key, Convert.ToBase64String(BitConverter.GetBytes(exp)), data);
}
public static string RSAEncrypt(string public_key, string exponent, string data)
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
//rsa.FromXmlString()
rsa.FromXmlString(String.Format("<RSAKeyValue><Modulus>{0}</Modulus><Exponent>{1}</Exponent></RSAKeyValue>", public_key, exponent));
byte[] plainbytes = System.Text.Encoding.UTF8.GetBytes(data);
byte[] cipherbytes = rsa.Encrypt(plainbytes,false);
return Convert.ToBase64String(cipherbytes);
}
I'm trying to replicate the Java code in JavaScript.
below is my Java code:
public static String encrypt(String input)
final byte[] SALT= { (byte) 0x21, (byte) 0x21, (byte) 0xF0, (byte) 0x55, (byte) 0xC3, (byte) 0x9F, (byte) 0x5A, (byte) 0x75 };
final int ITERATION_COUNT = 31;
{
if (input == null)
{
throw new IllegalArgumentException();
}
try
{
KeySpec keySpec = new PBEKeySpec(null, SALT, ITERATION_COUNT);
AlgorithmParameterSpec paramSpec = new PBEParameterSpec(SALT, ITERATION_COUNT);
SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);
Cipher ecipher = Cipher.getInstance(key.getAlgorithm());
ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
byte[] enc = ecipher.doFinal(input.getBytes());
String res = new String(Base64.encodeBase64(enc));
// escapes for url
res = res.replace('+', '-').replace('/', '_').replace("%", "%25").replace("\n", "%0A");
LOGGER.info("String Encrypted Successfully");
return res;
}
catch (Exception e)
{
LOGGER.error("encrypt Exception: "+e.getMessage());
}
return "";
}
and the JavaScript code, so far hammed up is below:
var encrypt = function(){
var iterations = 31;
var key = CryptoJS.MD5("PBEWithMD5AndDES");
var salt = CryptoJS.enc.Hex.parse('0021002100f0005500C3009F005A0075');
var options = {
mode: CryptoJS.mode.CBC,
iv: salt
};
var hashedPassword = CryptoJS.MD5($scope.data.webPassword);
var encryptedPassword = CryptoJS.DES.encrypt(hashedPassword, key,options).toString();
var result = encryptedPassword.toString(CryptoJS.enc.Base64);
}
but with both the encryption the encoded string I'm getting is different.
PBEwithMD5andDES is obsolete technology and should not be used nowadays. This answer is only provided for demonstration purposes.
PBEwithMD5andDES is defined in PKCS#5 v1.5 which is nothing more than deriving key+IV using PBKDF1 (with MD5) and encrypting with DES.
var password = CryptoJS.enc.Utf8.parse("test");
var salt = CryptoJS.enc.Hex.parse("2121F055C39F5A75");
var iterations = 31;
// PBE according to PKCS#5 v1.5 (in other words: PBKDF1)
var md5 = CryptoJS.algo.MD5.create();
md5.update(password);
md5.update(salt);
var result = md5.finalize();
md5.reset();
for(var i = 1; i < iterations; i++) {
md5.update(result);
result = md5.finalize();
md5.reset();
}
// splitting key and IV
var key = CryptoJS.lib.WordArray.create(result.words.slice(0, 2));
var iv = CryptoJS.lib.WordArray.create(result.words.slice(2, 4));
var encrypted = CryptoJS.DES.encrypt("test", key, {
iv: iv
});
enchex.innerHTML = encrypted.ciphertext.toString();
encbase64.innerHTML = encrypted.ciphertext.toString(CryptoJS.enc.Base64);
<script src="https://cdn.rawgit.com/CryptoStore/crypto-js/3.1.2/build/rollups/tripledes.js"></script>
<script src="https://cdn.rawgit.com/CryptoStore/crypto-js/3.1.2/build/rollups/md5.js"></script>
<div>Hex: <span id="enchex"></span></div>
<div>Base64: <span id="encbase64"></span></div>
Here is a jsFiddle to experiment with and here is the example Java code. Both produce the same result in Hex: aa8101a7d63093c6.
Security considerations:
PBEwithMD5andDES should not be used and there are better alternatives like PBEWithHmacSHA256AndAES_128 which require a slightly different approach.
The number of iterations must be large (a thousand to a million) in order to make it hard to brute-force the password. DES only provides 56 bits of security, so it is even possible to brute-force the key directly with today's means.
The salt must be randomly generated in order to achieve semantic security. The salt itself doesn't need to be secret. Since it has a known length it can be simply prepended to the ciphertext and sliced off before decryption.