AES Encryption by Java code and decryption by using OpenSSL (terminal) - java

I am able to encrypt the data in the file using below mentioned Java code. But when I try to decrypt the encrypted file using OpenSSL from the command line then I am not be able to do that.
I tried the command
openssl enc -aes-256-cbc -d -in file_05.encrypt.txt -out file_05.decrypt.txt
It asked for a password -
enter aes-256-cbc decryption password:
I entered the password as "helloworld",
Then in the terminal it shows a "bad magic number" error message.
String pwd = "helloworld";
String SALT_VALUE = "12345#salt";
private String algorithm = "PBEWITHSHA256AND256BITAES-CBC-BC";
String finalTxt = "Hi, Goof After noon All.";
char[] pwd = Crypt.password.toCharArray();
SecretKey originalKey = Crypt.generateSK(pwd);
byte[] cipherText = Crypt.encrypt(finalTxt.getBytes(),SALT_VALUE.getBytes(), originalKey);
public static SecretKey generateSK(char[] passPhrase) throws NoSuchAlgorithmException,
InvalidKeySpecException,
NoSuchPaddingException,
InvalidAlgorithmParameterException,
InvalidKeyException {
PBEKeySpec pbeKeySpec = new PBEKeySpec(passPhrase);
SecretKeyFactory secretKeyFactory;
secretKeyFactory = SecretKeyFactory.getInstance(algorithm);
return secretKeyFactory.generateSecret(pbeKeySpec);
}
public static byte[] encrypt(byte[] image, byte[] salt, SecretKey sKey) throws InvalidKeyException,
IllegalBlockSizeException,
BadPaddingException,
InvalidKeySpecException,
UnsupportedEncodingException,
InvalidAlgorithmParameterException {
Cipher cipher;
try {
cipher = getCipher(Cipher.ENCRYPT_MODE, salt, sKey);
return cipher.doFinal(image);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static Cipher getCipher(int mode, #NonNull byte[] salt, #NonNull SecretKey secretKey) throws Exception {
PBEParameterSpec pbeParamSpecKey = new PBEParameterSpec(salt, 1000);
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(mode, secretKey, pbeParamSpecKey);
return cipher;
}

It asked for a password - enter aes-256-cbc decryption password: I entered the password as "helloworld",
Then in the terminal it shows a "bad magic number" error message
Openssl uses by default its internal EVP_BytesToKey function to generate key and IV from provided password and salt. Just search on internet to find Java implementation if needed.
By default Openssl expect format Salted__<8bit_salt><ciphertext> if you don't provide key and IV directly.
I try to decrypt the encrypted file using OpenSSL from the command line then I am not be able to do that
I am not sure what your Crypt class is implemented, you may try to print hex encoded key and iv. The using openssl with parameters -iv <hex_IV> -K <hex_key> you can directly provide the IV and Key value to decrypt the ciphertext

It seems like you are missing header expected by openssl - string Salted__, followed by 8 bytes salt, followed by ciphertext.

Related

How to encrypt and decrypt AES-256-cbc in Java like openssl with given key and IV

First problem:
I have encrypted text by openssl, in the first step i generated key
openssl enc -aes-256-cbc -nosalt -k abcdefghasd -P -md sha256
generated output
key=E640008145BBB4B8DEF141BBF20301C2017D3DB7ABE56DEBCF95D412B03B61F2
iv =868CB4028A265D33B0EAE131EF72F3AB
then i try encrypt password using
openssl enc -aes-256-cbc -k E640008145BBB4B8DEF141BBF20301C2017D3DB7ABE56DEBCF95D412B03B61F2 -iv 868CB4028A265D33B0EAE131EF72F3AB -base64 <<< hashingpassword
In the next step i try decrypt this in Java
public String decrypt(String encryptedPassword) {
try {
String myKey = "E640008145BBB4B8DEF141BBF20301C2017D3DB7ABE56DEBCF95D412B03B61F2";
byte[] decodeKey = Hex.decodeHex(myKey.toCharArray());
SecretKeySpec key = new SecretKeySpec(decodeKey, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(Hex.decodeHex("868CB4028A265D33B0EAE131EF72F3AB")));
return new String(cipher.doFinal(Base64.getDecoder().decode(encryptedPassword)));
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
And i got error:
java.lang.IllegalStateException: javax.crypto.BadPaddingException: Given final block not properly padded. Such issues can arise if a bad key is used during decryption
What im doing wrong?
I'm new to the chapter on encryption
Problem is resolved by uppercase K in openssl command encryption

AES GCM encryption and decryption in JAVA

I am trying to implement AES/GCM/NoPadding encryption and decryption in JAVA .. the key used is a shared key from the public key of the receiver and the private key of the sender (ECDH).. encryption works well (with and without iv). However, I am unable to decrypt...
I get the exception: javax.crypto.BadPaddingException: mac check in GCM failed
public static String encryptString(SecretKey key, String plainText) throws NoSuchProviderException, NoSuchAlgorithmException, NoSuchPaddingException, UnsupportedEncodingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
//IvParameterSpec ivSpec = new IvParameterSpec(iv);
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding", "BC");//AES/ECB/PKCS5Padding //"AES/GCM/NoPadding", "BC"
byte[] plainTextBytes = plainText.getBytes("UTF-8");
byte[] cipherText;
//cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
cipher.init(Cipher.ENCRYPT_MODE, key);
return new String(Base64.getEncoder().encode(cipher.doFinal(plainTextBytes)));
}
public static String decryptString(SecretKey key, String
cipherText) throws NoSuchProviderException,
NoSuchAlgorithmException, NoSuchPaddingException,
InvalidKeyException, InvalidAlgorithmParameterException,
IllegalBlockSizeException, BadPaddingException,
UnsupportedEncodingException, ShortBufferException {
Key decryptionKey = new SecretKeySpec(key.getEncoded(),
key.getAlgorithm());
IvParameterSpec ivSpec = new IvParameterSpec(ivString.getBytes("UTF-8"));
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding", "BC");//AES/GCM/NoPadding", "BC");
cipher.init(Cipher.DECRYPT_MODE, decryptionKey, ivSpec);
return new String (Base64.getEncoder().encode(cipher.doFinal(Base64.getDecoder().decode(cipherText.getBytes()))));
}
You must use exactly the same IV for encryption and decryption of the same ciphertext and it must be different for each encryption that produces different ciphertexts. The IV is not secret, so you can send it along with the ciphertext. Usually, it is simply prepended to the ciphertext and sliced off before decryption.
You need to supply an instance of GCMParameterSpec (which includes the IV) for both of the Cipher.init calls. As has already been pointed out, the IV has to be the same for both encryption and decryption, and must be unique.

javax.crypto.BadPaddingException AES

I am using AESCrypt (gradle :compile 'com.scottyab:aescrypt:0.0.1')
to encrypt and decrypt the data.
TextView tv=(TextView)findViewById(R.id.demotext);
String encrypted="",decrypted="";
try {
encrypted = AESCrypt.encrypt("password","This is the best thing to go by");
decrypted = AESCrypt.decrypt("password",encrypted);
} catch (GeneralSecurityException e) {
e.printStackTrace();
}
System.out.println("EncryptedData:"+encrypted);
System.out.println("DecryptedData:"+decrypted);
tv.setText("Encrypted:"+encrypted +"\n"+"Decrypted:"+decrypted);
The code works perfectly fine in this case, I get the same input as decrypted text.
But, when I try to use already encrypted string using the same method (AES) from the site http://aesencryption.net/ as shown in the screenshot:
And copy paste that encrypted text like:
decrypted = AESCrypt.decrypt("password","sttA+FbNm3RkTovjHI8CcAdStXiMl45s29Jqle+y+pA=");
And then run the code then I get error saying :
javax.crypto.BadPaddingException: error:1e06b065:Cipher functions:EVP_DecryptFinal_ex:BAD_DECRYPT
But when I use the decrypted text into the same site it works fine as shown in the screenshot below.
private static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decrypted = cipher.doFinal(encrypted);
return decrypted;
}
Probably due to the algorithm to convert the passphrase 'password' to SecretKeySpec
This is the algorithm in AESCrypt
private static SecretKeySpec GenerateKey (final String password) throws NoSuchAlgorithmException, UnsupportedEncodingException {    
final MessageDigest digest = MessageDigest.getInstance (HASH_ALGORITHM);
byte [] bytes = password.getBytes ("UTF-8");
digest.update (bytes, 0, bytes.length);
byte [] key = digest.digest ();
log ("SHA-256 key" key);
SecretKeySpec secretKeySpec = new SecretKeySpec (key, "AES");
secretKeySpec return;
}
And this is the (Java) example aesencryption.net
sha = MessageDigest.getInstance ("SHA-1");
key = sha.digest (key);
key = Arrays.copyOf (key, 16); // Use only first 128 bit
SecretKey = new SecretKeySpec (key, "AES");
The first one applies SHA256 hashing, and the second SHA-1 after completing up to 16 bytes, so the key is different.
I think you are encrypting and decrypting AES in the right way. You do not need to change anything.
But if you want to be compatible with aesencryption.net, you need to implement the same key generation algorithm. The code is not too good. I try to summarize
//Code from aesencryption.net
// Generate key
MessageDigest sha = null;
key = myKey.getBytes ("UTF-8");
sha = MessageDigest.getInstance ("SHA-1");
key = sha.digest (key);
key = Arrays.copyOf (key, 16); // Use only first 128 bit
SecretKey = new SecretKeySpec (key, "AES");
public static String encrypt (String strToEncrypt) {
Cipher cipher = Cipher.getInstance ("AES / ECB / PKCS5Padding");
     cipher.init (Cipher.ENCRYPT_MODE, SecretKey);
Base64.encodeBase64String return (cipher.doFinal (strToEncrypt.getBytes ("UTF-8"))));
}
public static String decrypt (String strToDecrypt) {
Cipher cipher = Cipher.getInstance ("AES / ECB / PKCS5PADDING");
cipher.init (Cipher.DECRYPT_MODE, SecretKey);
return new String (cipher.doFinal (Base64.decodeBase64 (strToDecrypt))));
}
I can also provide my own code extracted from an Android app witch requires to store private user data. Data is ciphered with an AES key protected with an user passphrase
public static String SIMMETRICAL_ALGORITHM = "AES";
//Generate cipher key with user provided password
private static String getPassphraseSize16(String key) {
if (TextUtils.isEmpty(key)) {
return null;
}
char controlChar = '\u0014';
String key16 = key + controlChar;
if (key16.length() < 16) {
while (key16.length() < 16) {
key16 += key + controlChar;
}
}
if (key16.length() > 16) {
key16 = key16.substring(key16.length() - 16, key16.length());
}
return key16;
}
//AES cipher with passphrase
public static byte[] encrypt(byte[] message, String passphrase)
throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
String passphrase16 = getPassphraseSize16(passphrase);
SecretKeySpec secretKey = new SecretKeySpec(passphrase16.getBytes(), SIMMETRICAL_ALGORITHM);
Cipher cipher = Cipher.getInstance(SIMMETRICAL_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encoded = cipher.doFinal(message);
return encoded;
}
//AES decipher with passphrase
public static byte[] decrypt(byte[] encodedMessage, String key) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
String passphrase16 = getPassphraseSize16(key);
SecretKeySpec secretKey = new SecretKeySpec(passphrase16.getBytes(), SIMMETRICAL_ALGORITHM);
Cipher cipher = Cipher.getInstance(SIMMETRICAL_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte decoded[] = cipher.doFinal(encodedMessage);
return decoded;
}

