Java AES/CFB8/NoPadding encryption and Charset - java

I'm trying to encrypt and decrypt Strings in Java and PHP, so i use AES/CFB8/NoPadding that sould work on both sides.
Now my Cryptor works quit well with Latin Characters, as long as i set the Charset to Latin. But when i set it to UTF-8 (which is what i use in my DB), the encryption is not properly done.
Here is the output:
/*
* Latin (ISO-8859-1) output:
* Original: MiiiMüäöMeeʞ
* Encoded: rQ¶[ÉÐRíD
* Decoded: MiiiMüäöMee?
*
* UTF-8 output:
* Original: MiiiMüäöMeeʞ
* Encoded: rQ�[�
* Decoded: Mii0SS1])_�ELJI�S�;�W��W?*
*/
Since "ʞ" is not a latin character, I understand it can not be encrypted properly. But why does UTF-8 not work?
public class Cryptor {
private Cipher cipher;
private String secretKey = "1234567890qwertz";
private String iv = "1234567890qwertz";
private SecretKey keySpec;
private IvParameterSpec ivSpec;
private Charset CHARSET = Charset.forName("ISO-8859-1"); // ISO-8859-1 vs. UTF-8
public Cryptor() throws CryptingException {
keySpec = new SecretKeySpec(secretKey.getBytes(CHARSET), "AES");
ivSpec = new IvParameterSpec(iv.getBytes(CHARSET));
try {
cipher = Cipher.getInstance("AES/CFB8/NoPadding");
} catch (NoSuchAlgorithmException e) {
throw new SecurityException(e);
} catch (NoSuchPaddingException e) {
throw new SecurityException(e);
}
}
public String decrypt(String input) throws CryptingException {
try {
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
return new String(cipher.doFinal(input.getBytes(CHARSET)), CHARSET).trim();
} catch (IllegalBlockSizeException e) {
throw new SecurityException(e);
} catch (BadPaddingException e) {
throw new SecurityException(e);
} catch (InvalidKeyException e) {
throw new SecurityException(e);
} catch (InvalidAlgorithmParameterException e) {
throw new SecurityException(e);
}
}
public String encrypt(String input) throws CryptingException {
try {
cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
return new String(cipher.doFinal(input.getBytes(CHARSET)), CHARSET).trim();
} catch (InvalidKeyException e) {
throw new SecurityException(e);
} catch (InvalidAlgorithmParameterException e) {
throw new SecurityException(e);
} catch (IllegalBlockSizeException e) {
throw new SecurityException(e);
} catch (BadPaddingException e) {
throw new SecurityException(e);
}
}
public static void main(String Args[]) {
try {
Cryptor c = new Cryptor();
String original = "MiiiMüäöMeeʞ";
System.out.println("Original: " + original);
String encrypted = c.encrypt("MiiiMüäöMeeʞ");
System.out.println("Encoded: " + encrypted);
System.out.println("Decoded: " + c.decrypt(encrypted));
} catch (CryptingException e) {
e.printStackTrace();
}
}
class CryptingException extends RuntimeException {
private static final long serialVersionUID = 7123322995084333687L;
public CryptingException() {
super();
}
public CryptingException(String message) {
super(message);
}
}
}

I think turning the encrypted bytes into a String is a bad idea. The bytes are not valid for any encoding, they are random.
You need to encode the resulting byte[] to base64 to get a consistent outcome. See sun.misc.BASE64Encoder/sun.misc.BASE64Decoder.
Here is an example of decoding a base64 String to a byte[], the reverse process is very similar.
You can declare the decoder/encoder and the top of the class:
private final BASE64Decoder base64Decoder = new BASE64Decoder();
private final BASE64Encoder base64Encoder = new BASE64Encoder();
Then in your decypt method you need to call
return new String(cipher.doFinal(base64Decoder.decodeBuffer(input)), CHARSET);
And in your encrypt method
return base64Encoder.encode(cipher.doFinal(input.getBytes(CHARSET)));
Output using UTF-8:
Original: MiiiMüäöMeeʞ
Encoded: clEUtlv2ALXsKYw4ivOfwQ==
Decoded: MiiiMüäöMeeʞ
One side note is that it's not strictly speaking good practice to use packages from sun.* as they are not part of the java spec and hence may change/vanish from version to version.
Here is a little article on moving to the Apache Commons Codec implementation.
This is also a similar class in the Guava API.

