Android RSA decryption using private key, non-sense result - java

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

Related

FileNotFound Exception When Trying To Read File Using getServletContext().getRealPath()

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.

DESKeySpec class in java

public static String DESDecrypt(String src, String password) {
String result = src;
if (src == null) {
return result;
}
if (src.isEmpty()) {
return result;
}
byte[] item = password.substring(0, 8).getBytes();
try {
DESKeySpec item2 = new DESKeySpec(item);
SecretKey securekey = SecretKeyFactory.getInstance("DES").generateSecret(item2);
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
}
return password.substring(0, 8);
/*AlgorithmParameterSpec iv = new IvParameterSpec(ivkey);
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
cipher.init(2, securekey, iv);
return new String(cipher.doFinal(Base64.getDecoder().decode(src)));*/
}
I have errors on line:
SecretKey securekey = SecretKeyFactory.getInstance("DES").generateSecret(item2);
Unhandled exception type NoSuchAlgorithmException
Unhandled exception type InvalidKeySpecException

Java AES/CFB8/NoPadding encryption and Charset

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>

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