I'm able to successfully get a HMAC SHA256 using the following code:
public static String getHac(String dataUno, String keyUno) throws InvalidKeyException, NoSuchAlgorithmException, UnsupportedEncodingException {
SecretKey secretKey = null;
Mac mac = Mac.getInstance("HMACSHA256");
byte[] keyBytes = keyUno.getBytes("UTF-8");
secretKey = new SecretKeySpec(keyBytes,mac.getAlgorithm());
mac.init(secretKey);
byte[] text = dataUno.getBytes("UTF-8");
System.out.println("Hex encode: " + Hex.encode(keyUno.getBytes()));
byte[] encodedText = mac.doFinal(text);
return new String(Base64.encode(encodedText)).trim();
}
which yields:
HMAC: 9rH0svSCPHdbc6qUhco+nlkt2O7HE0rThV4M9Hbv5aY=
However, i would like getting this:
HMAC:eVXBY4RZmFQcOHHZ5FMRjDLOJ8vCuVGTjy7cHN7pqfo=
I tried an online tool and it appears that the difference between my code and online tool is that I am working with a text in the key type.
Test values:
String data = "5515071604000fAIkwJtkeiA:APA91bH_Pb5xB2lrmKWUst5xRuJ3joVE-sb9KoT0zXZuupIEfdHjii-cODj-JMnjyy7hFJUbIRAre9o2yaCU43KaFDmxKlhJhE36Dw0bZ2VntDUn_Zd1EJBuSyCYiUtmmkHfRvRy3hIb";
String key = "fc67bb2ee0648a72317dcc42f232fc24f3964a9ebac0dfab6cf47521e121dc6e";
getHac("5515071604000fAIkwJtkeiA:APA91bH_Pb5xB2lrmKWUst5xRuJ3joVE-sb9KoT0zXZuupIEfdHjii-cODj-JMnjyy7hFJUbIRAre9o2yaCU43KaFDmxKlhJhE36Dw0bZ2VntDUn_Zd1EJBuSyCYiUtmmkHfRvRy3hIb", "fc67bb2ee0648a72317dcc42f232fc24f3964a9ebac0dfab6cf47521e121dc6e"));
the execution of my method return
9rH0svSCPHdbc6qUhco+nlkt2O7HE0rThV4M9Hbv5aY=
(the online returns the same value with key type text selected)
and i expected
eVXBY4RZmFQcOHHZ5FMRjDLOJ8vCuVGTjy7cHN7pqfo=
(the online returns the same value with key type hex selected)
Assuming that you are using Apache Commons Codec 1.11, use the following:
byte[] keyBytes = Hex.decodeHex(keyUno);
getHac Method
You code just slightly modified looks like this then:
public static String getHac(String dataUno, String keyUno)
throws InvalidKeyException, NoSuchAlgorithmException, UnsupportedEncodingException, DecoderException {
SecretKey secretKey;
Mac mac = Mac.getInstance("HMACSHA256");
byte[] keyBytes = Hex.decodeHex(keyUno);
secretKey = new SecretKeySpec(keyBytes, mac.getAlgorithm());
mac.init(secretKey);
byte[] text = dataUno.getBytes("UTF-8");
byte[] encodedText = mac.doFinal(text);
return new String(Base64.encodeBase64(encodedText)).trim();
}
Test
This Java method gives then expected result:
eVXBY4RZmFQcOHHZ5FMRjDLOJ8vCuVGTjy7cHN7pqfo=
Related
I have made an app with javafx that I can write something and save it to database. my database is sqlite. it's a very simple app. although I've added login app to my writing app, still the sqlite can be opened by any software.
instead of encrypting the sqlite db(which i didn't know and i found really confusing to do :) ) I decided to encrypt the text in java and later when i want to read it i would turn it back to normal and show it.
I learned how to do it from this link and i changed it to print the string instead of writing to a file
so my final code looks like this:
public static void main(String[] args) throws Exception {
String textA = "";
String textB="";
byte[] thisismykey = "Hello How manyBytes are in#hts A".getBytes();
SecretKey secKey = new SecretKeySpec(thisismykey, "AES");
Cipher aesCipher = Cipher.getInstance("AES");
//turn your original text to byte
byte[] myoriginaltexttobyte = "Your Plain Text Here".getBytes();
//activate the encrypt method
aesCipher.init(Cipher.ENCRYPT_MODE, secKey);
//encrypt the text and assign the encrypted text to a byte array
byte[] bytecipheredoforgtext = aesCipher.doFinal(myoriginaltexttobyte);
//change it to string with new string
textA = new String(bytecipheredoforgtext);
System.out.println(textA);
//get the bytes of encrypted text and assign it to a byte array
byte[] byteofencryptedtext = textA.getBytes();
//activate the decrypt mode of the cipher
aesCipher.init(Cipher.DECRYPT_MODE, secKey);
//decrypt the encrypted text and assign it to a byte array
byte[] byteofencryptedbacktonormaltext = aesCipher.doFinal(byteofencryptedtext);
//change it to string with new string
textB = new String(byteofencryptedbacktonormaltext);
System.out.println(textB);
}
now that encrypt and decrypt are at the same method it works perfectly but I want to change it to a class with different methods so i could encrypt a text with one method and decrypt it with another. but when i separate things decrypt doesn't work well. Encrypt work well. this is the code now:
public class CipherFinalB {
//from https://stackoverflow.com/questions/20796042/aes-encryption-and-decryption-with-java/20796446#20796446
private final byte[] thisismykey;
private final SecretKey secKey;
private final Cipher aesCipher;
public CipherFinalB() throws NoSuchPaddingException, NoSuchAlgorithmException {
thisismykey = "HellodHowfmanyBytesgarehin#htseA".getBytes();
secKey = new SecretKeySpec(thisismykey, "AES");
aesCipher = Cipher.getInstance("AES");
}public String encrypt (String originaltext) throws InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
byte[] myoriginaltexttobyte =originaltext.getBytes();
aesCipher.init(Cipher.ENCRYPT_MODE, secKey);
byte[] bytecipheredoforgtext = aesCipher.doFinal(myoriginaltexttobyte);
String textA = new String(bytecipheredoforgtext);
System.out.println(textA);
return new String(bytecipheredoforgtext);
}
public String decrypt (String encryptedtext) throws InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
byte[] byteofencryptedtext = encryptedtext.getBytes();
aesCipher.init(Cipher.DECRYPT_MODE, secKey);
byte[] byteofencryptedbacktonormaltext = aesCipher.doFinal(byteofencryptedtext);
return new String(byteofencryptedbacktonormaltext);
}
}
when i use the encrypt method it gives me back a string. and when i send the same string to decrypt method it doesn't work and gives me the following error:
Exception in thread "main" javax.crypto.IllegalBlockSizeException: Input length must be multiple of 16 when decrypting with padded cipher
at java.base/com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:936)
at java.base/com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:847)
at java.base/com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:446)
at java.base/javax.crypto.Cipher.doFinal(Cipher.java:2191)
at main.CipherFinalB.decrypt(CipherFinalB.java:66)
at main.CipherTest.main(CipherTest.java:16)
What should i do?
UPDATE ANSWER:
as #Juan said the problem was "when data is ciphered you may have any byte in the array, not only printable characters." So I changed the method to return byte for encrypt method and decrypt method. decrypt method now gets byte as parameter instead of string and now everything works fine.
the updated code looks like this:
public byte[] encrypt (String originaltext) throws InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
byte[] myoriginaltexttobyte =originaltext.getBytes();
aesCipher.init(Cipher.ENCRYPT_MODE, secKey);
byte[] bytecipheredoforgtext = aesCipher.doFinal(myoriginaltexttobyte);
String textA = new String(bytecipheredoforgtext);
System.out.println(textA);
return bytecipheredoforgtext;
}
public byte[] decrypt (byte[] encryptedtext) throws InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
byte[] byteofencryptedtext = encryptedtext;
aesCipher.init(Cipher.DECRYPT_MODE, secKey);
byte[] byteofencryptedbacktonormaltext = aesCipher.doFinal(byteofencryptedtext);
return byteofencryptedbacktonormaltext;
}
I am not sure that the error is caused by this but the conversion between String and byte[] you are doing may work with bytes in the character set range, but when data is ciphered you may have any byte in the array, not only printable characters.
After you get the byte[] with the cyphered text, encode it as Base64 and store the string representation.
When decrypting, first decode the Base64 into the byte[] and then decipher it.
See Base64 class
I am trying to encode in nodejs and decryption for the same in nodejs works well. But when I try to do the decryption in Java using the same IV and secret, it doesn't behave as expected.
Here is the code snippet:
Encryption in nodeJs:
var crypto = require('crypto'),
algorithm = 'aes-256-ctr',
_ = require('lodash'),
secret = 'd6F3231q7d1942874322a#123nab#392';
function encrypt(text, secret) {
var iv = crypto.randomBytes(16);
console.log(iv);
var cipher = crypto.createCipheriv(algorithm, new Buffer(secret),
iv);
var encrypted = cipher.update(text);
encrypted = Buffer.concat([encrypted, cipher.final()]);
return iv.toString('hex') + ':' + encrypted.toString('hex');
}
var encrypted = encrypt("8123497494", secret);
console.log(encrypted);
And the output is:
<Buffer 94 fa a4 f4 a1 3c bf f6 d7 90 18 3f 3b db 3f b9>
94faa4f4a13cbff6d790183f3bdb3fb9:fae8b07a135e084eb91e
Code Snippet for decryption in JAVA:
public class Test {
public static void main(String[] args) throws Exception {
String s =
"94faa4f4a13cbff6d790183f3bdb3fb9:fae8b07a135e084eb91e";
String seed = "d6F3231q7d1942874322a#123nab#392";
decrypt(s, seed);
}
private static void decrypt(String s, String seed)
throws NoSuchAlgorithmException, NoSuchPaddingException, UnsupportedEncodingException, InvalidKeyException,
InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
String parts[] = s.split(":");
String ivString = parts[0];
String encodedString = parts[1];
Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding");
byte[] secretBytes = seed.getBytes("UTF-8");
IvParameterSpec ivSpec = new IvParameterSpec(hexStringToByteArray(ivString));
/*Removed after the accepted answer
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] thedigest = md.digest(secretBytes);*/
SecretKeySpec skey = new SecretKeySpec(thedigest, "AES");
cipher.init(Cipher.DECRYPT_MODE, skey, ivSpec);
byte[] output = cipher.doFinal(hexStringToByteArray(encodedString));
System.out.println(new String(output));
}
}
Output: �s˸8ƍ�
I am getting some junk value in the response. Tried a lot of options, but none of them seem to be working. Any lead/help is appreciated.
In your JS code, you're using the 32-character string d6F3231q7d19428743234#123nab#234 directly as the AES key, with each ASCII character directly mapped to a single key byte.
In the Java code, you're instead first hashing the same string with MD5, and then using the MD5 output as the AES key. It's no wonder that they won't match.
What you probably should be doing, in both cases, is either:
randomly generating a string of 32 bytes (most of which won't be printable ASCII characters) and using it as the key; or
using a key derivation function (KDF) to take an arbitrary input string and turn it into a pseudorandom AES key.
In the latter case, if the input string is likely to have less than 256 bits of entropy (e.g. if it's a user-chosen password, most of which only have a few dozen bits of entropy at best), then you should make sure to use a KDF that implements key stretching to slow down brute force guessing attacks.
Ps. To address the comments below, MD5 outputs a 16-byte digest, which will yield an AES-128 key when used as an AES SecretKeySpec. To use AES-256 in Java, you will need to provide a 32-byte key. If trying to use a 32-byte AES key in Java throws an InvalidKeyException, you are probably using an old version of Java with a limited crypto policy that does not allow encryption keys longer than 128 bits. As described this answer to the linked question, you will either need to upgrade to Java 8 update 161 or later, or obtain and install an unlimited crypto policy file for your Java version.
In the Java code you are taking the MD5 hash of secret before using it as a key:
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] thedigest = md.digest(secretBytes);
SecretKeySpec skey = new SecretKeySpec(thedigest, "AES");
Whereas, in your NodeJS code, you don't do this anywhere. So you're using two different keys when encrypting and decrypting.
Don't copy and paste code without understanding it. Especially crypto code.
Faced with the same task (but with 128, it easy to adapt for 256), here is working Java/NodeJs code with comments.
It's additionally wrapped to Base64 to readability, but it's easy to remove if you would like.
Java side (encrypt/decrypt) :
import java.lang.Math; // headers MUST be above the first class
import java.util.Base64;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.nio.charset.StandardCharsets;
// one class needs to have a main() method
public class MyClass
{
private static void log(String s)
{
System.out.print("\r\n"+s);
}
public static SecureRandom IVGenerator() {
return new SecureRandom();
}
// arguments are passed using the text field below this editor
public static void main(String[] args)
{
String valueToEncrypt = "hello, stackoverflow!";
String key = "3e$C!F)H#McQfTjK";
String encrypted = "";
String decrypted = "";
//ENCODE part
SecureRandom IVGenerator = IVGenerator();
byte[] encryptionKeyRaw = key.getBytes();
//aes-128=16bit IV block size
int ivLength=16;
byte[] iv = new byte[ivLength];
//generate random vector
IVGenerator.nextBytes(iv);
try {
Cipher encryptionCipher = Cipher.getInstance("AES/CTR/NoPadding");
encryptionCipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptionKeyRaw, "AES"), new IvParameterSpec(iv));
//encrypt
byte[] cipherText = encryptionCipher.doFinal(valueToEncrypt.getBytes());
ByteBuffer byteBuffer = ByteBuffer.allocate(ivLength + cipherText.length);
//storing IV in first part of whole message
byteBuffer.put(iv);
//store encrypted bytes
byteBuffer.put(cipherText);
//concat it to result message
byte[] cipherMessage = byteBuffer.array();
//and encrypt to base64 to get readable value
encrypted = new String(Base64.getEncoder().encode(cipherMessage));
} catch (Exception e) {
throw new IllegalStateException(e);
}
//END OF ENCODE CODE
log("encrypted and saved as Base64 : "+encrypted);
///DECRYPT CODE :
try {
//decoding from base64
byte[] cipherMessageArr = Base64.getDecoder().decode(encrypted);
//retrieving IV from message
iv = Arrays.copyOfRange(cipherMessageArr, 0, ivLength);
//retrieving encrypted value from end of message
byte[] cipherText = Arrays.copyOfRange(cipherMessageArr, ivLength, cipherMessageArr.length);
Cipher decryptionCipher = Cipher.getInstance("AES/CTR/NoPadding");
IvParameterSpec ivSpec = new IvParameterSpec(iv);
SecretKeySpec secretKeySpec = new SecretKeySpec(encryptionKeyRaw, "AES");
decryptionCipher.init(Cipher.DECRYPT_MODE,secretKeySpec , ivSpec);
//decrypt
byte[] finalCipherText = decryptionCipher.doFinal(cipherText);
//converting to string
String finalDecryptedValue = new String(finalCipherText);
decrypted = finalDecryptedValue;
} catch (Exception e) {
throw new IllegalStateException(e);
}
log("decrypted from Base64->aes128 : "+decrypted);
//END OF DECRYPT CODE
}
}
It could be easy be tested by online java compilers (this example prepared on https://www.jdoodle.com/online-java-compiler).
NodeJs decrypt side :
const crypto = require('crypto');
const ivLength = 16;
const algorithm = 'aes-128-ctr';
const encrypt = (value, key) => {
//not implemented, but it could be done easy if you will see to decrypt
return value;
};
function decrypt(value, key) {
//from base64 to byteArray
let decodedAsBase64Value = Buffer.from(value, 'base64');
let decodedAsBase64Key = Buffer.from(key);
//get IV from message
let ivArr = decodedAsBase64Value.slice(0, ivLength);
//get crypted message from second part of message
let cipherTextArr = decodedAsBase64Value.slice(ivLength, decodedAsBase64Value.length);
let cipher = crypto.createDecipheriv(algorithm, decodedAsBase64Key, ivArr);
//decrypted value
let decrypted = cipher.update(cipherTextArr, 'binary', 'utf8');
decrypted += cipher.final('utf8');
return decrypted;
}
I want to use a barcode (code 39) to represent a string, and I want this string to be encrypted using AES.
However, I can only display 43 characters with the barcode. How can I encrypt it so that the result uses only the available set of characters?
Here's what I have so far:
public static byte[] encryptAES(String seed, String cleartext)
throws Exception {
byte[] rawKey = getRawKey(seed.getBytes("ASCII"));
SecretKeySpec skeySpec = new SecretKeySpec(rawKey, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/NOPADDING");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
return cipher.doFinal(cleartext.getBytes("ASCII"));
}
private static byte[] getRawKey(byte[] seed) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
sr.setSeed(seed);
kgen.init(BLOCKS, sr); // 192 and 256 bits may not be available
SecretKey skey = kgen.generateKey();
byte[] raw = skey.getEncoded();
return raw;
}
public static void main(String [] args)
{
String str = "312432432";
String key = "4AFJ3243J";
String result = new String(encryptAES(key,str), "ASCII");
}
Thanks!
What you have is an encoding issue, the problem being you want to convert to a non-standard encoding. What I would do is convert to a base43 encoding. However, you will likely need to implement your own conversion. You should look into how to convert between arbitrary bases, and do the conversion on the byte output of the encryption. Essentially you will take the base10 value of the byte (between 0 and 255 if unsigned), and convert it to two different base43 characters.
A quick Google search for base43 gave me this. Which I haven't used myself, but looks like it could work.
I am using the code in below mentioned post to encrypt and decrypt values between Java and Java script module of my application.
Compatible AES algorithm for Java and Javascript
In a above post they are using 128 bit key value. I want to use my own key instead of hard coding the 128 bit key value.
My question is that can I convert any random string into 128 bit key value.
Please post some examples if it is possible to convert any string into 128 bit value.
Characters are represented with 8 bits. hence to form 128 bit key, create a string having 16 chars (16*8=128), e.g. "abcdefgh12345678".
to mask this key as base64, you may use Apache commons-codec Base64.encodeBase64... #see http://commons.apache.org/proper/commons-codec/apidocs/org/apache/commons/codec/binary/Base64.html
Something I fount by google, and use in my project:
private final static String algorithm = "PBKDF2WithHmacSHA1";
private final static String HEX = "0123456789ABCDEF";
private static final String CP_ALGORITH = "AES";
private static final String CP_KEY = "PUTsomeKEYinHere";
public static String cipher(String cipherKey, String data) throws NoSuchAlgorithmException,
InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException,
IllegalBlockSizeException, BadPaddingException {
SecretKeyFactory skf = SecretKeyFactory.getInstance(algorithm);
KeySpec spec = new PBEKeySpec(cipherKey.toCharArray(), cipherKey.getBytes(), 128, 256);
SecretKey tmp = skf.generateSecret(spec);
SecretKey key = new SecretKeySpec(tmp.getEncoded(), CP_ALGORITH);
Cipher cipher = Cipher.getInstance(CP_ALGORITH);
cipher.init(Cipher.ENCRYPT_MODE, key);
return toHex(cipher.doFinal(data.getBytes()));
}
public static String decipher(String cipherKey, String data) throws NoSuchAlgorithmException,
InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException,
IllegalBlockSizeException, BadPaddingException {
SecretKeyFactory skf = SecretKeyFactory.getInstance(algorithm);
KeySpec spec = new PBEKeySpec(cipherKey.toCharArray(), cipherKey.getBytes(), 128, 256);
SecretKey tmp = skf.generateSecret(spec);
SecretKey key = new SecretKeySpec(tmp.getEncoded(), CP_ALGORITH);
Cipher cipher = Cipher.getInstance(CP_ALGORITH);
cipher.init(Cipher.DECRYPT_MODE, key);
return new String(cipher.doFinal(toByte(data)));
}
private static byte[] toByte(String data) throws NullPointerException{
int len = data.length()/2;
byte[] result = new byte[len];
for (int i = 0; i < len; i++)
result[i] = Integer.valueOf(data.substring(2*i, 2*i+2), 16).byteValue();
return result;
}
private static String toHex(byte[] doFinal) {
StringBuffer result = new StringBuffer(2*doFinal.length);
for (int i = 0; i < doFinal.length; i++) {
result.append(HEX.charAt((doFinal[i]>>4)&0x0f)).append(HEX.charAt(doFinal[i]&0x0f));
}
return result.toString();
}
usage:
cipher(CP_KEY, STRINGtoCIPHER);
decipher(CP_KEY, YOURcipheredSTRING)
I put that all in a shared class with static fields and methods, so i can use it everywhere in my app. I use it to store SessionID i shared preferences, and it works nice.
I'm testing my Hmac with test vectors from https://www.rfc-editor.org/rfc/rfc4231
But on test case 3 "Test with a combined length of key and data that is larger than 64 bytes (= block-size of SHA-224 and SHA-256)." I get a different digest than the correct one.
byte[] key = hexify("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
byte[] data = hexify("dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd");
byte[] correct = hexify("773ea91e36800e46854db8ebd09181a72959098b3ef8c122d9635514ced565fe");
// Create digest
SecretKey macKey = new SecretKeySpec(key, "HmacSHA256");
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(macKey);
byte[] digest = mac.doFinal(data);
Any idea why they become different? What did I miss? I'm very new to this.
// Hex encoded
a5418172bb54bf71f3ec28d1c9f34c48da17007eac4d0ca9e2f8ab54b91603e8
773ea91e36800e46854db8ebd09181a72959098b3ef8c122d9635514ced565fe
I can't reproduce your issue. For me, the following SSCCE works just fine:
public static void main(String[] args) throws Exception {
byte[] key = hexify("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
byte[] data = hexify("dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd");
byte[] correct = hexify("773ea91e36800e46854db8ebd09181a72959098b3ef8c122d9635514ced565fe");
// Create digest
SecretKey macKey = new SecretKeySpec(key, "HmacSHA256");
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(macKey);
byte[] digest = mac.doFinal(data);
System.out.println(Arrays.equals(correct, digest));
}
private static byte[] hexify(String string) {
return DatatypeConverter.parseHexBinary(string);
}
Prints: true
Perhaps an error in your display or comparison code?