Java Password based Encryption decrypt throwing errors - java

I am trying to write a program that will encrypt a file based on a password the user enters when calling the program. The salt of the password should be included in the file. I believe the program is encrypting the file properly but when I go to decrypt the file the program throws
java.security.InvalidAlgorithmParameterException: Missing parameter type: IV expected.
I am not sure as to why this would be the case as I am not generating an IV as such. To call the program it is enc "password" fileToEncrypt.txt destinationFile.enc.
import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.util.HexFormat;
import java.util.logging.Logger;
public class FileEncryptor {
private static final Logger LOG = Logger.getLogger(FileEncryptor.class.getSimpleName());
private static final String ALGORITHM = "AES";
private static final String CIPHER = "AES/CBC/PkCS5PADDING";
public static void main(String[] args) {
if (args.length == 4) {
if (args[0].equals("enc") || args[0].equals("dec")) {
try {
if (args[0].equals("enc")) {
SecureRandom sr = new SecureRandom();
PBEKeySpec pbeKeySpec;
PBEParameterSpec pbeParamSpec;
SecretKeyFactory keyFac;
byte[] salt = new byte[16];
sr.nextBytes(salt);
int count = 1000;
pbeParamSpec = new PBEParameterSpec(salt, count);
char[] password = args[1].toCharArray();
pbeKeySpec = new PBEKeySpec(password);
keyFac = SecretKeyFactory.getInstance("PBEWithHmacSHA256AndAES_256");
SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);
Cipher pbeCipher = Cipher.getInstance("PBEWithHmacSHA256AndAES_256");
pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);
if (encrypt(pbeCipher, args[2], args[3],salt)) {
LOG.info("Encryption finished, saved at " + args[3]);
}
} else {
PBEKeySpec pbeKeySpec;
SecretKeyFactory keyFac;
char[] password = args[1].toCharArray();
pbeKeySpec = new PBEKeySpec(password);
keyFac = SecretKeyFactory.getInstance("PBEWithHmacSHA256AndAES_256");
SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);
Cipher pbeCipher = Cipher.getInstance("PBEWithHmacSHA256AndAES_256");
if (decrypt(pbeCipher, pbeKey, args[2], args[3])) {
LOG.info("Decryption complete, open " + args[3]);
}
}
} catch (Exception e) {
exceptionHandle(e);
}
} else {
errorHandle("Please call encrypt or decrypt");
}
} else {
errorHandle("Please call program with 4 arguments");
}
}
/**
* Method to encrypt a file with the Key and IV generated by the program and write the results to a
* new file.
*
* #param cipher cipher generated by the program early
* #param input name of the file to be encrypted
* #param output name of the new file after encryption
* #return boolean if encryption was successful or not.
*/
public static boolean encrypt(Cipher cipher, String input, String output,byte[] salt) {
LOG.info("File to be Encrypted: " + input);
try (FileInputStream in = new FileInputStream(input);
FileOutputStream out = new FileOutputStream(output);
CipherOutputStream encryptedOutputStream = new CipherOutputStream(out, cipher)) {
out.write(salt);
byte[] buffer = new byte[1024];
int nread;
while ((nread = in.read(buffer)) > 0) {
encryptedOutputStream.write(buffer, 0, nread);
}
encryptedOutputStream.flush();
} catch (IOException e) {
exceptionHandle(e);
}
return true;
}
/**
* Method to decrypt a file with the Key inputted by the user and IV stored in the file. Then write the results to a
* new file.
*
* #param cipher cipher generated by the program early based on key and IV provided.
* #param input name of the file to be decrypted
* #param output name of the new file after decryption
* #return boolean if decryption was successful or not
*/
public static boolean decrypt(Cipher cipher,SecretKey pbeKey, String input, String output) {
int count = 1000;
try (FileInputStream in = new FileInputStream(input);
CipherInputStream cipherInputStream = new CipherInputStream(in, cipher);
FileOutputStream out = new FileOutputStream(output)) {
byte[] salt = new byte[16];
in.read(salt);
byte[] buffer = new byte[1024];
cipher.init(Cipher.DECRYPT_MODE, pbeKey,new PBEParameterSpec(salt, count));
int nread;
while ((nread = cipherInputStream.read(buffer)) > 0) {
out.write(buffer, 0, nread);
}
out.flush();
} catch (IOException | InvalidAlgorithmParameterException | InvalidKeyException ex) {
ex.printStackTrace();
exceptionHandle(ex);
return false;
}
return true;
}
/**
* Methods prints a message to the console to let the user know what mistakes they made when running the program.
*
* #param message to be printed to the console.
*/
public static void errorHandle(String message) {
System.out.println(message);
}
/**
* Program prints a message to the user to let them know what went wrong in the program based on what exception
* was thrown early in the program and give them clear understanding of what went wrong.
*
* #param e Exception caught be the program
*/
public static void exceptionHandle(Exception e) {
if(e.getClass() == BadPaddingException.class){
System.out.println("hello");
LOG.info("Please input correct key. " + e.getMessage());
}
if (e.getClass() == FileNotFoundException.class) {
LOG.info("Please call enc or dec with an existing file. " + e.getMessage());
}
if (e.getClass() == InvalidKeyException.class) {
LOG.info("Please put correct Algorithm. " + e.getMessage());
}
if (e.getClass() == NoSuchAlgorithmException.class) {
LOG.info("Please put correct Cipher " + e.getMessage());
}
if (e.getClass() == InvalidAlgorithmParameterException.class) {
LOG.info("Please put correct IV length. " + e.getMessage());
}
if (e.getClass() == IllegalArgumentException.class) {
LOG.info("Please check length Key and IV. " + e.getMessage());
}
if (e.getClass() == NoSuchPaddingException.class) {
LOG.info("Please check Padding. " + e.getMessage());
}
}
public static String bytesToHex(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
sb.append(String.format("%02X ", b));
}
return sb.toString();
}
}

Related

Plain text encrypt from Dart code but decrypt from Java code