javax.crypto.BadPaddingException : Decryption error

I am trying to implement an RSA based encryption communication between my client and server. For this I generated RSA public and private keys using openssl in the following way :
openssl genrsa -out private.pem 2048
openssl rsa -in private.pem -outform PEM -pubout -out public.pem
--generate modulus and exponent
openssl rsa -pubin -in public_key.pem -modulus -noout
openssl rsa -pubin -in public_key.pem -text -noout
Using the above files, encryption is done on the Android side as follows :
public static byte[] encrypt(BigInteger modulus, BigInteger exp, byte[] data) {
try {
KeyFactory kf = KeyFactory.getInstance("RSA");
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(modulus, exp);
PublicKey publicKey = kf.generatePublic(keySpec);
final Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return cipher.doFinal(data);
} catch (Exception e) {
FileLog.e("module" , e);
}
return null;
}
This works fine and does encrypt the data. Now on the server side, I used the following code to decrypt. The private key is stored as a pkcs8 format key and that is read by java.
public static byte[] decrypt(byte[] data) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException{
String fileName = "location/of/private_key/file";
File f = new File(fileName);
FileInputStream fis = new FileInputStream(f);
DataInputStream dis = new DataInputStream(fis);
byte[] keyBytes = new byte[(int)f.length()];
dis.readFully(keyBytes);
dis.close();
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
PrivateKey rsaPrivate = kf.generatePrivate(spec);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, rsaPrivate);
return cipher.doFinal(data);
}
On running this using eclipse on the server, I get the BadPaddingException: Decryption error problem. The length of the data is exactly 256 bytes and hence the length should not be an issue.
Any help would be truly helpful.
Thanks
Android using different padding algorithm. You need to use other algorithm like below:
Cipher CheckCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
There are quit number of posts out there.
You can refer
RSA BadPaddingException in Java - encrypt in Android decrypt in JRE
RSA Encryption: Difference between Java and Android