Thanks alot for that answer, it really helped me alot.
Here is the working code i use to encrypt and decrypt JSON stuff in JAVA and PHP:
JAVA
/**
* Is used for encrypting and decrypting Strings and JSONObjects. <br>
* The JSON Objects can then be sent to a PHP script where they can be encrypted and decrypted with the same algorithm.
* #throws CryptingException
*/
public class Cryptor {
private Cipher cipher;
private String secretKey = "1234567890qwertz";
private String iv = "1234567890qwertz";
private final String CIPHER_MODE = "AES/CFB8/NoPadding";
private SecretKey keySpec;
private IvParameterSpec ivSpec;
private Charset CHARSET = Charset.forName("UTF8");
public Cryptor() throws CryptingException {
keySpec = new SecretKeySpec(secretKey.getBytes(CHARSET), "AES");
ivSpec = new IvParameterSpec(iv.getBytes(CHARSET));
try {
cipher = Cipher.getInstance(CIPHER_MODE);
} catch (NoSuchAlgorithmException e) {
throw new SecurityException(e);
} catch (NoSuchPaddingException e) {
throw new SecurityException(e);
}
}
/**
* #param input A "AES/CFB8/NoPadding" encrypted String
* #return The decrypted String
* #throws CryptingException
*/
public String decrypt(String input) throws CryptingException {
try {
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
return new String(cipher.doFinal(DatatypeConverter.parseBase64Binary(input)));
} catch (IllegalBlockSizeException e) {
throw new SecurityException(e);
} catch (BadPaddingException e) {
throw new SecurityException(e);
} catch (InvalidKeyException e) {
throw new SecurityException(e);
} catch (InvalidAlgorithmParameterException e) {
throw new SecurityException(e);
}
}
/**
* #param input Any String to be encrypted
* #return An "AES/CFB8/NoPadding" encrypted String
* #throws CryptingException
*/
public String encrypt(String input) throws CryptingException {
try {
cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
return DatatypeConverter.printBase64Binary(cipher.doFinal(input.getBytes(CHARSET))).trim();
} catch (InvalidKeyException e) {
throw new SecurityException(e);
} catch (InvalidAlgorithmParameterException e) {
throw new SecurityException(e);
} catch (IllegalBlockSizeException e) {
throw new SecurityException(e);
} catch (BadPaddingException e) {
throw new SecurityException(e);
}
}
/**
* Encrypts the keys and values of a JSONObject with Cryptor.encrypt(String input)
* #param o The JSONObject to be encrypted
* #return A JSONObject with encrypted keys and values
*/
public JSONObject jsonObjectEncrypt(JSONObject o) {
Iterator<?> keys = o.keys();
JSONObject returnObject = new JSONObject();
while( keys.hasNext() ){
String key = (String)keys.next();
returnObject.put(this.encrypt(key), this.encrypt(o.getString(key)));
}
return returnObject;
}
/**
* Decrypts the keys and values of a JSONObject with Cryptor.decrypt(String input)
* #param o The JSONObject to be decrypted
* #return A JSONObject with decrypted keys and values
*/
public JSONObject jsonObjectDecrypt(JSONObject o) {
Iterator<?> keys = o.keys();
JSONObject returnObject = new JSONObject();
while(keys.hasNext()){
String key = (String)keys.next();
if(key != null && !key.equals("")) {
returnObject.put(this.decrypt(key), this.decrypt(o.getString(key)));
}
}
return returnObject;
}
/**
* Encrypts keys and values of every JSONObject in a JSONArray
* #param a The JSONArray to be encrypted
* #return A JSONArray with encrypted keys and values
*/
public JSONArray jsonArrayEncrypt(JSONArray a) {
JSONArray returnArray = new JSONArray();
for(int i = 0; i < a.length(); i++) {
returnArray.put(this.jsonObjectEncrypt((JSONObject)a.get(i)));
}
return returnArray;
}
/**
* Decrypts keys and values of every JSONObject in a JSONArray
* #param a The JSONArray to be decrypted
* #return A JSONArray with decrypted keys and values
*/
public JSONArray jsonArrayDecrypt(JSONArray a) {
JSONArray returnArray = new JSONArray();
for(int i = 0; i < a.length(); i++) {
returnArray.put(this.jsonObjectDecrypt((JSONObject)a.get(i)));
}
return returnArray;
}
public static void main(String Args[]) {
try {
Cryptor c = new Cryptor();
String original = "MiiiMüäöMeeʞ";
System.out.println("Original: " + original);
String encrypted = c.encrypt(original);
System.out.println("Encoded: " + encrypted);
System.out.println("Decoded: " + c.decrypt(encrypted));
JSONArray arr = new JSONArray("[{\"id\"=\" 1 ʞ3 \"},{\"id\"=\"4\"}]");
System.out.println(c.jsonArrayDecrypt(c.jsonArrayEncrypt(arr)).getJSONObject(0).getString("id"));
} catch (CryptingException e) {
e.printStackTrace();
}
}
}
PHP
<html>
<meta charset='utf-8'>
<?php
$cryptor = new Cryptor();
echo $cryptor->decrypt($cryptor->encrypt("MiiiMüäöMeeʞ"));
class Cryptor {
//Use same as in java Cryptor
private $iv = '1234567890qwertz';
private $secretKey = '1234567890qwertz';
function encrypt($input) {
return base64_encode(
mcrypt_encrypt(
MCRYPT_RIJNDAEL_128,
$this->secretKey,
$input,
MCRYPT_MODE_CFB,
$this->iv
)
);
}
function decrypt($input) {
return mcrypt_decrypt(
MCRYPT_RIJNDAEL_128,
$this->secretKey,
base64_decode($input),
MCRYPT_MODE_CFB,
$this->iv
);
}
function arrayDecrypt($array) {
$returnArray = array();
foreach($array as $key=>$value) {
$newKey = $this->decrypt($key);
$returnArray[$newKey] = $this->decrypt($value);
}
return $returnArray;
}
function arrayEncrypt($array) {
$returnArray = array();
foreach($array as $key=>$value) {
$returnArray[$this->encrypt($key)] = $this->encrypt($value);
}
return $returnArray;
}
}
?>
</html>

