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.
Related
I am developing a program for Encryption and Decryption , the Encryption is working fine, but the Decryption is throwing error.
I am not able to find, What is the problem in that code??
key.txt
ssshhhhhhhhhhh!!!!
plaintext.txt
naddarbhatia.com
public class hello {
private static SecretKeySpec secretKey;
private static byte[] key;
public static void setKey(String myKey)
{
MessageDigest sha = null;
try {
key = myKey.getBytes("UTF-8");
sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 16);
secretKey = new SecretKeySpec(key, "AES");
}
catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
public static String encrypt(String strToEncrypt, String secret)
{
try
{
setKey(secret);
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));
}
catch (Exception e)
{
System.out.println("Error while encrypting: " + e.toString());
}
return null;
}
public static String decrypt(String strToDecrypt, String secret)
{
try
{
setKey(secret);
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));
}
catch (Exception e)
{
System.out.println("Error while decrypting: " + e.toString());
}
return null;
}
static String readFile(String path, Charset encoding)
throws IOException
{
byte[] encoded = Files.readAllBytes(Paths.get(path));
return new String(encoded, encoding);
}
public static void main(String[] args) throws IOException
{
String en_de_flag = args[0];
String secretKey="";
try {
secretKey = readFile("/Users/amulbhatia/Documents/EclipseProjects/HelloProject/src/key.txt",StandardCharsets.UTF_8);
//System.out.println(secretKey);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String originalString="";
String encryptedString="";
try {
originalString = readFile("/Users/amulbhatia/Documents/EclipseProjects/HelloProject/src/plaintext.txt",StandardCharsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
}
if(en_de_flag.equals("0")) {
encryptedString = hello.encrypt(originalString, secretKey) ;
PrintWriter out = new PrintWriter("encrypt.txt");
out.println(encryptedString);
System.out.println("Encrypted File Generated !! 'encrypt.txt' , Please check now");
out.close();
}
if(en_de_flag.equals("1")) {
String decryptedFileContent = readFile("/Users/amulbhatia/Documents/EclipseProjects/HelloProject/src/encrypt.txt",StandardCharsets.UTF_8);
System.out.println("decryptedFileContent:" + decryptedFileContent);
System.out.println("Secret Key:" + secretKey);
String decryptedString = hello.decrypt(decryptedFileContent, secretKey) ;
//System.out.println("Read Encrypted File, Now Decrypting..");
//System.out.println(decryptedString);
}
}}
STACKTRACE
java.lang.IllegalArgumentException: Input byte array has incorrect ending byte at 44
at java.base/java.util.Base64$Decoder.decode0(Base64.java:771)
at java.base/java.util.Base64$Decoder.decode(Base64.java:535)
at java.base/java.util.Base64$Decoder.decode(Base64.java:558)
at hello.decrypt(hello.java:63)
at hello.main(hello.java:12
8)
While executing the above code at command line with argument as '0' the encrypt.txt file will be generated with the encrypted content, and after that when I entered argument as '1' it reads the encrypted file 'encrypt.txt' and 'key.txt' and calls the decrypt function where the same function is getting failed, pl help
That error is thrown by the Base64 decoder because your ciphertext ends with a line terminator, written by the PrintWriter.
Just .trim() your decryptedFileContent (which is actually the encryptedfilecontent...) to remove the line break.
When I encrypt the password !QAZxdr5 by the code below:
public static String encryptPassword(String msg) {
try {
KeySpec keySpec = new DESKeySpec(msg.getBytes());
SecretKey key = SecretKeyFactory.getInstance("DES").generateSecret(keySpec);
Cipher ecipher = Cipher.getInstance(key.getAlgorithm());
ecipher.init(Cipher.ENCRYPT_MODE, key);
//Encode the string into bytes using utf-8
byte[] utf8 = msg.getBytes("UTF8");
//Encrypt
byte[] enc = ecipher.doFinal(utf8);
//Encode bytes to base64 to get a string
return new String(Base64.getEncoder().encode(enc));
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (InvalidKeySpecException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
I got the output: QQiu2a4NT9YfDAtmHjbk1A==
Now I try to create the decryption for this:
public static String decrypt(String msg) {
try {
KeySpec keySpec = new DESKeySpec(msg.getBytes());
SecretKey key =
SecretKeyFactory.getInstance("DES").generateSecret(keySpec);
Cipher decipher = Cipher.getInstance(key.getAlgorithm());
decipher.init(Cipher.DECRYPT_MODE, key);
// Decode base64 to get bytes
byte[] dec = Base64.getDecoder().decode(msg.getBytes("UTF-8"));
//Decrypt
byte[] utf8 = decipher.doFinal(dec);
//Decode using utf-8
return new String(utf8, "UTF8");
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (InvalidKeySpecException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}
However, it doesn't work properly as it returned null :(. Can you please help to check where I'm wrong?
Normally, Base64 encoding of !QAZxdr5 is IVFBWnhkcjU=, however, your code uses a key to encode extra AFAI understand, that's why you get QQiu2a4NT9YfDAtmHjbk1A==. So, decrypt() method needs to know also the key generated already, nonetheless, yours wouldn't.
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.util.Base64;
class EncryptDecryptTest {
public static void main(String[] args) throws Exception {
String key = "it's our key ~~~where is my +1 karma ??~~~ - soner";
String ciphertext = encrypt(key, "!QAZxdr5");
String decrypted = decrypt(key, ciphertext.trim());
String encrypted = encrypt(key, decrypted.trim());
if (ciphertext.contentEquals(encrypted.trim())) {
System.out.println("decrypted!");
} else {
System.out.println("wrong key!");
}
}
public static String encrypt(String key, String data)
throws GeneralSecurityException {
DESKeySpec desKeySpec = new DESKeySpec(key.getBytes(StandardCharsets.UTF_8));
SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("DES");
SecretKey secretKey = secretKeyFactory.generateSecret(desKeySpec);
byte[] dataBytes = data.getBytes(StandardCharsets.UTF_8);
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
return Base64.getEncoder().encodeToString(cipher.doFinal(dataBytes));
}
public static String decrypt(String key, String data)
throws GeneralSecurityException {
byte[] dataBytes = Base64.getDecoder().decode(data);
DESKeySpec desKeySpec = new DESKeySpec(key.getBytes(StandardCharsets.UTF_8));
SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("DES");
SecretKey secretKey = secretKeyFactory.generateSecret(desKeySpec);
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] dataBytesDecrypted = (cipher.doFinal(dataBytes));
return new String(dataBytesDecrypted);
}
}
As a side note,
The fact that return new String(Base64.getEncoder().encode(enc)); uses toString() method of array
should be return Base64.getEncoder().encodeToString(enc); in order to get expected encoded datum.
In DES encryption, it uses the same key to encrypt and decrypt a message.
So for both operations you need to have the same key.
In your case, you have used the same string as the key and as the password.
public static String encryptPassword(String msg) {
try {
KeySpec keySpec = new DESKeySpec(msg.getBytes());
In above code segment when creating new DESKeySpec object, you need to pass the key as well.
public static String decrypt(String msg) {
try {
KeySpec keySpec = new DESKeySpec(msg.getBytes());
Even in above decypt method you have to pass the same key you have used in encrypt method.
But in this you have given the encoded string to generate the key.
That is where you have gone wrong.
So i suggest you to change the methods parameters by adding one more parameter as key and then pass the same value for key in both methods.
public static String encryptPassword(String msg, String keySp) {
try {
KeySpec keySpec = new DESKeySpec(keySp.getBytes());
}
public static String decrypt(String msg, String keySp) {
try {
KeySpec keySpec = new DESKeySpec(keySp.getBytes());
}
I have included only the lines that needed to be changed.
You can call those methods by,
String key = "!QAZxdr5";
String password = "!QAZxdr5";
String encriptedPassword = encryptPassword(password, key);
System.out.println(decrypt(encriptedPassword, key));
I am using the encryption class in Objective C for my iPhone app but I am struggling to get the same functionality working in JAVA from my android app. My encryption code is below:
NSString * _secret = #"password";
NSString * _key = #"1428324560542678";
StringEncryption *crypto = [[StringEncryption alloc] init];
NSData *_secretData = [_secret dataUsingEncoding:NSUTF8StringEncoding];
CCOptions padding = kCCOptionPKCS7Padding;
NSData *encryptedData = [crypto encrypt:_secretData key:[_key dataUsingEncoding:NSUTF8StringEncoding] padding:&padding];
I have tried to replicate it in JAVA but I get a different string when I encode the same data. So I am doing something wrong but I can't figure it out. Here is my JAVA code:
byte[] key = "1428324560542678".getBytes();
Cipher c = null;
try {
c = Cipher.getInstance("AES/ECB/PKCS7Padding");
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SecretKeySpec k = new SecretKeySpec(key, "AES");
try {
c.init(Cipher.ENCRYPT_MODE, k);
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
EditText tv1passwordText = (EditText) findViewById(R.id.password);
String password = URLEncoder.encode(tv1passwordText.getText().toString(), "UTF-8");
byte[] encryptedData = c.doFinal( password.getBytes());
Can anyone see where I am going wrong?
Based on the comments below I added getBytes but the strings produced are still different:
byte[] key = null;
try {
key = "1428324560542678".getBytes("UTF-8");
} catch (UnsupportedEncodingException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
Cipher c = null;
try {
c = Cipher.getInstance("AES/ECB/PKCS7Padding");
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SecretKeySpec k = new SecretKeySpec(key, "AES");
try {
c.init(Cipher.ENCRYPT_MODE, k);
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
EditText tv1passwordText = (EditText) findViewById(R.id.password);
byte[] password = tv1passwordText.getText().toString().getBytes("UTF-8");
byte[] encryptedData = c.doFinal(password);
Here is a sample of encryption and decryption:
public static SecretKey generateKey() throws NoSuchAlgorithmException, InvalidKeySpecException {
return secret = new SecretKeySpec(password.getBytes(), "AES");
}
public static byte[] encryptMsg(String message, SecretKey secret) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidParameterSpecException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
/* Encrypt the message. */
Cipher cipher = null;
cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secret);
byte[] cipherText = cipher.doFinal(message.getBytes("UTF-8"));
return cipherText;
}
public static String decryptMsg(byte[] cipherText, SecretKey secret) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidParameterSpecException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException {
/* Decrypt the message, given derived encContentValues and initialization vector. */
Cipher cipher = null;
cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secret);
String decryptString = new String(cipher.doFinal(cipherText), "UTF-8");
return decryptString;
}
To encrypt:
SecretKey secret = EncUtil.generateKey();
EncUtil.encryptMsg(<String to Encrypt>, secret))
to decrypt
EncUtil.decryptMsg(<byte[]>, secret))
Instead of using ECB, you ought to use CBC or CTR if possible. ECB is insecure.
It looks like your Objective-C code is using UTF-8 encoding, but you're not specifying this in your Java code. Use getBytes("UTF-8").
One thing that I've noticed that has caused problems in the past is that the iOS string being encrypted is actually "Hello World\0", eg the string to be encrypted with an extra null at the end. so try adding a \0 to the end of your string in Java and see if it produces the same results.
Additionally, the URLEncoder step on java may be introducing extra control characters and other things that are not present on the iOS side. It may be worthwhile to compare the text after this with the text going into the iOS encryption step to ensure that they are exactly the same
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"));