Is this a safe way to use java to encrypt (using public private key) messages that might be sent across insecure networks

I am not an expert on this so I need to defer to an expert. Is the following example a reasonably secure way to encrypt and decrypt a message (of an unknown length) for transmission a potentially insecure network (i.e. Email, HTTP requests, or other means). By "reasonably secure" I mean, would prevent a casual, or semi determined third party from reading the message.
Encrypt a message with a random AES key, and protect AES key by encrypting it with a public key.
public static String encrypt(String data, PublicKey publicKey) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
// Create AES secret key
Cipher aes = Cipher.getInstance("AES");
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(256);
SecretKey key = kgen.generateKey();
SecretKeySpec aeskeySpec = new SecretKeySpec(key.getEncoded(), "AES");
// Encrypt data with AES Secret key
aes.init(Cipher.ENCRYPT_MODE, aeskeySpec);
byte[] dataEncoded = aes.doFinal(data.getBytes());
// Encrypt the secret AES key with the public key
Cipher rsa = Cipher.getInstance("RSA");
rsa.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] aesKeyEncoded = rsa.doFinal(key.getEncoded());
// Output both secret AES key and data
return
Base64.getEncoder().encodeToString(aesKeyEncoded) + "~" +
Base64.getEncoder().encodeToString(dataEncoded);
}
Decrypt the AES secret key, and then decrypt the message:
public static String decrypt(String data, PrivateKey privateKey) throws InvalidKeyException, NoSuchPaddingException, NoSuchAlgorithmException, BadPaddingException, IllegalBlockSizeException {
String[] parts = data.split("~");
// Decrypt AES secret key
byte[] encodedSecretKey = Base64.getDecoder().decode(parts[0]);
Cipher rsa = Cipher.getInstance("RSA");
rsa.init(Cipher.DECRYPT_MODE, privateKey);
byte[] decodedSecretKey = rsa.doFinal(encodedSecretKey);
SecretKeySpec key = new SecretKeySpec(decodedSecretKey, "AES");
// Decrypt message
Cipher aes = Cipher.getInstance("AES");
aes.init(Cipher.DECRYPT_MODE, key);
byte[] decodedData = aes.doFinal(Base64.getDecoder().decode(parts[1]));
return new String(decodedData);
}
Using the above methods:
public static void main(String args[]) throws NoSuchAlgorithmException, BadPaddingException, NoSuchPaddingException, IllegalBlockSizeException, InvalidKeyException {
// Generate public/private key
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
generator.initialize(2048, new SecureRandom());
KeyPair kp = generator.generateKeyPair();
System.out.println(" Public key = " + Base64.getEncoder().encodeToString(kp.getPublic().getEncoded()));
System.out.println("Private key = " + Base64.getEncoder().encodeToString(kp.getPrivate().getEncoded()));
String mytext = "test message with some test data.";
String e = encrypt(mytext, kp.getPublic());
String d = decrypt(e, kp.getPrivate());
System.out.println(" text = " + mytext);
System.out.println("Decoded text = " + d);
}
As long as you can trust the RSA public key the general idea is OK. If you just send the public key to the other side, then it is not.
You also need to protect your ciphertext by adding integrity and authenticity. You can easily do this by switching to AES / GCM mode (which is only available in Java 8, or using Bouncy Castle). Currently you are using the unsafe AES / ECB mode of encryption.
You should try and use RSA with OAEP padding, instead of PKCS#1 v1.5 padding. In general, you should not rely on default character encodings (getBytes()) or cipher modes.
So in the end: no, that's not secure. Try and use TLS is you want to avoid the many pitfalls.

Categories

Resources