Related

Error while decrypting the encrypted content of the file

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.

Android RSA decryption using private key, non-sense result

I am doing RSA decryption in my Android project, and somehow the result makes non-sense. I am showing my code here:
private static final int MAX_DECRYPT_BLOCK = 256;
private static RSAPrivateKey loadPrivateKey(InputStream in) throws Exception {
RSAPrivateKey priKey;
try {
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String readLine = null;
StringBuilder sb = new StringBuilder();
while ((readLine = br.readLine()) != null) {
if (readLine.charAt(0) == '-') {
continue;
} else {
sb.append(readLine);
sb.append('\r');
}
}
byte[] priKeyData = Base64.decode(new String(sb), Base64.NO_WRAP);
PKCS8EncodedKeySpec keySpec= new PKCS8EncodedKeySpec(priKeyData);
KeyFactory keyFactory= KeyFactory.getInstance("RSA",new BouncyCastleProvider());
priKey= (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
} catch (IOException e) {
throw new Exception("error reading the key");
} catch (NullPointerException e) {
throw new Exception("inputstream is null");
}
return priKey;
}
/**
* decrypt with a private key
*
* #param privateKey
* #param cipherData
* #return
* #throws Exception
*/
private static byte[] decrypt(RSAPrivateKey privateKey, byte[] cipherData) throws Exception {
if (privateKey == null) {
throw new Exception("key is null");
}
Cipher cipher = null;
try {
cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
int inputLen = cipherData.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
cache = cipher.doFinal(cipherData, offSet, MAX_DECRYPT_BLOCK);
} else {
cache = cipher.doFinal(cipherData, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_DECRYPT_BLOCK;
}
byte[] decryptedData = out.toByteArray();
out.close();
return decryptedData;
} catch (NoSuchAlgorithmException e) {
throw new Exception("no such algorithm");
} catch (NoSuchPaddingException e) {
e.printStackTrace();
return null;
} catch (InvalidKeyException e) {
throw new Exception("InvalidKeyException");
} catch (IllegalBlockSizeException e) {
throw new Exception("IllegalBlockSizeException");
} catch (BadPaddingException e) {
throw new Exception("BadPaddingException");
}
}
public static String RSADecrypt(Context context, String KeyFileNameInAssetFolder, byte[] content) {
try {
InputStream inputStream = context.getResources().getAssets().open(KeyFileNameInAssetFolder);
RSAPrivateKey privateKey = loadPrivateKey(inputStream);
byte[] b = decrypt(privateKey, content);
return new String(b,"utf-8");
} catch (Exception e) {
e.printStackTrace();
}
return "error";
}
and I am calling with this statement:
String result = RSAUtils.RSADecrypt(getApplicationContext(), Constant.PRIVATE_KEY_PKCS8_FILE_NAME,Base64.decode(qrcode_result,Base64.NO_WRAP));
And this is the private key:
> -----BEGIN PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCsQTbkXviKG1od
wVp0t15JB4OkdDUo8O36/yzLoJmsmPf3yFzAJ3YzEAaWAKKpUx92c9yfW4vW849F
pno/GUJLwPkIG5ss1YR55P5UI76kpLM74ZXume9+WfEuQ3B/HHkcnmCVl4CV/Xqq
4X4d3Rc7zGTbGSHdVui1QJ5ubQoqHjSGaO9j2SvMsqDSU20S1DjrL/8sb0e7B63a
fJVzOZFi7E62zqYzfBOEupY+24Ac8i7s8tyX3Bd4OJ1zdQ+si5yeIkaRiD8ZeUbJ
3yS2MlUohvuwmJy7uxpP8mYXmaXM1ZtMFLaLRUc4leA7KDRlDXHJLSYAkFxCyw8J
RTK2QOcTAgMBAAECggEARRrUnsHLC/z1JkLPu0tlM/8jvPIx8X7Wun9sxTRk8m1b
7bggHaa3ML0ZJ0yR9UQ3txm8ROJBM7b6n4KuQGotwp5kSfBpTI9MWmqX7cF5ViwN
C9TwhYyUHCiRLXI4y4XswKJ5NQpWt9W9RJi6M9ji3Uaen5dxko6vRSfrZ3mvPj2/
blW5HV8j3RIzJ3942CzQw2IX/hQWhityFxTwGY3f3Rh05jpI+SowJlOTIheOHqlR
2VFTLTYIvmoZJduFzxlM4t5W3VzGZl/KmC1apNh2N3xPcmimq/YsrDqN5GgkNhuh
/WTTB7pa3qsQlFPKnwylLc2LviQafiR+yunolImCwQKBgQDS9TIth96x+McD2Gu7
1QQlalhDK1+s/O9rjQV4la9FykEFdJB7+Q9xyq9vIqqSVIFj8rI1wqziHp3czUkY
Ijqcgp0DB1Stbwp3DPh3Rq4zVHHnKplzhMwAaDBOVaHmEGaiyB/LwspCcDoON+i+
70Bzdc6EW/KqNpGlP3OPJT2pSwKBgQDRCIlyklOnKQnzbCaMwFkBZBJlHHqgIl1Z
S7jdFaTX7uUkbXF3WVtJlY1+r6h0rK075hX/61VlhfoFjBIR/7ZDaBkrH3Nd6cdU
PJIOgnQEYobRAF4ugWSPTsf0A6bjd7tsVZ7+1ediKwg1QY9Pk2hj/jRb0FD2nKZ+
yWI3RPekWQKBgBM1DfeFSmpr2zrnZo+4imMZtqWO+mwWr3ncYiYjgszY6Gilv036
VESpDqYQwvUFyq4d98nbSsBfx0HGUyRmYW3EmqUe8r/Dv3EtdiXuAohb5O8GOuiA
q85RrixDsbTvw1iI3hRATQgVjcOjpYZU5Epe7ImykXqb81DXYR8kZePXAoGBAJWk
CuFeJ0yPcHQ2hBJW0GDShuijTpW8hB8cuiZrDCsY9ijxwDy0V0mCKlz62xlLVGiA
+lbO3b9j/exirbz81jnDF+FrDme4p92Bzv1cHjnVXrXYEZQxRQ/iUfo5cwt790xC
ryO3dYEtVR7q4/EPkbejj0/6/TrOQdKZ0BnI4Y9hAoGBALlFBlvCRspXYBOXf0XM
5V0Q4t1vAxgcfNaKi4h612UZDF2GluYIwtuF+uJlxYvhRxq1gzmgP5+Z9gblMb6d
8ysWfWPl2RWGYNw0nwOYhWI1/cWRNpfH7W+OY2kHmB3G1bHnf5PxUb+1JL2PvfXS
fZ8JY1/xKqYSoSORJYQh2Z7D
-----END PRIVATE KEY-----
and this is the string I tried to decrypt:
JRhdX3DLGbMVcxN6jV3697yUkfZUBfz/ee6P8pGlgHFnOo5OWgXH0fc10Ps4li3UKkyVqo1+iz10/zzhjVTbSKC5Fai6dLnQgrFVz6lOqOeR83+x4ezyF75kORdgAyEp5MiW0LHsK13ryYEqZ1GHiZdJ6E54nbLZsZGKJJkRZ2OVQW9hovqBQXAP3M8dGk1liruiY+xAHfKkeS73m+IPYPTNGQT+y5IDACoq8dLUvV4nw76p2ZUfyYFgoYOir9KBN2SbfcndR71DZUPWdRnZoDLNFCfvMjC2Ui27j3CxcQLzJSt4K4K+kmU6n5t8Xb6YyGb2j+5pduXcnZMgc5cjsm6NBIXUv+DQzXeRo61vHrXKWeamJ+Whl0RnA9HjIl6medxfE64xHgF+aD6lqbQcwWwHWm/s3f5XkS0xP21bYuOt8mgmHC90qhJNRGKmTGgyxxls/18aV4eZEIRUg82wCIXavvQGLA3hk5UWl4YkrpaGYh+SX1t3yfi+wQ8f30lQBrKl4A0iKk4WHKNCka6nd3sc8bDwD42cvQiFSPCp7m4DRtXy1CRzNmRG7FmSK8SgkQOWSWE+6KRKat88j0Nw+Rg6U1YaMBofJOLKfIswLHgW44Bpf2c0eynJEZdLi94oOh7lkTHcaqwBiO1MWg9eiYT/j7qXCPjoi9q3PzPhxoA=
and the decryption result is like this:
result image

AES encryption returning different values on different machines

My AES encryption program is returning different encrypted values on different machines. Can anyone please help on finding out what needs to be done to ensure the same encrypted value is returned on any machine the program is run..
private static SecretKeySpec secret;
private static String seed;
private static String text;
private static String salt = "Salt123";
private static int pswdIterations = 65536;
private static int keySize = 256;
/**
*
* #param mySeed
*/
public static void setSeed(String mySeed) {
try {
byte[] saltBytes = salt.getBytes("UTF-8");
PBEKeySpec spec = new PBEKeySpec(mySeed.toCharArray(), saltBytes,
pswdIterations, keySize);
SecretKeyFactory factory = SecretKeyFactory
.getInstance("PBKDF2WithHmacSHA1");
SecretKey secretKey = factory.generateSecret(spec);
secret = new SecretKeySpec(secretKey.getEncoded(), "AES");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (InvalidKeySpecException e) {
e.printStackTrace();
}
}
public static String getEncryptedStringFor(String text) {
try {
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secret);
byte[] encryptedData = cipher.doFinal(text.getBytes("UTF-8"));
return new String(Base64.encodeBase64(encryptedData));
} catch (Exception e) {
System.out.println("Error while encrypting: " + e.toString());
}
return null;
}
public static String getDecryptedStringFor(String text) {
try {
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, secret);
return (new String(cipher.doFinal(Base64
.decodeBase64(text.getBytes("UTF-8")))));
} catch (Exception e) {
System.out.println("Error while decrypting: " + e.toString());
}
return null;
}
Some sample values
seed : seed123
text : #text!
Encrypted value : RoVE3KsjzN0nNxCNsNpRPg==
seed : seed!!
text : #text123!
Encrypted value :X6pfUKCVXXrAEyqKko/kFQ==
The only thing I can see in the code is the following line:
return (new String(cipher.doFinal(Base64.decodeBase64(text.getBytes("UTF-8")))));
Now it looks like this is actually returning a String after decoding with UTF-8. But it doesn't: it uses the platform default:
return (new String(
cipher.doFinal(
Base64.decodeBase64(
text.getBytes("UTF-8")
)
)
));
Of course, the first ( is superfluous anyway, so try this:
byte[] ciphertext = Base64.decodeBase64(text.getBytes("UTF-8"));
byte[] plaintext = cipher.doFinal(ciphertext);
return new String(plaintext, "UTF-8");
Note that you can also use import static java.nio.charsets.StandardCharsets.UTF_8 nowadays, which lets you do away with the exception as well. I wish they would do the same for StandardCiphers.AES_CBC_PKCS7PADDING :)

Double layer encryption: "Input length must be multiple of 16 when decrypting with padded cipher..."

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.

Java function for Encrypt/Decrypt like Mysql's AES_ENCRYPT and AES_DECRYPT

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"));

Categories