When I encrypt plain text using Dart,and encrypted text is decrypted from Java code, I get this error:
javax.crypto.BadPaddingException: pad block corrupted
at org.bouncycastle.jcajce.provider.symmetric.util.BaseBlockCipher$BufferedGenericBlockCipher.doFinal(Unknown Source)
at org.bouncycastle.jcajce.provider.symmetric.util.BaseBlockCipher.engineDoFinal(Unknown Source)
at javax.crypto.Cipher.doFinal(Cipher.java:2168)
at AesUtil.doFinal(AesUtil.java:75)
at AesUtil.decrypt(AesUtil.java:60)
at Main.main(Main.java:18)
Same IV, salt and passphase value using Java side for key generation, but the generated key is different and also cipher test is different. I am using same method for key generation. I don't know what is missing in Dart code.
dependencies:
encrypt: ^5.0.1
hex: ^0.2.0
password_hash_plus: ^4.0.0
Dart code is:
var random = Random.secure();
var values = List<int>.generate(16, (i) => random.nextInt(255));
// final salt = aes.IV.fromSecureRandom(16);
final salt = hex.encode(values);
final generator = PBKDF2(hashAlgorithm: sha1);
final key = aes.Key.fromBase64(generator.generateBase64Key("1234567891234567", salt, 1000, 16));
final iv = aes.IV.fromSecureRandom(16);
final encrypter =
aes.Encrypter(aes.AES(key, mode: aes.AESMode.cbc, padding: 'PKCS7'));
final encrypted = encrypter.encrypt(st.password!, iv: iv);
var str = '${iv.base16}::${salt}::${encrypted.base64}';
var bytes = utf8.encode(str);
var base64Str = base64.encode(bytes);
//final decrypt = encrypter.decrypt64("/vvAYMc3rgCvPvuSVU/qQw==", iv: iv);
print(
'------------------------------,\n encrypt ${(encrypted.base64)}-----------'
//'--\ndecrypted ${decrypt}-----------base64--------$base64Str-----'
'\nkey = ${key.base64} array--\niv = ${iv.base16}--salt= {${salt}');
And Java code is:
class Main {
public static void main(String[] args) {
AesUtil aesUtil = new AesUtil();
String encrypt = aesUtil.encrypt("b9266c74df614967d9acaa2878bff87c", "6ab7c799d6411f9d0c8e048ad526eeee", "1234567891234567", "Jitu#123456");
String a = aesUtil.decrypt("01e6a073a4255c92e704bd94d76d75c5", "98a21e07ed34afc523c5f5938c9202db", "1234567891234567", "MumTfpnzZh9bk94yiTuA+g==");
System.out.println("encrypt = " + encrypt + " \ndecrpty valaue----" + a);
}
}
Encryption code in Java:
import java.io.UnsupportedEncodingException;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.util.Arrays;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
import org.springframework.stereotype.Component;
public class AesUtil {
private final int keySize;
private final int iterationCount;
private final Cipher cipher;
public AesUtil() {
this.keySize = 128;
this.iterationCount = 1000;
try {
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
} catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
e.printStackTrace();
throw fail(e);
} catch (NoSuchProviderException e) {
throw new RuntimeException(e);
}
}
public String encrypt(String salt, String iv, String passphrase, String plaintext) {
try {
SecretKey key = generateKey(salt, passphrase);
System.out.println("encryption key-------= " + base64(key.getEncoded()));
byte[] encrypted = doFinal(Cipher.ENCRYPT_MODE, key, iv, plaintext.getBytes("ISO-8859-1"));
return base64(encrypted);
} catch (UnsupportedEncodingException e) {
throw fail(e);
}
}
public String decrypt(String salt, String iv, String passphrase, String ciphertext) {
try {
SecretKey key = generateKey(salt, passphrase);
System.out.println("decrypt key-------= " + base64(key.getEncoded()));
byte[] decrypted = doFinal(Cipher.DECRYPT_MODE, key, iv, base64(ciphertext));
return new String(decrypted, "ISO-8859-1");
} catch (UnsupportedEncodingException e) {
return null;
} catch (Exception e) {
return null;
}
}
private byte[] doFinal(int encryptMode, SecretKey key, String iv, byte[] bytes) {
try {
IvParameterSpec IivParameterSpec = new IvParameterSpec(hex(iv));
System.out.println("----iv--= " + hex(IivParameterSpec.getIV()));
cipher.init(encryptMode, key, IivParameterSpec);
return cipher.doFinal(bytes);
} catch (InvalidKeyException
| InvalidAlgorithmParameterException
| IllegalBlockSizeException
| BadPaddingException e) {
e.printStackTrace();
return null;
}
}
private SecretKey generateKey(String salt, String passphrase) {
try {
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
byte[] s = hex(salt);
System.out.println("salt-= " + hex(s));
KeySpec spec = new PBEKeySpec(passphrase.toCharArray(), s, iterationCount, keySize);
SecretKey key = new SecretKeySpec(factory.generateSecret(spec).getEncoded(), "AES");
return key;
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
return null;
}
}
public static String random(int length) {
byte[] salt = new byte[length];
new SecureRandom().nextBytes(salt);
return hex(salt);
}
public static String base64(byte[] bytes) {
return Base64.encodeBase64String(bytes);
}
public static byte[] base64(String str) {
return Base64.decodeBase64(str);
}
public static String hex(byte[] bytes) {
return Hex.encodeHexString(bytes);
}
public static byte[] hex(String str) {
try {
return Hex.decodeHex(str.toCharArray());
} catch (DecoderException e) {
throw new IllegalStateException(e);
}
}
private IllegalStateException fail(Exception e) {
return null;
}
public static byte[][] GenerateKeyAndIV(int keyLength, int ivLength, int iterations, byte[] salt, byte[] password, MessageDigest md) {
int digestLength = md.getDigestLength();
int requiredLength = (keyLength + ivLength + digestLength - 1) / digestLength * digestLength;
byte[] generatedData = new byte[requiredLength];
int generatedLength = 0;
try {
md.reset();
// Repeat process until sufficient data has been generated
while (generatedLength < keyLength + ivLength) {
// Digest data (last digest if available, password data, salt if available)
if (generatedLength > 0)
md.update(generatedData, generatedLength - digestLength, digestLength);
md.update(password);
if (salt != null)
md.update(salt, 0, 8);
md.digest(generatedData, generatedLength, digestLength);
// additional rounds
for (int i = 1; i < iterations; i++) {
md.update(generatedData, generatedLength, digestLength);
md.digest(generatedData, generatedLength, digestLength);
}
generatedLength += digestLength;
}
// Copy key and IV into separate byte arrays
byte[][] result = new byte[2][];
result[0] = Arrays.copyOfRange(generatedData, 0, keyLength);
if (ivLength > 0)
result[1] = Arrays.copyOfRange(generatedData, keyLength, keyLength + ivLength);
return result;
} catch (DigestException e) {
throw new RuntimeException(e);
} finally {
// Clean out temporary data
Arrays.fill(generatedData, (byte) 0);
}
}
}
The decryption fails because in both codes different salts are used and therefore different keys are generated. Ultimately, this is due to an inappropriate design of the PBKDF2 implementation of the password_hash_plus Dart library.
In the Java code a random salt is applied, in this case 0xb9266c74df614967d9acaa2878bff87c. In main(), the salt is passed hex encoded to encrypt(), hex decoded in generateKey(), and the resulting byte sequence is used for key derivation.
The generateBase64Key() method of the password_hash_plus library, on the other hand, expects the salt as string and does a UTF-8 encoding internally, see here. Therefore, only salts that are UTF-8 decodable can be processed. This is generally not true for random salts, since these are corrupted by a UTF-8 decoding.
The hex encoding of the salt applied in the Dart code does not work either, of course, because generateBase64Key() does not perform a hex decoding internally but a UTF-8 encoding.
Since salts are generally random byte sequences, the design of the PBKDF2 implementation of the password_hash_plus library is unsuitable. Instead, an implementation is required where the salt is passed as byte sequence (Uint8List or List<int>), e.g. the PBKDF2 implementation of PointyCastle:
import 'package:pointycastle/export.dart';
import 'dart:typed_data';
...
final key = aes.Key(deriveKey("1234567891234567", Uint8List.fromList(values))); // Raw salt for key derivation!
final salt = hex.encode(values); // Hex encoded salt for output!
...
Uint8List deriveKey(String passphrase, Uint8List salt){
Uint8List passphraseBytes = Uint8List.fromList(utf8.encode(passphrase));
KeyDerivator derivator = PBKDF2KeyDerivator(HMac(SHA1Digest(), 64)); // 64 byte block size
Pbkdf2Parameters params = Pbkdf2Parameters(salt, 1000, 16); // 16 byte key size
derivator.init(params);
return derivator.process(passphraseBytes);
}
...
The Dart code returns salt and IV hex encoded and the ciphertext Base64 encoded. If this data is passed with these encodings to the decrypt() method of the Java code, decryption is successful.
Be aware that an iteration count of 1000 is generally too small for PBKDF2.

