I had a Java code to decrypt password stored in connections XML for SQL Developer V17.
Looks like the encryption method or details are changed for V19.
After updating to SQL Developer V19, the same old code is not working.
Anyone know how to decrypt the password stored in connections XML for SQL Developer V19?
Get encrypted password from connections.json file from location :
C:\Users<User name>\AppData\Roaming\SQL
Developer\system18.4.0.376.1900\o.jdeveloper.db.connection Example :
"password": "Ehi21wFkasdfc=",
Get the ecryption key from the file
product-preferences.xml in location C:\Users<user
name>\AppData\Roaming\SQL
Developer\system18.4.0.376.1900\o.sqldeveloper
Example :
decrypt the password using the below website.
https://abskmj.github.io/sqldev-pw-decryptor/
Alternative way to do it in local machine:
Get encrypted password from connections.json file from location :
C:\Users\AppData\Roaming\SQL
Developer\system18.4.0.376.1900\o.jdeveloper.db.connection Example :
"password": "Ehi21wFkasdfc=",
Get the ecryption key from the file product-preferences.xml in
location C:\Users\AppData\Roaming\SQL
Developer\system18.4.0.376.1900\o.sqldeveloper
Use the following code to decrypt the password
package utils;
import java.security.MessageDigest;
import java.security.GeneralSecurityException;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.util.Base64;
public class Decrypt_OracleSqlDevPW {
private static byte[] des_cbc_decrypt(
byte[] encrypted_password,
byte[] decryption_key,
byte[] iv)
throws GeneralSecurityException
{
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryption_key, "DES"), new IvParameterSpec(iv));
return cipher.doFinal(encrypted_password);
}
private static byte[] decrypt_v4(
byte[] encrypted,
byte[] db_system_id)
throws GeneralSecurityException
{
byte[] encrypted_password = Base64.getDecoder().decode(encrypted);
byte[] salt = DatatypeConverter.parseHexBinary("051399429372e8ad");
// key = db_system_id + salt
byte[] key = new byte[db_system_id.length + salt.length];
System.arraycopy(db_system_id, 0, key, 0, db_system_id.length);
System.arraycopy(salt, 0, key, db_system_id.length, salt.length);
java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
for (int i=0; i<42; i++) {
key = md.digest(key);
}
// secret_key = key [0..7]
byte[] secret_key = new byte[8];
System.arraycopy(key, 0, secret_key, 0, 8);
// iv = key [8..]
byte[] iv = new byte[key.length - 8];
System.arraycopy(key, 8, iv, 0, key.length - 8);
return des_cbc_decrypt(encrypted_password, secret_key, iv);
}
public static void main(String[] argv) { try {
String encryptedPassword = "wwA5s2bU02lfY4aTg==";// password
String key = "8397631a-9e0f-42-afda-3fafcac1f193";//key in our local machine
byte[] encrypted = encryptedPassword.getBytes();
byte[] db_system_id = key.getBytes();
byte[] x = decrypt_v4(encrypted, db_system_id);
String password = new String(x);
System.out.println(password);
}
catch (Exception e) {
System.out.println(e.toString());
}
}
}
Related
I need to convert java code for encryption and decryption using AES/CBC/PKCS5Padding algorithm to dart code.
The java code of AES/CBC/PKCS5Padding encryption and decryption:
package test_Terminal.classes;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
/**
*
* #author jeena
*/
public class IOTEncodingDecoding {
SecretKeySpec secretKeySpec;
IvParameterSpec ivSpec;
String EncryptionKey = "733D3A17-D8A0-454B-AD22-88608FD0C46A";
String saltString = "FA9A4D0F-5523-4EEF-B226-9A3E8F14FEF8";
String algorithm = "AES/CBC/PKCS5Padding";
int encoding_mode;
test_Terminal.classes.general General = new test_Terminal.classes.general();
void setSecretKey() {
try {
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
PBEKeySpec pbeKeySpec = new PBEKeySpec(EncryptionKey.toCharArray(), saltString.getBytes(StandardCharsets.UTF_16LE), 1000, 384);
byte[] derivedData = factory.generateSecret(pbeKeySpec).getEncoded();
byte[] key = new byte[32];
byte[] iv = new byte[16];
System.arraycopy(derivedData, 0, key, 0, key.length);
System.arraycopy(derivedData, key.length, iv, 0, iv.length);
secretKeySpec = new SecretKeySpec(key, "AES");
ivSpec = new IvParameterSpec(iv);
} catch (Exception e) {
General.LogException("setSecretKey", e);
}
}
public String encrypt(String input) {
try {
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivSpec);
byte[] cipherText ;
if(encoding_mode==1)
cipherText = cipher.doFinal(input.getBytes(StandardCharsets.UTF_16LE));
else
cipherText = cipher.doFinal(input.getBytes());
return Base64.getEncoder().encodeToString(cipherText);
} catch (Exception e) {
General.LogException("encrypt", e);
}
return "";
}
public String decrypt(String cipherText) {
try {
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivSpec);
byte[] plainText = cipher.doFinal(Base64.getDecoder().decode(cipherText));
if(encoding_mode==1)
return new String(plainText, StandardCharsets.UTF_16LE);
else
return new String(plainText);
} catch (Exception e) {
General.LogException("decrypt", e);
General.LogActivity("decrypt", e.getMessage());
}
return "Ticket format error";
}
public void setMode() {
setSecretKey();
}
}
I need to get the following result:
Input(PlainText):C123492349C1CT20230206130645.
Output(Encrypted string):8tyHRaQCsxmmGW2xPBFYx/PALmvHkmjx/TzaXC2rIv0=
This is the dart code that I've got so far for decryption, but I'm getting error.
Uint8List? decrypt(String ciphertext, String password) {
Uint8List rawCipher = base64.decode(ciphertext);
var salt = rawCipher.sublist(0, 0 + 8);
var iv = rawCipher.sublist(8, 8 + 16);
var encrypted = rawCipher.sublist(8 + 16);
Uint8List key = generateKey(password, salt);
print('key => $key');
CBCBlockCipher cipher = CBCBlockCipher(AESEngine());
ParametersWithIV<KeyParameter> params =
ParametersWithIV<KeyParameter>(KeyParameter(key), iv);
PaddedBlockCipherParameters<ParametersWithIV<KeyParameter>, Null>
paddingParams =
PaddedBlockCipherParameters<ParametersWithIV<KeyParameter>, Null>(
params, null);
PaddedBlockCipherImpl paddingCipher =
PaddedBlockCipherImpl(PKCS7Padding(), cipher);
paddingCipher.init(false, paddingParams);
var val = paddingCipher.process(encrypted);
String res = String.fromCharCodes(val);
debugPrint('res => $res');
return val;
}
Uint8List generateKey(String passphrase, Uint8List salt) {
final derivator = PBKDF2KeyDerivator(HMac(SHA1Digest(), 64))
..init(Pbkdf2Parameters(salt, 1024, 16));
return derivator.process(utf8.encode(passphrase) as Uint8List);
}
I got this code from
The Exception that I'm getting is:
Exception has occurred.
ArgumentError (Invalid argument(s): Input data length must be a multiple of cipher's block size)
I think the values inside rawCipher.sublist() function is wrong. I'm stuck on this problem for few days, please help.
Both codes differ:
Regarding encodings: The Dart code does not consider the UTF-16 LE encoding of the salt. Furthermore, the encoding of the plaintext is unclear. For encoding_mode==1 it is UTF-16LE, otherwise it corresponds to the platform encoding in your environment (which only you know).
Regarding PBKDF2: The Java code derives key and IV from a static salt (note that a static salt is a vulnerability), while the Dart code assumes a concatenation in the order salt|IV|ciphertext during encryption (using a random 8 bytes salt and a random IV).
Also, different iteration counts are used: 1000 in the Java code, 1024 in the Dart code (note that both values are generally much too small for PBKDF2).
The differences can be fixed as follows:
Regarding encodings: In the Dart code, the salt must first be UTF-16 LE encoded: Since the utf package is deprecated, see e.g. here for a UTF-16 LE encoding and here for the decoding. The encoding can be adapted to:
Uint8List encodeUtf16LE(String salt) {
var byteData = ByteData(salt.codeUnits.length * 2);
for (var i = 0; i < salt.codeUnits.length; i += 1) {
byteData.setUint16(i * 2, salt.codeUnits[i], Endian.little);
}
return byteData.buffer.asUint8List();
}
Moreover, from the sample data it can be concluded (by testing) that the plaintext in the Java code has been encoded with UTF-8.
Regarding PBKDF2: In the Dart code, key and IV must be derived from the static salt applied in the Java code.
Also, the parameters from the Java code must be applied (digest: SHA-1, iteration count: 1000, keysize: 32 + 16 = 48 bytes):
Uint8List generateKey(String passphrase, Uint8List salt) {
final derivator = PBKDF2KeyDerivator(HMac(SHA1Digest(), 64))
..init(Pbkdf2Parameters(salt, 1000, 32 + 16));
return derivator.process(utf8.encode(passphrase) as Uint8List);
}
With these changes, key and IV can be derived as follows:
var salt = "FA9A4D0F-5523-4EEF-B226-9A3E8F14FEF8";
var passphrase = "733D3A17-D8A0-454B-AD22-88608FD0C46A";
var saltBytes = encodeUtf16LE(salt);
var keyIv = generateKey(passphrase, saltBytes);
var key = keyIv.sublist(0, 32);
var iv = keyIv.sublist(32, 32 + 16);
The decryption code can be applied unchanged, for decoding use utf8.decode() instead of String.fromCharCodes().
import 'dart:convert';
import 'dart:typed_data';
import 'package:pointycastle/export.dart';
...
var ciphertext = "8tyHRaQCsxmmGW2xPBFYx/PALmvHkmjx/TzaXC2rIv0=";
var encrypted = base64.decode(ciphertext);
var paddingCipher = PaddedBlockCipherImpl(PKCS7Padding(), CBCBlockCipher(AESEngine()))
..init(false, PaddedBlockCipherParameters(ParametersWithIV(KeyParameter(key), iv), null));
var decryptedBytes = paddingCipher.process(encrypted);
var decrypted = utf8.decode(decryptedBytes); // C123492349C1CT20230206130645
So I think I have encrypted my secret key and String well but decryption is becoming the problem for me. Below is my code:
package ReadFileExample;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.KeyStore;
public class generatekey {
static Cipher cipher;
public static void main(String[] args) throws Exception {
// generating a symmetric key using the AES algorithm
KeyGenerator generator = KeyGenerator.getInstance("AES");
// 128 bit key
generator.init(256);
//generates a secret key
SecretKey secretkey = generator.generateKey();
// returns an AES cipher
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
//print key
System.out.println("Key: " + cipher);
String plainText = "Hello World";
// call to method encrypt
String hexEncryptedByteText = encrypt(plainText, secretkey);
// print orignial text and encrypted text
System.out.println("Plain Text: " + plainText);
System.out.println("Encrypted Text: " + hexEncryptedByteText);
int plainTextlength = plainText.length();
System.out.println("length of text: " + plainTextlength);
// allows to write data to a file
FileOutputStream fos = null;
// write bytes to file
BufferedOutputStream bos = null;
// create file to which data needs to be written
String fileName = "C:/Users/******/newFile.txt";
try{
// allows written data to go into the written path
fos = new FileOutputStream(fileName);
// converts written data into bytes
bos = new BufferedOutputStream(fos);
// writes the encrypted text into file
bos.write(hexEncryptedByteText.length());
System.out.println("encryptedText has been written successfully in "
+fileName);
// allows to catch bug in code
} catch (IOException e) {
e.printStackTrace();
} finally {
try{
// check for null exception
if (bos != null){
bos.close();
}
// check for null exception
if (fos != null){
fos.close();
}
} catch (IOException e){
e.printStackTrace();
}
}
// creates a file input stream by opening a path to the file needed
FileInputStream fin = new FileInputStream("C:/Users/*****/public.cert");
// implements the X509 certificate type
CertificateFactory f = CertificateFactory.getInstance("X.509");
// initalizes data found in the file
X509Certificate certificate = (X509Certificate)f.generateCertificate(fin);
// gets public key from this certificate
PublicKey pk = certificate.getPublicKey();
System.out.println(pk);
String hexEncryptedByteKey = encryptedKey(pk, secretkey);
System.out.println("Encrypted Key: " + hexEncryptedByteKey);
System.out.println("Encrypted Key length: " + hexEncryptedByteKey.length());
// allows to write data to a file
FileOutputStream newFos = null;
// write bytes to file
BufferedOutputStream newBos = null;
// create file to which data needs to be written
String fileNameKey = "C:/Users/****/symmetric.txt";
try{
// allows written data to go into the written path
newFos = new FileOutputStream(fileNameKey);
// converts written data into bytes
newBos = new BufferedOutputStream(newFos);
// writes the encrypted text into file
newBos.write(hexEncryptedByteKey.length());
System.out.println("encryptedKey has been written successfully in "
+fileNameKey);
// allows to catch bug in code
} catch (IOException e) {
e.printStackTrace();
} finally {
try{
// check for null exception
if (newBos != null){
newBos.close();
}
// check for null exception
if (newFos != null){
newFos.close();
}
} catch (IOException e){
e.printStackTrace();
}
}
// load keystore to get private key
KeyStore ks = KeyStore.getInstance("JKS");
String password = "*****";
char[] passwordChar = password.toCharArray();
System.out.println("password: " + passwordChar);
// locate file
try (FileInputStream fis = new FileInputStream("C:/Users/*****/keystore.jks")) {
ks.load(fis, passwordChar);
}
// protect password for keystore
KeyStore.ProtectionParameter protParam = new KeyStore.PasswordProtection(passwordChar);
// get private key from keystore
KeyStore.PrivateKeyEntry pkEntry = (KeyStore.PrivateKeyEntry)
ks.getEntry("*****", protParam);
PrivateKey myPrivateKey = pkEntry.getPrivateKey();
System.out.println("private key: " + myPrivateKey);
//method declaration
String decryptedKey = decryptedKey(myPrivateKey, hexEncryptedByteKey);
System.out.println("decrypted Key: " + decryptedKey);
String hexDecryptedByteText = decryptedTextHex(decryptedKey, hexEncryptedByteText);
System.out.println("key: " + hexDecryptedByteText);
}
public static String encrypt(String plainText, SecretKey secretkey) throws Exception {
//Encodes the string into a sequence of bytes
byte[] plainTextByte = plainText.getBytes();
//intialize cipher to encryption mode
cipher.init(Cipher.ENCRYPT_MODE, secretkey);
//data is encrypted
byte[] encryptedByte = cipher.doFinal(plainTextByte);
//Base64.Encoder encoder = Base64.getEncoder();
//encodes bytes into a string using Base64
byte[] encryptedByteText = Base64.getEncoder().encode(plainTextByte);
String hexEncryptedByteText = DatatypeConverter.printHexBinary(plainTextByte);
// return the string encrypted text to the main method
return hexEncryptedByteText;
}
public static String encryptedKey(PublicKey pk, SecretKey secretkey) throws Exception {
// data written to byte array
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// writes data types to the output stream
ObjectOutputStream writter = new ObjectOutputStream(baos);
//specific object of secretkey is written to the output stream
writter.writeObject(secretkey);
//creates a byte array
byte[] plainTextByteKey = baos.toByteArray();
//creates a cipher using the RSA algorithm
Cipher cipher = Cipher.getInstance("RSA");
// initalizes cipher for encryption using the public key
cipher.init(Cipher.ENCRYPT_MODE, pk);
//encrypts data
//byte[] encryptedByteKey = Base64.getEncoder().encode(plainTextByteKey);
String hexEncryptedByteKey = DatatypeConverter.printHexBinary(plainTextByteKey);
//Base64.Encoder encoderKey = Base64.getEncoder();
// encodes the byte array into a string.
//String encryptedTextKey = new String(encryptedByteKey);
return hexEncryptedByteKey;
}
private static String decryptedKey(PrivateKey myPrivateKey, String hexEncryptedByteKey) throws Exception {
//ByteArrayOutputStream baosDecrypt = new ByteArrayOutputStream();
//ObjectOutputStream writterDecrypt = new ObjectOutputStream(baosDecrypt);
//writterDecrypt.writeObject(hexEncryptedByteKey);
//byte[] byteKeyDecrypt = baosDecrypt.toByteArray();
Cipher cipher;
cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, myPrivateKey);
//cipher.doFinal();
//byte [] decryptedKey = Base64.getDecoder().decode(byteKeyDecrypt);
//String decryptedTextKey = new String(byteKeyDecrypt);
byte[] decodedHex = DatatypeConverter.parseHexBinary(hexEncryptedByteKey);
System.out.println("decoded hex key: " + decodedHex);
String decryptedKey = new String(decodedHex, "UTF-8");
return decryptedKey;
}
private static String decryptedTextHex(String decryptedKey, String hexEncryptedByteText) throws Exception {
byte[] decryptedTextByte = decryptedKey.getBytes();
byte[] textString = hexEncryptedByteText.getBytes();
SecretKey key = new SecretKeySpec(decryptedTextByte, 0, decryptedTextByte.length, "AES");
Cipher cipher;
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
//IvParameterSpec iv = new IvParameterSpec(cipher.getIV());
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] decodedTextHex = cipher.doFinal(textString);
byte[] decoded = Base64.getDecoder().decode(decodedTextHex);
String hexDecryptedByteText = DatatypeConverter.printHexBinary(decoded);
return hexDecryptedByteText;
}
}
This is the error I am getting:
Exception in thread "main" java.security.InvalidKeyException: Parameters missing
at com.sun.crypto.provider.CipherCore.init(CipherCore.java:469)
at com.sun.crypto.provider.AESCipher.engineInit(AESCipher.java:313)
at javax.crypto.Cipher.implInit(Cipher.java:802)
at javax.crypto.Cipher.chooseProvider(Cipher.java:864)
at javax.crypto.Cipher.init(Cipher.java:1249)
at javax.crypto.Cipher.init(Cipher.java:1186)
at ReadFileExample.generatekey.decryptedTextHex(generatekey.java:289)
at ReadFileExample.generatekey.main(generatekey.java:202)
I am not sure what is wrong. If my decryption of key is wrong or just the decryption of the String. I get no errors when it comes to the decryption of the key however.
For some more information: I generated a secret key, encrypted a String with the secret key and then encrypted the secret key with a generated public key. Then I decrypted the secret key with the private key and lastly I need to decrypt the String with the decrypted secret key.
Help is greatly appreciated. I have been working on this for so long and I just don't know what to do anymore. ]
EDIT: That other question has nothing to do with my question. I don't even have that same error message and I have already downloaded the JCE as that solution has stated.
You have to be carefull with the key size, AES is a 128-bit block cipher supporting keys of 128, 192, and 256 bits so if your key size is any different you will get exceptions, also if you keysize is greater than 128 then the code wont work unless you have Unlimited policy files. Basically there is quite a bit detail to this. If you want to see some working code check out this link: https://github.com/Jsondb/jsondb-core/blob/master/src/main/java/io/jsondb/crypto/DefaultAESCBCCipher.java
I've tried running the code for about 3 days now but I am not able to figure out the mistake I've done.
I 'am using AES/CFB/NOPadding in 128 bit with password salting
Salt_Len = 8 bytes and IV_Len = 16 bytes
package Firstage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.SecureRandom;
import java.security.spec.KeySpec;
import java.util.Random;
import java.util.Scanner;
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 Thealgorithm1
{
static Scanner get = new Scanner(System.in);
private static final String ALGORITHM = "AES";
private static final String ALGORITHM_MODE ="AES/CFB/NoPadding";
private static String password;
public static void encrypt(File inputFile, File outputFile)
throws Exception
{
System.out.println("Enetr passprhase");
password=get.nextLine();
final Random ivspc = new SecureRandom();
byte[] ivspec = new byte[16];
ivspc.nextBytes(ivspec);
IvParameterSpec enciv = new IvParameterSpec(ivspec);
FileOutputStream outputstrm = new FileOutputStream(outputFile);
byte[] outputBytes = doCrypto(Cipher.ENCRYPT_MODE, inputFile,password,enciv);
System.arraycopy(ivspec, 0,outputBytes , 0, 16);
outputstrm.write(outputBytes);
outputstrm.close();
System.out.println("File encrypted successfully!");
}
public static void decrypt(File inputFile, File outputFile)
throws Exception
{
System.out.println("Enter password");
password=get.nextLine();
IvParameterSpec hj = null;
byte[]outpytBytes=doCrypto(Cipher.DECRYPT_MODE, inputFile,password,hj);
FileOutputStream outputstrm = new FileOutputStream(outputFile);
outputstrm.write(outpytBytes);
outputstrm.close();
System.out.println("File decrypted successfully!");
}
private static byte[] doCrypto(int cipherMode, File inputFile,String keyo ,IvParameterSpec ivespec)
throws Exception {
/* Derive the key, given password and salt. */
final Random slt = new SecureRandom();
byte[] salt = new byte[8];
slt.nextBytes(salt);
char[] passkeyo = keyo.toCharArray();
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
KeySpec spec = new PBEKeySpec(passkeyo, salt, 65536, 128);
SecretKey tmp = factory.generateSecret(spec);
SecretKey secret = new SecretKeySpec(tmp.getEncoded(), ALGORITHM);
FileInputStream fylin = new FileInputStream(inputFile);
byte[] inputBytes = new byte[(int)inputFile.length()];
fylin.read(inputBytes);
fylin.close();
Cipher cipher = Cipher.getInstance(ALGORITHM_MODE);
byte[] outputBytes;
if(cipherMode==2)
{
IvParameterSpec ivdec = new IvParameterSpec(inputBytes,0,16);
cipher.init(cipherMode, secret,ivdec);
}
else
{
cipher.init(cipherMode, secret, ivespec);
}
if(cipherMode==2)
{
outputBytes = cipher.doFinal(inputBytes, 16,(inputBytes.length-16));
}
else
{
outputBytes=cipher.doFinal(inputBytes);
}
return outputBytes;
}
public static void main(String[] args)
{
File inputFile = new File("C:/temp/File.txt");
File encryptedFile = new File("C:/temp/encryaes.enc");
File decryptedFile = new File("C:/temp/mydr.txt");
try {
Thealgorithm1.encrypt(inputFile, encryptedFile);
Thealgorithm1.decrypt(encryptedFile, decryptedFile);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
The code encrypts it properly and also decrypts it, but the problem is that what it decrypts is not proper i.e there's a fault in the code.
You have two problems:
during encryption, you're overwriting a the first 16 bytes of the ciphertext with the IV. An easy fix is to write the IV to the stream instead of using System.arraycopy(). Change
System.arraycopy(ivspec, 0,outputBytes , 0, 16);
to
outputstrm.write(ivspec);
You're using a different salts during encryption and decryption, because you're always generating a new one. You should also write the salt in front of the ciphertext beside the IV and read it back during decryption.
You could also just use one of the two: generate a 16 byte salt and write that in front of the ciphertext. Then you can use a static IV, because the semantic property is achieved from the random salt.
You have two main issues in your code:
The key must be exactly the same for encryption and decryption. When you decrypt you are generating a different (random) salt value so, even if you enter the same passphrase, the decryption key is going to be different. You can test this by making the salt a class attribute and only initializing it once.
When you do this inside the encrypt method:
System.arraycopy(ivspec, 0,outputBytes , 0, 16);
You are writing over the first 16 bytes of the encrypted output.
My simple suggestion is to do something like this:
byte[] outputBytes = doCrypto(Cipher.ENCRYPT_MODE, inputFile, password, enciv);
byte[] outputBytesWithIV = new byte[outputBytes.length + 16];
System.arraycopy(ivspec, 0, outputBytesWithIV, 0, 16);
System.arraycopy(outputBytes, 0, outputBytesWithIV, 16, outputBytes.length);
outputstrm.write(outputBytesWithIV);
I am writing a Spring mvc app and it needs to send an email with a link and encrypted params. The user will click on the link and I need to decrypt the params in the new page. So I am writing a util class to encrypt and decrypt along with encoding and decoding the parameters.
When I run my stand alone java class(using for testing) - I get the following error when the decryption is called(encrypting, encoding, decoding works fine).
java.security.InvalidAlgorithmParameterException: Wrong IV length: must be 16 bytes long
at com.sun.crypto.provider.CipherCore.init(CipherCore.java:430)
at com.sun.crypto.provider.AESCipher.engineInit(AESCipher.java:217)
at javax.crypto.Cipher.implInit(Cipher.java:791)
at javax.crypto.Cipher.chooseProvider(Cipher.java:849)
at javax.crypto.Cipher.init(Cipher.java:1348)
My class is below
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.Map;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
public class TestEncryptionEncode2 {
private String keyString = "asdfgh";
public static void main(String[] args) throws Exception {
TestEncryptionEncode2 api = new TestEncryptionEncode2();
String input = "abcdwer.comq1234";
try {
String[] encrypted = api.encryptObject(input);
// url may differ.. based upon project initial context
System.out.println("http://localhost:8080/view?d="+encrypted[0]+"&v="+encrypted[1]);
Object obj = api.decryptObject(encrypted[0], encrypted[1]);
System.out.println("Object Decrypted: "+obj.toString());
}catch(Exception e) {
//logger.debug("Unable to encrypt view id: "+id, e);
e.printStackTrace();
}
System.out.println("DONEE ");
}
private String[] encryptObject(Object obj) throws Exception {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
ObjectOutput out = new ObjectOutputStream(stream);
try {
// Serialize the object
out.writeObject(obj);
byte[] serialized = stream.toByteArray();
System.out.println("serialized "+serialized[0]);
// Setup the cipher and Init Vector
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] iv = new byte[cipher.getBlockSize()];
System.out.println("cipher.getBlockSize() "+cipher.getBlockSize());
System.out.println("iv.length "+iv.length);
new SecureRandom().nextBytes(iv);
IvParameterSpec ivSpec = new IvParameterSpec(iv);
// Hash the key with SHA-256 and trim the output to 128-bit for the key
MessageDigest digest = MessageDigest.getInstance("SHA-256");
digest.update(keyString.getBytes());
byte[] key = new byte[16];
System.arraycopy(digest.digest(), 0, key, 0, key.length);
SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
// encrypt
cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
// Encrypt & Encode the input
byte[] encrypted = cipher.doFinal(serialized);
byte[] base64Encoded = Base64.encodeBase64(encrypted);
String base64String = new String(base64Encoded);
String urlEncodedData = URLEncoder.encode(base64String,"UTF-8");
// Encode the Init Vector
byte[] base64IV = Base64.encodeBase64(iv);
String base64IVString = new String(base64IV);
String urlEncodedIV = URLEncoder.encode(base64IVString, "UTF-8");
System.out.println("urlEncodedData.length "+urlEncodedData.length());
System.out.println("urlEncodedIV.length "+urlEncodedIV.length());
return new String[] {urlEncodedData, urlEncodedIV};
}finally {
stream.close();
out.close();
}
}
/**
* Decrypts the String and serializes the object
* #param base64Data
* #param base64IV
* #return
* #throws Exception
*/
public Object decryptObject(String base64Data, String base64IV) throws Exception {
System.out.println("decryptObject "+base64Data);
System.out.println("decryptObject "+base64IV);
// Decode the data
byte[] encryptedData = Base64.decodeBase64(base64Data.getBytes());
// Decode the Init Vector
byte[] rawIV = Base64.decodeBase64(base64IV.getBytes());
System.out.println("rawIV "+rawIV.length);
for (int i=0;i < rawIV.length;i++ ){
System.out.println("---------"+rawIV[i]);
}
// Configure the Cipher
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec ivSpec = new IvParameterSpec(rawIV);
MessageDigest digest = MessageDigest.getInstance("SHA-256");
digest.update(keyString.getBytes());
byte[] key = new byte[16];
System.arraycopy(digest.digest(), 0, key, 0, key.length);
SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec); //////////////////////////////This is the error line
// Decrypt the data..
byte[] decrypted = cipher.doFinal(encryptedData);
// Deserialize the object
ByteArrayInputStream stream = new ByteArrayInputStream(decrypted);
ObjectInput in = new ObjectInputStream(stream);
Object obj = null;
try {
obj = in.readObject();
System.out.println("objobj "+obj);
}
catch(Exception e) {
//logger.debug("Unable to encrypt view id: "+id, e);
e.printStackTrace();
}finally {
stream.close();
in.close();
}
return obj;
}
}
This is the error line - cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
Do I need to add anything else? Thanks.
EDIT: Thanks, thanks worked. For some reason, I thought I am already decoding the data.
EDIT2: If the text to decode has + in it, then the decoded text will have space instead of +. So I had to replace all the spaces with + back when decrypting. Hopefully this helps someone.
The decryption process should be just reverse of encryption process.
Here in encryption you are doing URL encoding before returning it to user. So you must do URL decoding first in your decryption process.
Here is complete decryption process working with URL decoding:
public Object decryptObject(String base64Data, String base64IV) throws Exception {
System.out.println("decryptObject " + base64Data);
System.out.println("decryptObject " + base64IV);
String urlDecodedData=URLDecoder.decode(base64Data,"UTF-8");
// Decode the data
byte[] encryptedData = Base64.decodeBase64(urlDecodedData.getBytes());
String urlDecodedIV=URLDecoder.decode(base64IV,"UTF-8");
// Decode the Init Vector
byte[] rawIV = Base64.decodeBase64(urlDecodedIV.getBytes());
System.out.println("rawIV " + rawIV.length);
// Configure the Cipher
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec ivSpec = new IvParameterSpec(rawIV);
MessageDigest digest = MessageDigest.getInstance("SHA-256");
digest.update(keyString.getBytes());
byte[] key = new byte[16];
System.arraycopy(digest.digest(), 0, key, 0, key.length);
SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec); //////////////////////////////This is the error line
// Decrypt the data..
byte[] decrypted = cipher.doFinal(encryptedData);
// Deserialize the object
ByteArrayInputStream stream = new ByteArrayInputStream(decrypted);
ObjectInput in = new ObjectInputStream(stream);
Object obj = null;
try {
obj = in.readObject();
System.out.println("objobj " + obj);
} catch (Exception e) {
//logger.debug("Unable to encrypt view id: "+id, e);
e.printStackTrace();
} finally {
stream.close();
in.close();
}
return obj;
}
I have translate a C# based decrypt function into Java. It works fine and could be used to decrypted the passwords which have been encrypted by C# program.
Here is the source code:
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
public class TestDecrpt {
public static void main(String[] args) throws Exception {
String data = "encrypted data";
String sEncryptionKey = "encryption key";
byte[] rawData = new Base64().decode(data);
byte[] salt = new byte[8];
System.arraycopy(rawData, 0, salt, 0, salt.length);
Rfc2898DeriveBytes keyGen = new Rfc2898DeriveBytes(sEncryptionKey, salt);
byte[] IV = keyGen.getBytes(128 / 8);
byte[] keyByte = keyGen.getBytes(256 / 8);
Key key = new SecretKeySpec(keyByte, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(IV));
int pureDataLength = rawData.length - 8;
byte[] pureData = new byte[pureDataLength];
System.arraycopy(rawData, 8, pureData, 0, pureDataLength);
String plaintext = new String(cipher.doFinal(pureData), "UTF-8").replaceAll("\u0000", "");
System.out.println(plaintext);
}
}
I follow its algorithm to write the encrypt function. And codes is:
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.security.SecureRandom;
public class testEncrypt {
public static void main(String[] args) throws Exception {
String data = "Welcome2012~1#Welcome2012~1#Welcome2012~1#Welcome2012~1#Welcome2012~1#";
String sEncryptionKey = "encryption key"; # the same key
byte[] rawData = new Base64().decode(data);
SecureRandom random = new SecureRandom();
byte[] salt = new byte[8];
random.nextBytes(salt);
Rfc2898DeriveBytes keyGen = new Rfc2898DeriveBytes(sEncryptionKey, salt);
byte[] IV = keyGen.getBytes(128 / 8);
byte[] keyByte = keyGen.getBytes(256 / 8);
Key key = new SecretKeySpec(keyByte, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(IV));
byte[] out2 = cipher.doFinal(rawData);
byte[] out = new byte[8 + out2.length];
System.arraycopy(salt, 0, out, 0, 8);
System.arraycopy(out2, 0, out, 8, out2.length);
//String outStr=new String(out,"UTF-8");
String outStr = new Base64().encodeToString(out);
System.out.println(outStr);
System.out.print(outStr.length());
}
}
However, the encrypted data could not be decrypted correctly, it always return garbage codes, such as
ꉜ뙧巓妵峩枢펶땝ꉜ뙧巓妵峩枢펶땝ꉜ뙧巓�
Is there something wrong with the encrypt function?
================================================================================
[Update]
After changing the code to
byte[] rawData = data.getBytes("UTF-8");
The data could be encrypted and decrypted successfully.
However, the data which is encrypted in Java could not be correctly descrypted in C#.
Here is the C# version decrypt function:
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace Test
{
class Program
{
public static void Main(string[] args)
{
string data="EncryptedData";
string sEncryptionKey="EncryptionKey";
byte[] rawData = Convert.FromBase64String(data);
byte[] salt = new byte[8];
for (int i = 0; i < salt.Length; i++)
salt[i] = rawData[i];
Rfc2898DeriveBytes keyGenerator = new Rfc2898DeriveBytes(sEncryptionKey, salt);
Rijndael aes = Rijndael.Create();
aes.IV = keyGenerator.GetBytes(aes.BlockSize / 8);
aes.Key = keyGenerator.GetBytes(aes.KeySize / 8);
using (MemoryStream memoryStream = new MemoryStream())
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, aes.CreateDecryptor(), CryptoStreamMode.Write))
{
cryptoStream.Write(rawData, 8, rawData.Length - 8);
cryptoStream.Close();
byte[] decrypted = memoryStream.ToArray();
Console.Out.WriteLine(Encoding.Unicode.GetString(decrypted));
Console.In.ReadLine();
}
}
}
}
I find that the original code are using "Unicode" as output format,
Encoding.Unicode.GetString(decrypted)
so I change my Java code to "Unicode".
For Decrypt in Java:
String plaintext = new String(cipher.doFinal(pureData), "Unicode");
System.out.println(plaintext);
For Encrypt in Java:
byte[] rawData = data.getBytes("Unicode");
But using the C# code to decrypt the data which has been encrypted by the Java program still meet garbage codes.
How could I fix this issue? Is there any magical trick?
[Last Update]
After using "UTF-16LE" instead of "UTF-8", the issue has gone. It seems that "UTF-16LE" is the Java equivalent to the "Unicode" of C#.
This is the problem:
String data = "Welcome2012~1#Welcome2012~1#Welcome2012~1#Welcome2012~1#Welcome2012~1#";
byte[] rawData = new Base64().decode(data);
That text is not meant to be base64-encoded binary data. It's just text. Why are you trying to decode it as base64 data?
You want:
byte[] rawData = data.getBytes("UTF-8");
That way, when you later write:
String plaintext = new String(cipher.doFinal(pureData), "UTF-8")
.replaceAll("\u0000", "");
you're doing the reverse action. (Admittedly you probably shouldn't need the replaceAll call, but that's a different matter.)
For anything like this, you need to make sure that the steps you take on the way "out" are the reverse of the steps on the way "in". So in the correct code, you have:
Unencrypted text data => unencrypted binary data (encode via UTF-8)
Unencrypted binary data => encrypted binary data (encrypt with AES)
Encrypted binary data => encrypted text data (encode with base64)
So to reverse, we do:
Encrypted text data => encrypted binary data (decode with base64)
Encrypted binary data => unencrypted binary data (decrypt with AES)
Unencrypted binary data => unencrypted text data (decode via UTF-8)