I have two method for Encrypt-save and decrypt-load Object from file in Android Internal Storage.
Encrypt and save process is done without any problem, but when I want to load the object StreamCorruptedException occurs in inputStream = new ObjectInputStream(cipherInputStream);
I searched SO more and more but I did't find a solution for my problem. all other solutions are for socket life or like this.
my code is below:
private static byte[] iv = { (byte) 0xB1, (byte) 0x15, (byte) 0xB5,
(byte) 0xB7, (byte) 0x66, (byte) 0x43, (byte) 0x2F, (byte) 0xA4,
(byte) 0xB1, (byte) 0x15, (byte) 0x35, (byte) 0xC7, (byte) 0x66,
(byte) 0x58, (byte) 0x2F, (byte) 0x5F };
save method: (work well)
private static String saveToFile(Serializable object, String fileName,
Context ctx) {
try {
Cipher cipher = null;
cipher = Cipher.getInstance("DES");
SecretKey key = KeyGenerator.getInstance("DES").generateKey();
AlgorithmParameterSpec paramSpec = new IvParameterSpec(iv);
cipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
SealedObject sealedObject = null;
sealedObject = new SealedObject(object, cipher);
CipherOutputStream cipherOutputStream = null;
FileOutputStream fos = ctx.openFileOutput(fileName,
Context.MODE_PRIVATE);
cipherOutputStream = new CipherOutputStream(
new BufferedOutputStream(fos), cipher);
ObjectOutputStream outputStream = null;
outputStream = new ObjectOutputStream(cipherOutputStream);
outputStream.writeObject(sealedObject);
outputStream.close();
return "Save Complete!";
} catch (IOException e) {
e.printStackTrace();
return e.getMessage();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return e.getMessage();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
return e.getMessage();
} catch (InvalidKeyException e) {
e.printStackTrace();
return e.getMessage();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
return e.getMessage();
} catch (InvalidAlgorithmParameterException e) {
e.printStackTrace();
return e.getMessage();
}
}
Load method: (can't load object from cipherInputStream)
private static Serializable loadFromFile(String fileName, Context ctx) {
Cipher cipher = null;
Serializable userList = null;
try {
cipher = Cipher.getInstance("DES");
// Code to write your object to file
SecretKey key = KeyGenerator.getInstance("DES").generateKey();
AlgorithmParameterSpec paramSpec = new IvParameterSpec(iv);
cipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
CipherInputStream cipherInputStream = null;
FileInputStream fos = ctx.openFileInput(fileName);
cipherInputStream = new CipherInputStream(new BufferedInputStream(
fos), cipher);
ObjectInputStream inputStream = null;
inputStream = new ObjectInputStream(cipherInputStream);
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
SealedObject sealedObject = null;
sealedObject = (SealedObject) inputStream.readObject();
userList = (Serializable) sealedObject.getObject(cipher);
inputStream.close();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return e.getMessage();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
return e.getMessage();
} catch (InvalidKeyException e) {
e.printStackTrace();
return e.getMessage();
} catch (InvalidAlgorithmParameterException e) {
e.printStackTrace();
return e.getMessage();
} catch (FileNotFoundException e) {
e.printStackTrace();
return e.getMessage();
} catch (StreamCorruptedException e) {
e.printStackTrace();
return e.getMessage();
} catch (IOException e) {
e.printStackTrace();
return e.getMessage();
} catch (ClassNotFoundException e) {
e.printStackTrace();
return e.getMessage();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
return e.getMessage();
} catch (BadPaddingException e) {
e.printStackTrace();
return e.getMessage();
}
return userList;
}
public methods for save and load:
public Serializable loadPlayer(Context ctx) {
return loadFromFile("player.dat", ctx);
}
public String savePlayer(Player player, Context ctx) {
return saveToFile(player, "player.dat", ctx);
}
You're making at least two major mistakes.
You have to use the same key to decrypt as you used to encrypt. You can't just generate a random key and except it to be able to decrypt anything. Cryptology isn't magic. You will have to arrange for the decryption key to be preserved somehow, transmitted if necessary, securely, and used at the decryption step.
You're encrypting once with the SealedObject and again with the CipherOutputStream; then in the reverse direction you're decrypting once with the CipherInputStream and again via the SealedObject. This won't actually work, because the Cipher object isn't in comparable states at sender and receiver, and in any case it's pointless. Lose either the SealedObject or the Cipher streams.
Related
My program is able to create and write to a file using the path-file:
private static final String PUBLIC_KEY_FILE = "WebContent/Config/MyPublic.key";
private static final String PRIVATE_KEY_FILE = "WebContent/Config/MyPrivate.key";
And the correct files are generated within the folders according to the path declared above.
But then a FileNotFoundException error occurs when I try to read from those files using the path files:
private String REAL_PUBLIC_PATH = getServletContext().getRealPath("/WebContent/Config/MyPublic.key");
private String REAL_PRIVATE_PATH = getServletContext().getRealPath("/WebContent/Config/MyPrivate.key");
This is the lines of code that is causing the error:
PublicKey pubKey = readPublicKeyFromFile(this.REAL_PUBLIC_PATH);
PrivateKey privKey = readPrivateKeyFromFile(this.REAL_PRIVATE_PATH);
Which is tied to the variables REAL_PUBLIC_PATH and REAL_PUBLIC_PATH. Meaning there's something wrong with how the path file is being read.
My folder structure goes:
> MyProject
>Web-Content
>Config
>MyPublic.key
>MyPrivate.key
>WEB-INF
>META-INF
My full class code is below for context:
public class RSAEncryptionHelper extends HttpServlet {
private static final String PUBLIC_KEY_FILE = "WebContent/Config/MyPublic.key";
private static final String PRIVATE_KEY_FILE = "WebContent/Config/MyPrivate.key";
private String REAL_PUBLIC_PATH = getServletContext().getRealPath("/WebContent/Config/MyPublic.key");
private String REAL_PRIVATE_PATH = getServletContext().getRealPath("/WebContent/Config/MyPrivate.key");
public static void main(String[] args) throws IOException{
try
{
System.out.println("--GENERATE PUBLIC and PRIVATE KEY --");
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048); //1024 for normal securities
KeyPair keyPair = keyPairGenerator.generateKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
System.out.println("\n--PULLING OUT PARAMETERS WHICH MAKES KEYPAIR--\n");
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
RSAPublicKeySpec rsaPubKeySpec = keyFactory.getKeySpec(publicKey, RSAPublicKeySpec.class);
RSAPrivateKeySpec rsaPrivKeySpec = keyFactory.getKeySpec(privateKey, RSAPrivateKeySpec.class);
System.out.println("\n--SAVING PUBLIC KEY AND PRIVATE KEY TO FILES--\n");
RSAEncryptionHelper rsaObj = new RSAEncryptionHelper();
rsaObj.saveKeys(PUBLIC_KEY_FILE, rsaPubKeySpec.getModulus(), rsaPubKeySpec.getPublicExponent());
rsaObj.saveKeys(PRIVATE_KEY_FILE, rsaPrivKeySpec.getModulus(), rsaPrivKeySpec.getPrivateExponent());
}
catch (NoSuchAlgorithmException | InvalidKeySpecException e)
{
System.out.println(e);
}
}
private void saveKeys(String fileName, BigInteger mod, BigInteger exp) throws IOException {
FileOutputStream fos = null;
ObjectOutputStream oos = null;
try
{
System.out.println("Generating: " + fileName + "...");
fos = new FileOutputStream(fileName);
oos = new ObjectOutputStream(new BufferedOutputStream(fos));
oos.writeObject(mod);
oos.writeObject(exp);
System.out.println(fileName + "generated successfully");;
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (oos!=null)
{
oos.close();
if (fos!= null)
{
fos.close();
}
}
}
}
public PublicKey readPublicKeyFromFile(String fileName) throws IOException{
FileInputStream fis = null;
ObjectInputStream ois = null;
PublicKey publicKey = null;
try
{
fis = new FileInputStream(new File(fileName));
ois = new ObjectInputStream(fis);
BigInteger modulus = (BigInteger) ois.readObject();
BigInteger exponent = (BigInteger) ois.readObject();
//Get Public Key
RSAPublicKeySpec rsaPublicKeySpec = new RSAPublicKeySpec(modulus, exponent);
KeyFactory fact = KeyFactory.getInstance("RSA");
publicKey = fact.generatePublic(rsaPublicKeySpec);
return publicKey;
}
catch (IOException e)
{
e.printStackTrace();
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
catch (InvalidKeySpecException e)
{
e.printStackTrace();
}
finally
{
if (ois != null)
{
ois.close();
if (fis != null)
{
fis.close();
}
}
}
return publicKey;
}
public PrivateKey readPrivateKeyFromFile(String fileName) throws IOException{
FileInputStream fis = null;
ObjectInputStream ois = null;
PrivateKey privateKey = null;
try
{
fis = new FileInputStream(new File(fileName));
ois = new ObjectInputStream(fis);
BigInteger modulus = (BigInteger) ois.readObject();
BigInteger exponent = (BigInteger) ois.readObject();
//Get Public Key
RSAPrivateKeySpec rsaPrivateKeySpec = new RSAPrivateKeySpec(modulus, exponent);
KeyFactory fact = KeyFactory.getInstance("RSA");
privateKey = fact.generatePrivate(rsaPrivateKeySpec);
return privateKey;
}
catch (IOException e)
{
e.printStackTrace();
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
catch (InvalidKeySpecException e)
{
e.printStackTrace();
}
finally
{
if (ois != null)
{
ois.close();
if (fis != null)
{
fis.close();
}
}
}
return privateKey;
}
public byte[] encryptData(String data) throws IOException {
System.out.println("\n--ENCRYPTION STARTED--");
System.out.println("Data Before Encryption: " + data);
byte[] dataToEncrypt = data.getBytes();
byte[] encryptedData = null;
try
{
PublicKey pubKey = readPublicKeyFromFile(this.REAL_PUBLIC_PATH);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
encryptedData = cipher.doFinal(dataToEncrypt);
System.out.println("Encrypted Data: " + encryptedData);
}
catch (IOException e)
{
e.printStackTrace();
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
catch (InvalidKeyException e)
{
e.printStackTrace();
}
catch (IllegalBlockSizeException e)
{
e.printStackTrace();
}
catch (BadPaddingException e)
{
e.printStackTrace();
}
catch (NoSuchPaddingException e)
{
e.printStackTrace();
}
System.out.println("--ENCRYPTION COMPLETED--");
return encryptedData;
}
public String decryptData(byte[] data) throws IOException {
System.out.println("\n--DECRYPTION STARTED--");
byte[] decryptedData = null;
String decData = "";
try
{
PrivateKey privateKey = readPrivateKeyFromFile(this.REAL_PRIVATE_PATH);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
decryptedData = cipher.doFinal(data);
decData = new String(decryptedData);
System.out.println("Decrypted Data: " + decData);
return decData;
}
catch (IOException e)
{
e.printStackTrace();
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
catch (NoSuchPaddingException e)
{
e.printStackTrace();
}
catch (InvalidKeyException e)
{
e.printStackTrace();
}
catch ( IllegalBlockSizeException e)
{
e.printStackTrace();
}
catch (BadPaddingException e)
{
e.printStackTrace();
}
System.out.println("--DECRYPTION COMPLETED--");
return decData;
}
}
Do your keys already exist before you run the program? if not, then getRealPath to a file that doesn't exist isn't going to work.
But that shouldn't matter because if you can access the files using private static final String PUBLIC_KEY_FILE, why not use that same path to read the files.
So instead of this:
PrivateKey privateKey = readPrivateKeyFromFile(this.REAL_PRIVATE_PATH);
Why not do this?
PrivateKey privateKey = readPrivateKeyFromFile(this.PRIVATE_KEY_FILE);
If you've sucessfully written to a file using PRIVATE_KEY_FILE path, you can also read from the same path.
I have the following Java code which correctly decrypts a base64 encoded payload:
private static byte[] decryptPBKDF2WithBC(char[] password, byte[] data, byte[] salt, byte[] iv)
throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException,
InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
PBEParametersGenerator generator = new PKCS5S2ParametersGenerator();
generator.init(PBEParametersGenerator.PKCS5PasswordToUTF8Bytes(password), salt,1024);
KeyParameter params = (KeyParameter)generator.generateDerivedParameters(256);
byte[] endcoded = params.getKey();
SecretKey key = new SecretKeySpec(endcoded, "AES");
Cipher ciph = Cipher.getInstance("AES/CBC/PKCS5Padding");
ciph.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
return ciph.doFinal(data);
}
public String decrypt(String encrypted){
String salt = SALT;
String password = PASSWORD;
String[] parts = encrypted.split("--");
if (parts.length != 2) return null;
byte[] encryptedData = Base64.decode(parts[0], Base64.DEFAULT);
byte[] iv = Base64.decode(parts[1], Base64.DEFAULT);
byte[] result = null;
try {
result = decryptPBKDF2WithBC(password.toCharArray(), encryptedData, salt.getBytes(), iv);
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeySpecException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidAlgorithmParameterException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
catch(Exception e){
e.printStackTrace();
}
try {
return new String(result, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
catch(Exception e){
e.printStackTrace();
return null;
}
}
The problem I'm having is that I need to port this to IOS. I've searched for several examples online, but I haven't been able to find one that uses a password, a salt and an IV. Are there any security/IOS experts who know enough about the IOS crypto libraries to at least point me in the right direction (which libraries to use or any code samples)?
Use RNCryptor if possible.
On iOS use the CommonCrypto library for the decryption along with the NSData Base64 methods.
You need to add Security.framework and you can look at the header files for the methods and more information.
Iam using TripleDes /cbc/pkcs7padding in C#.net to encrypt file.
and i need to decrypt in java.In java am using DESede/CBC/PKcs5padding
But the file is decrypted,but corrupted.
*In java is it possible to use pkcs7padding?
or any other solution to decrypt the file in java with encrypted using pkcs7 padding
C# code
namespace EncryptEpubFiles
{
public class Encryptor
{
public static bool EncryptBook(FileInfo fileToEncrypt,string outPathWithoutExtension,string keyString)
{
try
{
byte[] encryptedFileByteArray;
//Start Encryption service provider
TripleDESCryptoServiceProvider tDES = new TripleDESCryptoServiceProvider();
//Read all bytes from input file
byte[] _fileByteArray = File.ReadAllBytes(fileToEncrypt.FullName);
tDES.Key = GetBytes(keyString);
tDES.Mode = CipherMode.CBC;
//tDES.Padding = PaddingMode.PKCS7;
tDES.Padding = PaddingMode.PKCS7;
ICryptoTransform trans = tDES.CreateEncryptor();
//Create Encrypted file byte array
encryptedFileByteArray = (trans.TransformFinalBlock(_fileByteArray, 0, ((_fileByteArray).Length)));
//Write Encrypted file byte array to a filr with proper extension
System.IO.File.WriteAllBytes((outPathWithoutExtension + ".akr"), encryptedFileByteArray);
return true;
}
catch (Exception ex)
{
return false;
}
}
Java code
public class DecryptFinal {
private static Cipher dcipher;
private static byte[] iv = {
(byte)0xB2, (byte)0x12, (byte)0xD5, (byte)0xB2,
(byte)0x44, (byte)0x21, (byte)0xC3, (byte)0xC3
};
public static void main(String[] args){
try {
String s = "123456789123456789111234";
AlgorithmParameterSpec paramSpec = new IvParameterSpec(iv);
SecretKeyFactory keyfactory=SecretKeyFactory.getInstance("DESede");
byte[] encodedkey=s.getBytes();
System.out.println();
SecretKey key = keyfactory.generateSecret(new DESedeKeySpec(encodedkey));
System.out.println(new DESedeKeySpec(encodedkey));
SecretKeySpec(encodedKey,0,encodedKey.length,"DESede" );
dcipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
FileInputStream fs =new FileInputStream("E:\\Test1\\Test1\\Encrypted Files\\Wedding bells.akr");
FileOutputStream os= new FileOutputStream("E:\\Test1\\Test1\\Encrypted Files\\Encrypted Files\\E-pub Totorials");
byte[] buf = new byte[1024];// bytes read from stream will be decrypted
CipherInputStream cis = new CipherInputStream(fs, dcipher);// read in the decrypted bytes and write the clear text to out
int numRead = 0;
while ((numRead = cis.read(buf)) >= 0) {
os.write(buf, 0, numRead);
}
cis.close();// close all streams
fs.close();
os.close();
}
catch(FileNotFoundException e) {
System.out.println("File Not Found:" + e.getMessage());
return;
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidAlgorithmParameterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
System.out.println("I/O Error:" + e.getMessage());
}
catch (InvalidKeySpecException e) {
// TODO: handle exception
e.printStackTrace();
}
I have an application consisting of three services: Client, Server and TokenService. In order to access data on the Server, Client has to obtain SecurityToken object from TokenService. The communication between parties is encrypted using shared keys (Client and TokenService share a key 'A' and TokenService and Server share a different key 'B'). When Client sends request to TokenService then the communication is encrypted with 'A'. When TokenService returns SecurityToken object, this object is encrypted with B and A like this: ((SecurityToken)B)A). This doubly encrypted object first goes back to Client, Client decrypts it with A, puts it into another object, attaches some additional information (String with request) and sends it to the Server where SecurityToken gets decrypted with B.
Everything works fine until I'am decrypting SecurityToken object on the server side. I get Exception:
javax.crypto.IllegalBlockSizeException: Input length must be multiple of 16 when decrypting with padded cipher
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:749)
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:675)
at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:313)
at javax.crypto.Cipher.doFinal(Cipher.java:2087)
at mds.hm5.sharedclasses.Decryptor.decryptData(Decryptor.java:40)
at mds.hm5.tokenservice.Main2.main(Main2.java:28)
I was able to recreate this error (without remote communication between parties) like this:
public static void main(String[] args) {
SecurityToken s = new SecurityToken(false, "2");
try {
byte[] bytes = Encryptor.getBytesFromObject(s);
bytes = Encryptor.encryptData(bytes, "secretkey1");
bytes = Encryptor.encryptData(bytes, "secretkey2");
bytes = Base64.encodeBase64(bytes);
System.out.println(bytes);
bytes = Base64.decodeBase64(bytes);
bytes = Decryptor.decryptData(bytes, "secretkey2");
bytes = Decryptor.decryptData(bytes, "secretkey1");
SecurityToken s2 = (SecurityToken) Decryptor.getObjectFromBytes(bytes);
System.out.println(s2.getRole());
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
I have no idea what I'am doing wrong here. Is it impossible to create two layers of encryption just like that? Am I missing something?
Additional information:
Here is my Encryptor class:
public class Encryptor {
public static byte[] encryptData(byte[] credentials, String key){
Cipher c;
SecretKeySpec k;
byte[] byteCredentials = null;
byte[] encryptedCredentials = null;
byte[] byteSharedKey = null;
try {
byteCredentials = getBytesFromObject(credentials);
byteSharedKey = getByteKey(key);
c = Cipher.getInstance("AES");
k = new SecretKeySpec(byteSharedKey, "AES");
c.init(Cipher.ENCRYPT_MODE, k);
encryptedCredentials = c.doFinal(byteCredentials);
} catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return encryptedCredentials;
}
public static byte[] getBytesFromObject(Object credentials) throws IOException{
//Hmmm.... now I'm thinking I should make generic type for both: Token and ITU_Credentials object, that would have this getBytes and getObject methods.
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput out = null;
byte[] newBytes = null;
try {
out = new ObjectOutputStream(bos);
out.writeObject(credentials);
newBytes = bos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
} finally {
out.close();
bos.close();
}
return newBytes;
}
private static byte[] getByteKey(String key) throws UnsupportedEncodingException, NoSuchAlgorithmException{
//Converting key to SHA-1 and trimming to mach maximum lenght of key
byte[] bkey = key.getBytes("UTF-8");
MessageDigest sha = MessageDigest.getInstance("SHA-1");
bkey = sha.digest(bkey);
bkey = Arrays.copyOf(bkey, 16);
return bkey;
}
And here is my Decryptor class:
public class Decryptor {
public static byte[] decryptData(byte[] encryptedCredentials, String key){
Cipher c;
SecretKeySpec k;
byte[] byteSharedKey = null;
byte[] byteObject = null;
try {
byteSharedKey = getByteKey(key);
c = Cipher.getInstance("AES");
k = new SecretKeySpec(byteSharedKey, "AES");
c.init(Cipher.DECRYPT_MODE, k);
byteObject = c.doFinal(encryptedCredentials);
} catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return byteObject;
}
public static Object getObjectFromBytes(byte[] credentials) throws IOException, ClassNotFoundException{
ByteArrayInputStream bis = new ByteArrayInputStream(credentials);
ObjectInput in = null;
ITU_Credentials credentialsObj = null;
try {
in = new ObjectInputStream(bis);
credentialsObj = (ITU_Credentials)in.readObject();
} finally {
bis.close();
in.close();
}
return credentialsObj;
}
private static byte[] getByteKey(String key) throws UnsupportedEncodingException, NoSuchAlgorithmException{
//Converting key to SHA-1 and trimming to mach maximum lenght of key
byte[] bkey = key.getBytes("UTF-8");
MessageDigest sha = MessageDigest.getInstance("SHA-1");
bkey = sha.digest(bkey);
bkey = Arrays.copyOf(bkey, 16);
return bkey;
}
public static void main(String[] args) {
new Encryptor();
}
}
EDIT:
As advised, I replaced all e.printStackTrace(); with throw new RuntimeException(e); in the Decriptor class to properly throw exceptions:
public class Decryptor {
public static byte[] decryptData(byte[] encryptedCredentials, String key){
Cipher c;
SecretKeySpec k;
byte[] byteSharedKey = null;
byte[] byteObject = null;
try {
byteSharedKey = getByteKey(key);
c = Cipher.getInstance("AES");
k = new SecretKeySpec(byteSharedKey, "AES");
c.init(Cipher.DECRYPT_MODE, k);
byteObject = c.doFinal(encryptedCredentials);
} catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
throw new RuntimeException(e);
} catch (InvalidKeyException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
} catch (IllegalBlockSizeException e) {
throw new RuntimeException(e);
} catch (BadPaddingException e) {
throw new RuntimeException(e);
}
return byteObject;
}
public static Object getObjectFromBytes(byte[] credentials) throws IOException, ClassNotFoundException{
ByteArrayInputStream bis = new ByteArrayInputStream(credentials);
ObjectInput in = null;
ITU_Credentials credentialsObj = null;
try {
in = new ObjectInputStream(bis);
credentialsObj = (ITU_Credentials)in.readObject();
} finally {
bis.close();
in.close();
}
return credentialsObj;
}
private static byte[] getByteKey(String key) throws UnsupportedEncodingException, NoSuchAlgorithmException{
//Converting key to SHA-1 and trimming to mach maximum lenght of key
byte[] bkey = key.getBytes("UTF-8");
MessageDigest sha = MessageDigest.getInstance("SHA-1");
bkey = sha.digest(bkey);
bkey = Arrays.copyOf(bkey, 16);
return bkey;
}
public static void main(String[] args) {
new Encryptor();
}
}
Now the exception looks as follows:
Exception in thread "main" java.lang.RuntimeException: javax.crypto.IllegalBlockSizeException: Input length must be multiple of 16 when decrypting with padded cipher
at mds.hm5.sharedclasses.Decryptor.decryptData(Decryptor.java:51)
at mds.hm5.tokenservice.Main2.main(Main2.java:28)
Caused by: javax.crypto.IllegalBlockSizeException: Input length must be multiple of 16 when decrypting with padded cipher
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:749)
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:675)
at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:313)
at javax.crypto.Cipher.doFinal(Cipher.java:2087)
at mds.hm5.sharedclasses.Decryptor.decryptData(Decryptor.java:40)
... 1 more
I think the root of your problem is:
byte[] bytes = Encryptor.getBytesFromObject(s);
bytes = Encryptor.encryptData(bytes, "secretkey1");
which goes to:
//etc.//
byte[] encryptedCredentials = null;
byte[] byteSharedKey = null;
try {
byteCredentials = getBytesFromObject(credentials);
//Whoops! credentials is already a byte array.
//etc.//
catch (and eat) exception.....
return encryptedCredentials;
And, since you eat the exception and just return null, as home has advised against in the comments, then it keeps moving until it gets to the decryption step, where it throws an exception you hadn't anticipated (when it fails to decrypt, an IllegalBlockSizeException which is none of the eight types of Exception that you catch there), and gives you something useful.
That's what I think is going on anyway.
Is there any way to get the same result as doing in MySQL
SELECT AES_ENCRYPT("text", "key")
using a Java function?
And if possible, what's the other function to simulate the AES_DECRYPT.
If you need the code to decrypt the algorithm is here JAVA
public static String aes_decrypt(String passwordhex, String strKey) throws Exception {
try {
byte[] keyBytes = Arrays.copyOf(strKey.getBytes("ASCII"), 16);
SecretKey key = new SecretKeySpec(keyBytes, "AES");
Cipher decipher = Cipher.getInstance("AES");
decipher.init(Cipher.DECRYPT_MODE, key);
char[] cleartext = passwordhex.toCharArray();
byte[] decodeHex = Hex.decodeHex(cleartext);
byte[] ciphertextBytes = decipher.doFinal(decodeHex);
return new String(ciphertextBytes);
} catch (Exception e) {
e.getMessage();
}
return null;
}
It received a standard hex format string but variable and returns the password. Test with those in main method
System.out.println(aes_encrypt("your_string_password", "your_string_key"));
System.out.println(aes_decrypt("standard_hex_format_string ", "your_string_key"));
firstable test only with encrypt, then just with decrypt.
By the way you must install 'commons-codec-1.6.jar' so you can use the Hex class
http://commons.apache.org/proper/commons-codec/download_codec.cgi
Greetings from Ecuador, Ibarra
Ok, I've managed to get it working like this.
MySQL Query:
SELECT HEX(aes_encrypt("password", "0123456789012345"));
Java function:
public static String aes_encrypt(String password, String strKey) {
try {
byte[] keyBytes = Arrays.copyOf(strKey.getBytes("ASCII"), 16);
SecretKey key = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] cleartext = password.getBytes("UTF-8");
byte[] ciphertextBytes = cipher.doFinal(cleartext);
return new String(Hex.encodeHex(ciphertextBytes));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} return null;
}
in my case i just code like this
private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();
public static String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = HEX_ARRAY[v >>> 4];
hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
}
return new String(hexChars);
}
and than create method aes 128
public static String aes_encrypt(String password, String strKey) {
try {
byte[] keyBytes = Arrays.copyOf(strKey.getBytes("ASCII"), 16);
SecretKey key = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] cleartext = password.getBytes("UTF-8");
byte[] ciphertextBytes = cipher.doFinal(cleartext);
return new String(bytesToHex(ciphertextBytes));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}
example :
mysql code
SELECT HEX(aes_encrypt("text", "0123456889812345"))
java code
System.out.println(aes_encrypt("text", "0123456889812345"));