Looking for Java implementation for decrypting a message encrypted using openssl -aes-256-cbc -a -salt command?

I am looking for any sample java code that will decrypt the messages encrypted using "openssl enc -aes-256-cbc) -a -salt" command provided the key is known.
https://pastebin.com/YiwbCAW8
So far i was able to get the following java code that encrypts and also decrypts the message. But i am not able to decrypt the encrypted message using openssl command. Getting "Bad Magic Number" error. Any idea ?
Encrypt the message using the code >
Encrypt("sample text", "test$password") = "i+5zkPPgnDdV7fr/w8uHkw=="
Decrypt("i+5zkPPgnDdV7fr/w8uHkw==", "test$password") = "sample text"
Decrypt the message using openssl >
F:\cipher>echo i+5zkPPgnDdV7fr/w8uHkw== | openssl aes-256-cbc -a -salt -d
enter aes-256-cbc decryption password:
bad magic number
import java.security.spec.KeySpec;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
public class AES {
private static final byte[] SALT = {
(byte) 0xA9, (byte) 0x9B, (byte) 0xC8, (byte) 0x32,
(byte) 0x56, (byte) 0x35, (byte) 0xE3, (byte) 0x03
};
private static final int ITERATION_COUNT = 65536;
private static final int KEY_LENGTH = 256;
private Cipher ecipher;
private Cipher dcipher;
AES(String passPhrase) throws Exception {
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
KeySpec spec = new PBEKeySpec(passPhrase.toCharArray(), SALT, ITERATION_COUNT, KEY_LENGTH);
SecretKey tmp = factory.generateSecret(spec);
SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
ecipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
ecipher.init(Cipher.ENCRYPT_MODE, secret);
dcipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] iv = ecipher.getParameters().getParameterSpec(IvParameterSpec.class).getIV();
dcipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv));
}
public String encrypt(String encrypt) throws Exception {
byte[] bytes = encrypt.getBytes("UTF8");
byte[] encrypted = encrypt(bytes);
return Base64.getEncoder().encodeToString(encrypted);
}
public byte[] encrypt(byte[] plain) throws Exception {
return ecipher.doFinal(plain);
}
public String decrypt(String encrypt) throws Exception {
byte[] bytes = Base64.getDecoder().decode(encrypt);
byte[] decrypted = decrypt(bytes);
return new String(decrypted, "UTF8");
}
public byte[] decrypt(byte[] encrypt) throws Exception {
return dcipher.doFinal(encrypt);
}
public static void main(String[] args) throws Exception {
String message = "sample text";
String password = "test$password";
AES encrypter = new AES(password);
String encrypted = encrypter.encrypt(message);
String decrypted = encrypter.decrypt(encrypted);
System.out.println("Encrypt(\"" + message + "\", \"" + password + "\") = \"" + encrypted + "\"");
System.out.println("Decrypt(\"" + encrypted + "\", \"" + password + "\") = \"" + decrypted + "\"");
}
}
You may search stackoverflow for many similar questions.
you have multiple issues in your code:
You use different keys:
In Java you use PBKDF2 to generate an encryption key from the provided password. Openssl uses its EVP_BytesToKey. Search internet for Java implementation. Please note the hash used in the EVP_BytesToKey changed with some openssl version (from MD5 to SHA-1 SHA-256), if someone is having more details, please comment
And you use random IV. you don't pass the IV along the ciphertext, so you may be able to decrypt the ciphertext with the same cipher instance (kkeping the same iv), but lets try your Java code to decrypt your ciphertext other time or with other instance, it won't work. You need to pass IV along the ciphertext (usually it's prepended)
Openssl expect following format:
Salted_<8 byte salt>ciphertext
Salted__<8 byte salt>ciphertext
8 byte salt is a random byte array used to generate the encryption key and IV from the provided password. Try encrypt with openssl with -pparameter, it will print the salt, IV and Key generated so you can check and compare
Using CBC without any integrity check (hmac, ..) may be unsafe in many implementations
Suggestions:
you can find an openssl java library implementing the same required (EVP_BytesToKey)
you can implement EVP_BytesToKey yourself
you can use openssl directly with -K/-ivparameters providing the encryption key and IV (in hex format) instead of password, then openssl expects pure ciphertext (no Salted_ or salt inside the input)
Thanks a lot for the clues. As mentioned, did some search and modified the code from one of the post. I have seen similar code with EVP_BytesToKeys in many places, but took some time to figure out the usage. I am able to decrypt the msg encrypted by openssl.
Trying to search the code for encryption as well. Meanwhile any help of encryption is appreciated as well.
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
public class AES5 {
private static final Charset ASCII = Charset.forName("ASCII");
private static final int INDEX_KEY = 0;
private static final int INDEX_IV = 1;
private static final int ITERATIONS = 1;
private static final int SALT_OFFSET = 8;
private static final int SALT_SIZE = 8;
private static final int CIPHERTEXT_OFFSET = SALT_OFFSET + SALT_SIZE;
private static final int KEY_SIZE_BITS = 256;
/**
* Thanks go to Ola Bini for releasing this source on his blog. The source was
* obtained from here
*
*/
public static byte[][] EVP_BytesToKey(int key_len, int iv_len, MessageDigest md, byte[] salt, byte[] data,
int count) {
byte[][] both = new byte[2][];
byte[] key = new byte[key_len];
int key_ix = 0;
byte[] iv = new byte[iv_len];
int iv_ix = 0;
both[0] = key;
both[1] = iv;
byte[] md_buf = null;
int nkey = key_len;
int niv = iv_len;
int i = 0;
if (data == null) {
return both;
}
int addmd = 0;
for (;;) {
md.reset();
if (addmd++ > 0) {
md.update(md_buf);
}
md.update(data);
if (null != salt) {
md.update(salt, 0, 8);
}
md_buf = md.digest();
for (i = 1; i < count; i++) {
md.reset();
md.update(md_buf);
md_buf = md.digest();
}
i = 0;
if (nkey > 0) {
for (;;) {
if (nkey == 0)
break;
if (i == md_buf.length)
break;
key[key_ix++] = md_buf[i];
nkey--;
i++;
}
}
if (niv > 0 && i != md_buf.length) {
for (;;) {
if (niv == 0)
break;
if (i == md_buf.length)
break;
iv[iv_ix++] = md_buf[i];
niv--;
i++;
}
}
if (nkey == 0 && niv == 0) {
break;
}
}
for (i = 0; i < md_buf.length; i++) {
md_buf[i] = 0;
}
return both;
}
public static byte[][] getKeyIV(byte[] headerSaltAndCipherText, Cipher aesCBC, String password) {
byte[] salt = Arrays.copyOfRange(headerSaltAndCipherText, SALT_OFFSET, SALT_OFFSET + SALT_SIZE);
byte[][] keyAndIV=null;
try {
MessageDigest md5 = MessageDigest.getInstance("MD5");
keyAndIV = EVP_BytesToKey(KEY_SIZE_BITS / Byte.SIZE, aesCBC.getBlockSize(), md5, salt,
password.getBytes(ASCII), ITERATIONS);
} catch (Exception e) {e.printStackTrace();}
return keyAndIV;
}
// https://stackoverflow.com/questions/11783062/how-to-decrypt-file-in-java-encrypted-with-openssl-command-using-aes
public static String decrypt(String encryptedMsg, String password) {
String decryptedMsg =null;
byte[] headerSaltAndCipherText = Base64.decodeBase64(encryptedMsg);
byte[] encrypted = Arrays.copyOfRange(headerSaltAndCipherText, CIPHERTEXT_OFFSET, headerSaltAndCipherText.length);
try {
Cipher aesCBC = Cipher.getInstance("AES/CBC/PKCS5Padding");
final byte[][] keyAndIV = getKeyIV(headerSaltAndCipherText, aesCBC, password);
SecretKeySpec key = new SecretKeySpec(keyAndIV[INDEX_KEY], "AES");
IvParameterSpec iv = new IvParameterSpec(keyAndIV[INDEX_IV]);
aesCBC.init(Cipher.DECRYPT_MODE, key, iv);
byte[] decrypted = aesCBC.doFinal(encrypted);
decryptedMsg = new String(decrypted, ASCII);
} catch (Exception e) {e.printStackTrace();}
return decryptedMsg;
}
//TODO - Encrypt the msg in same manner as "openssl enc -aes-256-cbc -a -salt"
public static String encrypt(String msg, String password) {
String decryptedMsg =null;
byte[] headerSaltAndCipherText = Base64.decodeBase64(msg);
byte[] encrypted = Arrays.copyOfRange(headerSaltAndCipherText, CIPHERTEXT_OFFSET, headerSaltAndCipherText.length);
try {
Cipher aesCBC = Cipher.getInstance("AES/CBC/PKCS5Padding");
final byte[][] keyAndIV = getKeyIV(headerSaltAndCipherText, aesCBC, password);
SecretKeySpec key = new SecretKeySpec(keyAndIV[INDEX_KEY], "AES");
IvParameterSpec iv = new IvParameterSpec(keyAndIV[INDEX_IV]);
aesCBC.init(Cipher.ENCRYPT_MODE, key, iv);
byte[] decrypted = aesCBC.doFinal(encrypted);
decryptedMsg = new String(decrypted, ASCII);
} catch (Exception e) {e.printStackTrace();}
return decryptedMsg;
}
public static void main(String[] args) {
String msg = "the decrypted message is this";
String password = "pass";
System.out.println(encrypt(msg, password));
String encryptedMsg = "U2FsdGVkX190A5FsNTanwTKBdex29SpnH4zWkZN+Ld+MmbJgK4BH1whGIRRSpOJT";
System.out.println(decrypt(encryptedMsg, password));
}
}
Also got an improved solution from the following site. Got the code for both encryption and decryption for now...
http://qaru.site/questions/19874/java-equivalent-of-an-openssl-aes-cbc-encryption
import java.net.URLEncoder;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Arrays;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import static java.nio.charset.StandardCharsets.*;
/**
* Mimics the OpenSSL AES Cipher options for encrypting and decrypting messages using a
* shared key (aka password) with symetric ciphers.
*/
public class OpenSslAesQu {
/** OpenSSL magic initial bytes. */
private static final String SALTED_STR = "Salted__";
private static final byte[] SALTED_MAGIC = SALTED_STR.getBytes(US_ASCII);
public static String encryptAndURLEncode(String password, String clearText) {
String encrypted = null;
try {
encrypted = URLEncoder.encode(encrypt(password, clearText),UTF_8.name());
} catch (Exception e) {e.printStackTrace();}
return encrypted;
}
/**
*
* #param password The password / key to encrypt with.
* #param data The data to encrypt
* #return A base64 encoded string containing the encrypted data.
*/
public static String encrypt(String password, String clearText) {
String encryptedMsg = null;
final byte[] pass = password.getBytes(US_ASCII);
final byte[] salt = (new SecureRandom()).generateSeed(8);
final byte[] inBytes = clearText.getBytes(UTF_8);
final byte[] passAndSalt = array_concat(pass, salt);
byte[] hash = new byte[0];
byte[] keyAndIv = new byte[0];
try {
for (int i = 0; i < 3 && keyAndIv.length < 48; i++) {
final byte[] hashData = array_concat(hash, passAndSalt);
final MessageDigest md = MessageDigest.getInstance("MD5");
hash = md.digest(hashData);
keyAndIv = array_concat(keyAndIv, hash);
}
final byte[] keyValue = Arrays.copyOfRange(keyAndIv, 0, 32);
final byte[] iv = Arrays.copyOfRange(keyAndIv, 32, 48);
final SecretKeySpec key = new SecretKeySpec(keyValue, "AES");
final Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));
byte[] data = cipher.doFinal(inBytes);
data = array_concat(array_concat(SALTED_MAGIC, salt), data);
//return Base64.getEncoder().encodeToString( data );
encryptedMsg = org.apache.commons.codec.binary.Base64.encodeBase64String(data);
} catch(Exception e) {e.printStackTrace();}
return encryptedMsg;
}
/**
* #see http://stackoverflow.com/questions/32508961/java-equivalent-of-an-openssl-aes-cbc-encryption for what looks like a useful answer. The not-yet-commons-ssl also has an implementation
* #param password
* #param source The encrypted data
*/
public static String decrypt(String password, String source) {
String decryptedMsg = null;
final byte[] pass = password.getBytes(US_ASCII);
//final byte[] inBytes = Base64.getDecoder().decode(source);
final byte[] inBytes = Base64.decodeBase64(source);
final byte[] shouldBeMagic = Arrays.copyOfRange(inBytes, 0, SALTED_MAGIC.length);
if (!Arrays.equals(shouldBeMagic, SALTED_MAGIC)) {
throw new IllegalArgumentException("Initial bytes from input do not match OpenSSL SALTED_MAGIC salt value.");
}
final byte[] salt = Arrays.copyOfRange(inBytes, SALTED_MAGIC.length, SALTED_MAGIC.length + 8);
final byte[] passAndSalt = array_concat(pass, salt);
byte[] hash = new byte[0];
byte[] keyAndIv = new byte[0];
try {
for (int i = 0; i < 3 && keyAndIv.length < 48; i++) {
final byte[] hashData = array_concat(hash, passAndSalt);
final MessageDigest md = MessageDigest.getInstance("MD5");
hash = md.digest(hashData);
keyAndIv = array_concat(keyAndIv, hash);
}
final byte[] keyValue = Arrays.copyOfRange(keyAndIv, 0, 32);
final SecretKeySpec key = new SecretKeySpec(keyValue, "AES");
final byte[] iv = Arrays.copyOfRange(keyAndIv, 32, 48);
final Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
final byte[] clear = cipher.doFinal(inBytes, 16, inBytes.length - 16);
decryptedMsg = new String(clear, UTF_8);
} catch (Exception e) {e.printStackTrace();}
return decryptedMsg;
}
private static byte[] array_concat(final byte[] a, final byte[] b) {
final byte[] c = new byte[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
return c;
}
public static void main(String[] args) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
String msg = "the decrypted message is this";
String password = "pass";
System.out.println(">> "+encrypt(password,msg));
//System.out.println("<< "+decrypt(encrypt(msg, password), password));
String encryptedMsg = "U2FsdGVkX190A5FsNTanwTKBdex29SpnH4zWkZN+Ld+MmbJgK4BH1whGIRRSpOJT";
String encryptedMsg2 = "U2FsdGVkX1/B6oOznz5+nd7W/qXwXI7G7rhj5o9pjx8MS0TXp9SNxO3AhM9HBJ/z";
System.out.println(decrypt(password,encryptedMsg));
System.out.println(decrypt(password,encryptedMsg2));
System.out.println(decrypt(password,encrypt(password,msg)));
}
}

