I give up in trying to research for solutions regarding my problem. I've done my part and search about this problem and encountered solutions (like this https://stackoverflow.com/a/21252990/5328303) which was really the same problem as mine but he is using aes-128-ecb.
I cannot get the solution to work for aes-192-ecb mode.
Here's the node.js part (take note I cannot change this part of the code since this is a third party provider and I'm very limited.)
console.log(encrypt("hello world"))
function encrypt(data) {
const aesKey = '4327601417486622'
const algorithm = 'aes-192-ecb'
const cipher = crypto.createCipher(algorithm, aesKey)
const crypted = cipher.update(data, 'utf-8', "hex") + cipher.final("hex")
return crypted
}
// expected: 066c47b162cd5c464ea9805742c1af9b
And here's my Java function:
public static String decrypt(String seed, String encrypted) throws Exception {
byte[] keyb = seed.getBytes("UTF-8");
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] thedigest = md.digest(keyb);
SecretKeySpec skey = new SecretKeySpec(thedigest, "AES");
Cipher dcipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
dcipher.init(Cipher.DECRYPT_MODE, skey);
byte[] clearbyte = dcipher.doFinal(toByte(encrypted));
return new String(clearbyte);
}
The java code above works well if I use aes-128-ecb on my node code but it cannot decode when I'm using aes-192-ecb or even aes-256-ecb.
Maybe I just don't quite understand openssl EVP_BytesToKey function since I read that crypto.createCipher() uses it when encrypting. It also said that it is hashing the key with MD5 which I'm currently doing with the java code.
Also I was thinking that the aesKey that I have is only 16 bytes and maybe that's why it won't work with AES-192 and only works with AES-128. I want to understand how openssl/crypto does it when I'm only passing a 16 byte key with the required 24 bytes key for AES-192 since I cannot change the node.js code.
Am I on the right track? Can anyone guide me?
Thank you!
Related
I'm trying to convert below java code into nodejs.
private static String TRANS_MODE = "Blowfish";
private static String BLOWFISH_KEY = "BLOWFISH_KEY";
public static String encrypt(String password) throws Exception {
SecretKeySpec keySpec = new SecretKeySpec(BLOWFISH_KEY.getBytes("Windows-31J"),TRANS_MODE);
Cipher cipher;
cipher = Cipher.getInstance(TRANS_MODE);
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
byte[] passByte;
passByte = cipher.doFinal(password.getBytes("Windows-31J"));
return new String(Hex.encodeHex(passByte));
}
Here is what I was able to figure out-
const crypto = require('crypto');
function encrypt(password)
var fcKey = "BLOWFISH_KEY";
var cipher = crypto.createCipher('BF-CBC', fcKey, "");
var encrypted = cipher.update(password,'ascii','hex');
encrypted += cipher.final('hex');
return encrypted;
I'm not able to get same output. For example if
password= "password01"
Java Code output - fe0facbf8d458adaa47c5fe430cbc0ad
Nodejs Code output - ae5e8238c929b5716566e97fa35efb9b
Can someone help me figure out the problem ??
Notice that crypto.createCipher(algorithm, password[, options]) is deprecated and should not be used.
Where the SecretKeySpec(..) in java takes a binary key as input, the createCipher(..) in js takes a "password" as input, and behind the scene tries to derive a binary key using MD5. So your actually key used in the two programs ends up being different. The js methode
also tries to derive an IV from the password, which is bad practice and different from your java code.
In js you need to use the crypto.createCipheriv() instead. And when you are at it, you also need to consider if an iv is needed - both in Java and in js.
Every time the encryption values changed by using AES, let anyone investigate the below code and let me know the issue
code:
private static final String secretKeys = "58BA833E57A51CBF9BF8BAB696BF9"
public static String encrypt() throws Exception {
byte[] salt = new byte[16];
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
PBEKeySpec pbeKeySpec = new PBEKeySpec(secretKeys.getChars(),salt,1000, 256);
Key secretKey = factory.generateSecret(pbeKeySpec);
byte[] key = new byte[32];
byte[] iv = new byte[16];
SecretKeySpec secret = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secret);
byte[] result = cipher.doFinal("welcome".getBytes("UTF-8"));
String s = Base64.getEncoder().encodeToString(result);
return s
}
Output
first time I got the below-encrypted string
CZRIP35M4CnJtuDQ6YpmaQ==
The second time I got the below-encrypted string
/fylTjohAZDsnCaHhiZo3A==
I have three questions:
why the encrypted string not a constant?
how can I set the Blocksize? ( AES.BlockSize = 128;)
How can I set the padding mode? (AES.Padding = PaddingMode.PKCS7;)
For the first question, #Freiheit already answered this.
Long story short, based on the iv (initilization vector) which acts as a salt and will be different for each encryption.
Having that said, encrypting the same plain text will result in different encrypted text, but the decryption (if necessary) will result back into the same plain text.
IV is helpful to make the encryption predictable.
Having stored the same password for 2 different users in a database will have different values, but will be the same password.
With the current cipher configured, you already have 128 block size. You can read more about the different cypher transformation here. You can also find more information of the block sizes for different algorithms here
You just need to change the Cipher.getInstance() to AES/CBC/PKCS7Padding
1) the encrypted text is always different because the Cipher initialization is providing it's own IV since you are not providing one. You need to provide the IV you've "computed" in order to have a consistent output. Remember you never want to use an IV more than once for whatever this code is ultimately intended to do.
2) The keysize can be 128, 192 or 256 but the blocksize is always 128.
3) Java only provides PKCS5, but there is no difference in the implementation for AES. see what-is-the-difference-between-pkcs5-padding-and-pkcs7-padding
As was already pointed out there are several problems with the code provided such as the first lines not actually doing anything and the key and iv both being uninitialized. I would additionally suggest you use SecureRandom to initialize your key and iv. If you plan on using only a single AES key, this can be computed once and placed in the code or configuration file instead of running PBKDF2 every time.
Only adding to the answer provided by #micker, you need to invoke another version of Cipher.init(); one that takes the IV into account:
...
byte[] iv = new byte[16];
IvParameterSpec ivSpec = new IvParameterSpec(iv); // <= Wrap your IV bytes here.
SecretKeySpec secret = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secret, ivSpec); // <= Add IV here.
...
That being said, the implementation suffers from a slew of other issues (key being all zeroes, IV being all zeroes, first 4 line don't do anything for you (as #JBNizet pointed out)). I hope you are only using it to study how Java's encryption mechanics works.
So I have a problem that I cant't seem to solve. I need to decode some Base64 text using a generated hash md5 as key. I have written this code. The output does not come out readable. The key's "freeforall" and "validate" are the actual ones.
Can anyone give me some light to what is wrong with this code? Or possibly with my interpretation of the problem.
private String decrypt(String data, byte[] key) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] original = cipher.doFinal(Base64.decode(data));
return new String(original, "UTF-8").trim();
}
private byte[] getMD5(String value) throws NoSuchAlgorithmException, UnsupportedEncodingException {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(value.getBytes("utf-8"), 0, value.length());
return md.digest();
}
public static void main(String[] args) {
String grupo0 = "r8Z48nEsKskL+9mOb9EQ519MLNjeFkcTQe3M4+XMdmkWZ+7F3o027zOwuMpyr1XQKFDSILDSUxUhAIoDW4QcnoA0um0BKs4sA/ZczucCAEjCpQmy4xR3o+xR1Ve3bNV6/X3hq98hrlCdycgEwprn8qvQRAHwpA1FqseBl2NCuo+vn5VZA0GHKnuNPiApjCMDo6qpTIELy9FB+2vWZwYprA==";
String grupoMenos1 = "fGpu3YkXGxTdVTeHhC2FZT9utUOGJgvvmPlzlEq39oSTc419ashyqmBvYGSC7BqRvXQ3Wx+i8C7jIiaBo9fXAd/JLed+T6XvlSkJfH+PGX8xi8tuD+OoLhaA102mscVSatsKtGTzOWAt17DzWeLe2QKXbClN+ElGSQaPBRD/aHpNQJNAMrUOUEgPDNjbb7HmlmOfFsCpQZOEFq+n2SOMpA==";
System.out.println(decrypt(grupo0, getMD5("freeforall")));
System.out.println(decrypt(grupoMenos1, getMD5("validate")));
}
Without being able to see the code used to do the encryption, it is not possible to determine if you are doing the right thing. I have very similar code in an Android app and it works fine. One difference is that I pass a javax.crypto.spec.IvParameterSpec to Cipher.init(). Also, the Android Base64 class takes a flags argument for decode() but I don't think that is your problem here.
You also have a minor bug in your getMD5() function but it should not be the issue here since your keys are plain ASCII. You should use the length of the UTF-8 byte array not the length of the original string when calculating the digest.
md.update(value.getBytes("utf-8"), 0, value.length());
Should be:
byte [] valueBytes = value.getBytes("utf-8");
md.update(valueBytes, 0, valueBytes.length);
EDIT: As James K Polk suggested, you could just do:
md.update(value.getBytes("utf-8"));
This question already has answers here:
UTF-8 byte[] to String
(11 answers)
Closed 8 years ago.
I got a code snippet from another SO question and modified it a bit but I can't seem to get it to work. Can anyone figure out why? it's currently printing [B#405e70bc or similar values. All I'm trying to do is store a password in an encrypted form just for the sole purpose of keeping it away from curious eyes, is there a better way to do that?
String secret = "1234567812345678";
Key key = new SecretKeySpec(secret.getBytes(), "AES");
// Encrypt
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encryptedData = cipher.doFinal("helloworld".getBytes());
// Decrypt
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] decryptedData = cipher.doFinal(encryptedData);
System.out.println(decryptedData.toString());
There is nothing wrong with your encryption / decryption logic. The problem is with you calling .toString() on a byte [].
Use this output statement instead:
System.out.println(new String(decryptedData));
Thanks Alexander.
This worked
String secret = "1234567812345678";
Key key = new SecretKeySpec(secret.getBytes(), "AES");
// Encrypt
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encryptedData = cipher.doFinal("helloworld".getBytes());
// Decrypt
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] decryptedData = cipher.doFinal(encryptedData);
System.out.println(new String(decryptedData, "UTF-8"));
Please don't use this for anything critical. The standard Java AES code makes use of a fixed-length block cipher which can result in identical encrypted byte data. The upshot is a gradual leakage of plaintext information.
You should look into Cipher Block Chaining and Initialisation Vectors if you want your code to be more robust. http://www.javamex.com/tutorials/cryptography/block_modes.shtml
It may be overkill for your needs, but just thought i'd mention it.
I need to write Java code for encrypting a string using AES (Rijndael).
There is an already working C# code that does this same encryption for the same purpose.
The C# code:
RijndaelManaged rijndaelCipher = new RijndaelManaged();
rijndaelCipher.KeySize = 256;
rijndaelCipher.BlockSize = 256;
rijndaelCipher.Mode = CipherMode.CBC;
rijndaelCipher.Padding = PaddingMode.PKCS7;
byte[] pwdBytes = System.Text.Encoding.UTF8.GetBytes(password); // password is 32 bytes long
byte[] keyBytes = new byte[32];
System.Array.Copy(pwdBytes, keyBytes, 32);
rijndaelCipher.Key = keyBytes;
rijndaelCipher.IV = keyBytes;
ICryptoTransform transform = rijndaelCipher.CreateEncryptor();
The Java code I came up with:
byte[] sessionKey = SENDER_KEY.getBytes(StandardCharsets.UTF_8);
byte[] iv = SENDER_KEY.getBytes(StandardCharsets.UTF_8) ;
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
SecretKeySpec secretKeySpec = new SecretKeySpec(sessionKey, "AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
byte[] cipheredText = cipher.doFinal(stringedXmlForSending.getBytes());
When I execute the Java code I get the exception:
java.security.InvalidAlgorithmParameterException: Wrong IV length: must be 16 bytes long
Is it true that I cannot write in Java Rijndael encryption which is using 32 bytes keys?
Another difference is that padding in the C# is PKCS7 while in Java there is PKCS5. Will it still work?
The basic Java Cryptographic Extensions only provide AES implementations which is compatible with Rijndael at 128-bit block size. You should use 128-bit BlockSize so that you are compatible with most implementations which implement AES. If you do then the padding is no problem, since PKCS#5 is the same as PKCS#7 padding in AES.
It's important to note that AES is standardized which Rijndael isn't.
I struggled significantly to get this working due to the padding issue. By theory PKCS#5 from java should match PKCS#7 padding from .Net . When I looked deeper into the issue I found that there is an issue with Base64 encoder. Java has different library to encode byte into base64. By default java uses Base64 from java.util and it gives padding issue. When I used the different library to achieve this purpose I could get the desired library.
org.apache.commons.codec.binary.Base64.encodeBase64String (byte[] encryptedtext)