RSA Encryption Encode using Android Decrypt using apache codec Issue

1) I have a private key in a txt file
2) I have written a decrypt method
while running the decrypt method I am getting the below mentioned exception.
import java.io.File;
import java.io.FileInputStream;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.EncodedKeySpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Calendar;
import java.util.Random;
import javax.crypto.Cipher;
import android.util.Base64;
public static String decrypt(String inputString, byte[] keyBytes) {
String resultStr = null;
Calendar cal = Calendar.getInstance();
int mDay = cal.get(Calendar.DAY_OF_MONTH);
Random generator = new Random(mDay);
int num = (generator.nextInt()) % 100;
String salt = "XXwerr" + num;
PrivateKey privateKey = null;
try {
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(keyBytes);
privateKey = keyFactory.generatePrivate(privateKeySpec);
} catch (Exception e) {
System.out.println("Exception privateKey::::::::::::::::: "
+ e.getMessage());
}
byte[] decodedBytes = null;
try {
Cipher c = Cipher.getInstance("RSA");
//Also tried
// Cipher c = Cipher.getInstance("RSA/ECB/PKCS1Padding");
c.init(Cipher.DECRYPT_MODE, privateKey);
decodedBytes = c.doFinal(Base64.decode(inputString, Base64.NO_CLOSE));
} catch (Exception e) {
System.out.println("Exception privateKey1::::::::::::::::: "
+ e.getMessage());
e.printStackTrace();
}
if (decodedBytes != null) {
resultStr = new String(decodedBytes);
System.out.println("resultStr:::" + resultStr + ":::::");
resultStr = resultStr.replace(salt, "");
}
return resultStr;
}
Following is the main method
public static void main(String[] args) {
FileInputStream fileInputStream = null;
File file = new File("/Users/buta1/Downloads/private.txt");
byte[] bFile = new byte[(int) file.length()];
try {
// convert file into array of bytes
fileInputStream = new FileInputStream(file);
fileInputStream.read(bFile);
fileInputStream.close();
// for (int i = 0; i < bFile.length; i++) {
// System.out.println((char)bFile[i]);
// }
decrypt("08F8CFE58F2E707C314F4D7894E0F1", bFile);
System.out.println("Done");
} catch (Exception e) {
e.printStackTrace();
}
}
THE ENCRYPTION METHOD USED IS AS follows USING ANDROID Base64 class
public static String encrypt(String inputString, byte [] keyBytes)
{
Calendar cal = Calendar.getInstance();
int mDay = cal.get(Calendar.DAY_OF_MONTH);
//System.out.println("Day of month :::" + mDay);
String encryptedString = "";
Key publicKey = null;
try {
Random generator = new Random(mDay);
int num = (generator.nextInt() ) % 100;
String salt = "xx"+num;
inputString += salt;
X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
publicKey = keyFactory.generatePublic(publicKeySpec);
} catch (Exception e) {
System.out.println("Exception rsaEncrypt::::::::::::::::: "+
e.getMessage());
}
// Encode the original data with RSA public key
byte[] encodedBytes = null;
try {
Cipher c = Cipher.getInstance("RSA");
c.init(Cipher.ENCRYPT_MODE, publicKey);
encodedBytes = c.doFinal(inputString.getBytes());
encryptedString =
Base64.encodeToString(encodedBytes, Base64.NO_CLOSE);
} catch (Exception e) {
System.out.println("Exception rsaEncrypt::::::::::::::::: "+
e.getMessage());
}
return encryptedString;
}
After using commons codec Base 64
Cipher c = Cipher.getInstance("RSA/ECB/PKCS1Padding ");
getting following error
javax.crypto.BadPaddingException: Decryption error
at sun.security.rsa.RSAPadding.unpadV15(RSAPadding.java:380)
at sun.security.rsa.RSAPadding.unpad(RSAPadding.java:291)
at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:365)
at com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:391)
at javax.crypto.Cipher.doFinal(Cipher.java:2087)
at RSAEncryption.decrypt(RSAEncryption.java:41)
at RSAEncryption.main(RSAEncryption.java:108)
I am assuming that you are trying to run Android code from inside your IDE with the android.jar on your classpath (e.g. by using the ADT Plugin in eclipse). Then this looks like "working as intended" (cf. https://code.google.com/p/android/issues/detail?id=33188).
The android.jar only contains stub implementations for all classes, because the intended way would be to run that code inside an emulator.
If you are trying to write code for Android and you find running the code inside an emulator to be too cumbersome, you could try Roboelectric, which basically replaces all those stubs with real implementations and allows you to run the code from inside your IDE.
On the other hand, if you are not trying to write code for Android you can simply replace android.util.Base64 with org.apache.commons.codec.binary.Base64 or java.util.Base64.Decoder (since Java 8).

rsa with digital signature coding in java

I was running a code for rsa with digital signature on netbeans but got the following error :
Exception caught
java.io.FileNotFoundException: \org\owasp\crypto\testkeystore.ks (The system cannot find the path specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.(FileInputStream.java:120)
at java.io.FileInputStream.(FileInputStream.java:79)
at org.owasp.crypto.PublicKeyCryptography.main(PublicKeyCryptography.java:52)
BUILD SUCCESSFUL (total time: 0 seconds)
package org.owasp.crypto;
import java.security.*;
import java.security.cert.*;
import javax.crypto.*;
import sun.misc.BASE64Encoder;
import sun.misc.BASE64Decoder;
public class PublicKeyCryptography {
public static void main(String[] args) {
SymmetricEncrypt encryptUtil = new SymmetricEncrypt();
String strDataToEncrypt = "Hello World";
byte[] byteDataToTransmit = strDataToEncrypt.getBytes();
// Generating a SecretKey for Symmetric Encryption
SecretKey senderSecretKey = SymmetricEncrypt.getSecret();
//1. Encrypt the data using a Symmetric Key
byte[] byteCipherText = encryptUtil.encryptData(byteDataToTransmit,senderSecretKey,"AES");
String strCipherText = new BASE64Encoder().encode(byteCipherText);
//2. Encrypt the Symmetric key using the Receivers public key
try{
// 2.1 Specify the Keystore where the Receivers certificate has been imported
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
char [] password = "testpwd".toCharArray();
java.io.FileInputStream fis = new java.io.FileInputStream("/org/owasp/crypto/testkeystore.ks");
ks.load(fis, password);
fis.close();
// 2.2 Creating an X509 Certificate of the Receiver
X509Certificate recvcert ;
MessageDigest md = MessageDigest.getInstance("MD5");
recvcert = (X509Certificate)ks.getCertificate("testrecv");
// 2.3 Getting the Receivers public Key from the Certificate
PublicKey pubKeyReceiver = recvcert.getPublicKey();
// 2.4 Encrypting the SecretKey with the Receivers public Key
byte[] byteEncryptWithPublicKey = encryptUtil.encryptData(senderSecretKey.getEncoded(),pubKeyReceiver,"RSA/ECB/PKCS1Padding");
String strSenbyteEncryptWithPublicKey = new BASE64Encoder().encode(byteEncryptWithPublicKey);
// 3. Create a Message Digest of the Data to be transmitted
md.update(byteDataToTransmit);
byte byteMDofDataToTransmit[] = md.digest();
String strMDofDataToTransmit = new String();
for (int i = 0; i < byteMDofDataToTransmit.length; i++){
strMDofDataToTransmit = strMDofDataToTransmit + Integer.toHexString((int)byteMDofDataToTransmit[i] & 0xFF) ;
}
// 3.1 Message to be Signed = Encrypted Secret Key + MAC of the data to be transmitted
String strMsgToSign = strSenbyteEncryptWithPublicKey + "|" + strMDofDataToTransmit;
// 4. Sign the message
// 4.1 Get the private key of the Sender from the keystore by providing the password set for the private key while creating the keys using keytool
char[] keypassword = "send123".toCharArray();
Key myKey = ks.getKey("testsender", keypassword);
PrivateKey myPrivateKey = (PrivateKey)myKey;
// 4.2 Sign the message
Signature mySign = Signature.getInstance("MD5withRSA");
mySign.initSign(myPrivateKey);
mySign.update(strMsgToSign.getBytes());
byte[] byteSignedData = mySign.sign();
// 5. The Values byteSignedData (the signature) and strMsgToSign (the data which was signed) can be sent across to the receiver
// 6.Validate the Signature
// 6.1 Extracting the Senders public Key from his certificate
X509Certificate sendercert ;
sendercert = (X509Certificate)ks.getCertificate("testsender");
PublicKey pubKeySender = sendercert.getPublicKey();
// 6.2 Verifying the Signature
Signature myVerifySign = Signature.getInstance("MD5withRSA");
myVerifySign.initVerify(pubKeySender);
myVerifySign.update(strMsgToSign.getBytes());
boolean verifySign = myVerifySign.verify(byteSignedData);
if (verifySign == false)
{
System.out.println(" Error in validating Signature ");
}
else
System.out.println(" Successfully validated Signature ");
// 7. Decrypt the message using Recv private Key to get the Symmetric Key
char[] recvpassword = "recv123".toCharArray();
Key recvKey = ks.getKey("testrecv", recvpassword);
PrivateKey recvPrivateKey = (PrivateKey)recvKey;
// Parsing the MessageDigest and the encrypted value
String strRecvSignedData = new String (byteSignedData);
String[] strRecvSignedDataArray = new String [10];
strRecvSignedDataArray = strMsgToSign.split("|");
int intindexofsep = strMsgToSign.indexOf("|");
String strEncryptWithPublicKey = strMsgToSign.substring(0,intindexofsep);
String strHashOfData = strMsgToSign.substring(intindexofsep+1);
// Decrypting to get the symmetric key
byte[] bytestrEncryptWithPublicKey = new BASE64Decoder().decodeBuffer(strEncryptWithPublicKey);
byte[] byteDecryptWithPrivateKey = encryptUtil.decryptData(byteEncryptWithPublicKey,recvPrivateKey,"RSA/ECB/PKCS1Padding");
// 8. Decrypt the data using the Symmetric Key
javax.crypto.spec.SecretKeySpec secretKeySpecDecrypted = new javax.crypto.spec.SecretKeySpec(byteDecryptWithPrivateKey,"AES");
byte[] byteDecryptText = encryptUtil.decryptData(byteCipherText,secretKeySpecDecrypted,"AES");
String strDecryptedText = new String(byteDecryptText);
System.out.println(" Decrypted data is " +strDecryptedText);
// 9. Compute MessageDigest of data + Signed message
MessageDigest recvmd = MessageDigest.getInstance("MD5");
recvmd.update(byteDecryptText);
byte byteHashOfRecvSignedData[] = recvmd.digest();
String strHashOfRecvSignedData = new String();
for (int i = 0; i < byteHashOfRecvSignedData.length; i++){
strHashOfRecvSignedData = strHashOfRecvSignedData + Integer.toHexString((int)byteHashOfRecvSignedData[i] & 0xFF) ;
}
// 10. Validate if the Message Digest of the Decrypted Text matches the Message Digest of the Original Message
if (!strHashOfRecvSignedData.equals(strHashOfData))
{
System.out.println(" Message has been tampered ");
}
}
catch(Exception exp)
{
System.out.println(" Exception caught " + exp);
exp.printStackTrace();
}
}
}
package org.owasp.crypto;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.Cipher;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.InvalidKeyException;
import java.security.InvalidAlgorithmParameterException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import sun.misc.BASE64Encoder;
/**
* #author Joe Prasanna Kumar
* This program provides the following cryptographic functionalities
* 1. Encryption using AES
* 2. Decryption using AES
* High Level Algorithm :
* 1. Generate a DES key (specify the Key size during this phase)
* 2. Create the Cipher
* 3. To Encrypt : Initialize the Cipher for Encryption
* 4. To Decrypt : Initialize the Cipher for Decryption
*/
public class SymmetricEncrypt {
String strDataToEncrypt = new String();
String strCipherText = new String();
String strDecryptedText = new String();
static KeyGenerator keyGen;
private static String strHexVal = "0123456789abcdef";
public static SecretKey getSecret(){
/**
* Step 1. Generate an AES key using KeyGenerator
* Initialize the keysize to 128
*
*/
try{
keyGen = KeyGenerator.getInstance("AES");
keyGen.init(128);
}
catch(Exception exp)
{
System.out.println(" Exception inside constructor " +exp);
}
SecretKey secretKey = keyGen.generateKey();
return secretKey;
}
/**
* Step2. Create a Cipher by specifying the following parameters
* a. Algorithm name - here it is AES
*/
public byte[] encryptData(byte[] byteDataToEncrypt, Key secretKey, String Algorithm) {
byte[] byteCipherText = new byte[200];
try {
Cipher aesCipher = Cipher.getInstance(Algorithm);
/**
* Step 3. Initialize the Cipher for Encryption
*/
if(Algorithm.equals("AES")){
aesCipher.init(Cipher.ENCRYPT_MODE,secretKey,aesCipher.getParameters());
}
else if(Algorithm.equals("RSA/ECB/PKCS1Padding")){
aesCipher.init(Cipher.ENCRYPT_MODE,secretKey);
}
/**
* Step 4. Encrypt the Data
* 1. Declare / Initialize the Data. Here the data is of type String
* 2. Convert the Input Text to Bytes
* 3. Encrypt the bytes using doFinal method
*/
byteCipherText = aesCipher.doFinal(byteDataToEncrypt);
strCipherText = new BASE64Encoder().encode(byteCipherText);
}
catch (NoSuchAlgorithmException noSuchAlgo)
{
System.out.println(" No Such Algorithm exists " + noSuchAlgo);
}
catch (NoSuchPaddingException noSuchPad)
{
System.out.println(" No Such Padding exists " + noSuchPad);
}
catch (InvalidKeyException invalidKey)
{
System.out.println(" Invalid Key " + invalidKey);
}
catch (BadPaddingException badPadding)
{
System.out.println(" Bad Padding " + badPadding);
}
catch (IllegalBlockSizeException illegalBlockSize)
{
System.out.println(" Illegal Block Size " + illegalBlockSize);
illegalBlockSize.printStackTrace();
}
catch (Exception exp)
{
exp.printStackTrace();
}
return byteCipherText;
}
/**
* Step 5. Decrypt the Data
* 1. Initialize the Cipher for Decryption
* 2. Decrypt the cipher bytes using doFinal method
*/
public byte[] decryptData(byte[] byteCipherText, Key secretKey, String Algorithm) {
byte[] byteDecryptedText = new byte[200];
try{
Cipher aesCipher = Cipher.getInstance(Algorithm);
if(Algorithm.equals("AES")){
aesCipher.init(Cipher.DECRYPT_MODE,secretKey,aesCipher.getParameters());
}
else if(Algorithm.equals("RSA/ECB/PKCS1Padding")){
aesCipher.init(Cipher.DECRYPT_MODE,secretKey);
}
byteDecryptedText = aesCipher.doFinal(byteCipherText);
strDecryptedText = new String(byteDecryptedText);
}
catch (NoSuchAlgorithmException noSuchAlgo)
{
System.out.println(" No Such Algorithm exists " + noSuchAlgo);
}
catch (NoSuchPaddingException noSuchPad)
{
System.out.println(" No Such Padding exists " + noSuchPad);
}
catch (InvalidKeyException invalidKey)
{
System.out.println(" Invalid Key " + invalidKey);
invalidKey.printStackTrace();
}
catch (BadPaddingException badPadding)
{
System.out.println(" Bad Padding " + badPadding);
badPadding.printStackTrace();
}
catch (IllegalBlockSizeException illegalBlockSize)
{
System.out.println(" Illegal Block Size " + illegalBlockSize);
illegalBlockSize.printStackTrace();
}
catch (InvalidAlgorithmParameterException invalidParam)
{
System.out.println(" Invalid Parameter " + invalidParam);
}
return byteDecryptedText;
}
public static byte[] convertStringToByteArray(String strInput) {
strInput = strInput.toLowerCase();
byte[] byteConverted = new byte[(strInput.length() + 1) / 2];
int j = 0;
int interimVal;
int nibble = -1;
for (int i = 0; i < strInput.length(); ++i) {
interimVal = strHexVal.indexOf(strInput.charAt(i));
if (interimVal >= 0) {
if (nibble < 0) {
nibble = interimVal;
} else {
byteConverted[j++] = (byte) ((nibble << 4) + interimVal);
nibble = -1;
}
}
}
if (nibble >= 0) {
byteConverted[j++] = (byte) (nibble << 4);
}
if (j < byteConverted.length) {
byte[] byteTemp = new byte[j];
System.arraycopy(byteConverted, 0, byteTemp, 0, j);
byteConverted = byteTemp;
}
return byteConverted;
}
public static String convertByteArrayToString(byte[] block) {
StringBuffer buf = new StringBuffer();
for (int i = 0; i < block.length; ++i) {
buf.append(strHexVal.charAt((block[i] >>> 4) & 0xf));
buf.append(strHexVal.charAt(block[i] & 0xf));
}
return buf.toString();
}
}
Your exception is caused because you've passed a non-existent file path to the FileInputStream constructor:
... = FileInputStream("/org/owasp/crypto/testkeystore.ks")
Make sure the path you provide is a valid relative or absolute path.

javax.crypto.BadPaddingException

I am working on AES algorithm, and I have this exception which I couldn't solve.
javax.crypto.BadPaddingException: Given final block not properly padded
at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
at com.sun.crypto.provider.AESCipher.engineDoFinal(DashoA13*..)
at javax.crypto.Cipher.doFinal(DashoA13*..)
the exception happens in the decryption part.
I initialize the key in a different place from where the decryption algorithm is
KeyGenerator kgen = KeyGenerator.getInstance("AES");//key generation for AES
kgen.init(128); // 192 and 256 bits may not be available
then I pass it with the cipher text which I read from file to the following method
public String decrypt(String message, SecretKey skey) {
byte[] raw = skey.getEncoded();
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
// Instantiate the cipher
Cipher cipher;
byte[] original = null;
try {
cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
System.out.println("Original string: "
+ message);
original = cipher.doFinal(message.trim().getBytes()); //here where I got the exception
String originalString = new String(original);
}
//catches
EDIT
here's the encryption method.
public String encrypt(String message, SecretKey skey) {
byte[] raw = skey.getEncoded();
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
// Instantiate the cipher
Cipher cipher;
byte[] encrypted = null;
try {
cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
encrypted = cipher.doFinal(message.getBytes());
System.out.println("raw is " + encrypted);
} catches
return asHex(encrypted);
}
and here's the asHex method
public static String asHex(byte buf[]) {
StringBuffer strbuf = new StringBuffer(buf.length * 2);
int i;
for (i = 0; i < buf.length; i++) {
if (((int) buf[i] & 0xff) < 0x10) {
strbuf.append("0");
}
strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
}
return strbuf.toString();
}
Here's where I read the cipher text form the file
static public String readFile(String filePath) {
StringBuilder file = new StringBuilder();
String line = null;
try {
FileReader reader = new FileReader(filePath);
BufferedReader br = new BufferedReader(reader);
if (br != null) {
line = br.readLine();
while (line != null) {
file.append(line);
// System.out.println("line is " + line);
line = br.readLine();
}
}
br.close();
reader.close();
} catch (IOException ex) {
Logger.getLogger(FileManagement.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("line is " + file.toString());
return String.valueOf(file);
}
can someone help?
Ok, so the problem is that you are converting the encrypted bytes to a hex string (using the asHex method) but are not converting the hex string back to a byte array correctly for decryption. You can't use getBytes.
You can use the following method to convert a hex string to a byte array:
public static byte[] fromHexString(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i+1), 16));
}
return data;
}
and then change your decrypt method to use:
original = cipher.doFinal(fromHexString(message));
I did have a Bad Padding Exception and have not been able to find on the internet a solution to my problem. Since I found it after some hard-working hours, I give it here.
My problem was, I was reading a file on my hard drive, and encrypting it through a buffer, always calling the doFinal() method instead of update() method. So when decrypting it, I had padding errors
input = new FileInputStream(file);
output = new FileOutputStream(newFile);
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, mySecretKey);
byte[] buf = new byte[1024];
count = input.read(buf);
while (count >= 0) {
output.write(cipher.update(buf, 0, count)); // HERE I WAS DOING doFinal() method
count = input.read(buf);
}
output.write(cipher.doFinal()); // AND I DID NOT HAD THIS LINE BEFORE
output.flush();
And when decrypting, with the same method, but with a Cipher init with DECRYPT_MODE
input = new FileInputStream(file);
output = new FileOutputStream(newFile);
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.DECRYPT_MODE, mySecretKey);
byte[] buf = new byte[1024];
count = input.read(buf);
while (count >= 0) {
output.write(cipher.update(buf, 0, count)); // HERE I WAS DOING doFinal() method
//AND HERE WAS THE BadPaddingExceotion -- the first pass in the while structure
count = input.read(buf);
}
output.write(cipher.doFinal()); // AND I DID NOT HAD THIS LINE BEFORE
output.flush();
With the code written, I no longer have any BadPaddingException.
I may precise that this exception only appears when the original clear file length (obtained through file.length()) is bigger than the buffer. Else, we do not need to pass several times in the while structure, and we can encrypt in one pass with a doFinal() call. That justify the random character of the exception following the size of the file you try to encrypt.
I hope you had a good reading!
I guess the expression message.trim().getBytes() does not return the same bytes which are generated when you encrypted the message. Specially the trim() method could delete the bytes which were added as padding in the encrypted message.
Verify that both the returned array of the doFinal() method during the encryption and the returned array of message.trim().getBytes():
got the same number of bytes (array length)
got the same bytes in the array
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(512);
KeyPair rsaKeyPair = kpg.genKeyPair();
byte[] txt = "This is a secret message.".getBytes();
System.out.println("Original clear message: " + new String(txt));
// encrypt
Cipher cipher;
try
{
cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, rsaKeyPair.getPublic());
txt = cipher.doFinal(txt);
}
catch (Throwable e)
{
e.printStackTrace();
return;
}
System.out.println("Encrypted message: " + new String(txt));
// decrypt
try
{
cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, rsaKeyPair.getPrivate());
txt = cipher.doFinal(txt);
}
catch (Throwable e)
{
e.printStackTrace();
return;
}
System.out.println("Decrypted message: " + new String(txt));
Here is a solution I was able to piece together using a jks keystore with RSA encryption
import javax.crypto.Cipher;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.cert.Certificate;
public class Main {
public static void main(String[] args) {
byte[] txt = "This is a secret message for your own eyes only".getBytes();
byte[] encText;
try{
// Load the keystore
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
char[] password = "keystorePassword".toCharArray();
java.io.FileInputStream fis = new java.io.FileInputStream("/path/to/keystore/myKeyStore.jks");
ks.load(fis, password);
fis.close();
Key rsakey = ks.getKey("mykeyalias", password);
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
// Encrypt
Certificate cert = ks.getCertificate("mykeyalias");
try
{
cipher.init(Cipher.ENCRYPT_MODE, cert.getPublicKey());
encText = cipher.doFinal(txt);
System.out.println(encText.toString());
}
catch (Throwable e)
{
e.printStackTrace();
return;
}
// Decrypt
cipher.init(Cipher.DECRYPT_MODE, rsakey);
String decrypted = new String(cipher.doFinal(encText));
System.out.println(decrypted);
} catch (Exception e) {
System.out.println("error" + e);
}
}

Categories

Resources