0

I'm trying to do an Encryption and Decryption in Java Android.

Below is my code for C#, I need to convert it to Java Android. Can someone help me how to do it?

I've been doing this for almost 2 days yet can't find any solutions on how to convert it. I'm newbie in Android.

public static string Encrypt(string toEncrypt)
        {
            byte[] keyArray;
            byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);

            System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader();

            string key = "KEY";

            MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
            keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
            hashmd5.Clear();

            TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
            tdes.Key = keyArray;
            tdes.Mode = CipherMode.ECB;
            tdes.Padding = PaddingMode.PKCS7;

            ICryptoTransform cTransform = tdes.CreateEncryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            tdes.Clear();
            return Convert.ToBase64String(resultArray, 0, resultArray.Length);
        }

        public static string Decrypt(string cipherString)
        {
            try
            {
                byte[] keyArray;
                byte[] toEncryptArray = Convert.FromBase64String(cipherString);

                string key = "KEY";

                MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
                keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
                hashmd5.Clear();

                TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
                tdes.Key = keyArray;
                tdes.Mode = CipherMode.ECB;
                tdes.Padding = PaddingMode.PKCS7;

                ICryptoTransform cTransform = tdes.CreateDecryptor();
                byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

                tdes.Clear();
                return UTF8Encoding.UTF8.GetString(resultArray);
            }
            catch (Exception)
            {
                return "Invalid";
            }
        }
Anthon
  • 69,918
  • 32
  • 186
  • 246
user2826499
  • 121
  • 1
  • 1
  • 19
  • Instead of an unwanted "Thank you!" (no distractions, no chit-chat (read [help→tour](http://stackoverflow.com/tour)) you should include what output you expect, and what you get. And any errors if those are thrown. Please update your post with that information. Don't put stuff like **Edit** or **Update** in your question when you do revise. This site has edit history, those who need to see differences can get the information from there. – Anthon Mar 24 '15 at 06:01
  • Have a look [here](http://www.androidsnippets.com/encryptdecrypt-strings) – Sebastian Mar 24 '15 at 07:41

1 Answers1

0

Try This,

package mypackage;

import java.security.MessageDigest;
import java.util.Arrays;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

public class Main {

    public static void main(String[] args) throws Exception {

        String text = "neeraj";

        String codedtext = new Main().encrypt(text);

        String decodedtext = new Main().decrypt(codedtext);

        System.out.println(codedtext); // this is a byte array, you'll just see a reference to an array
        System.out.println(decodedtext); // This correctly shows "neeraj"
    }

    public String encrypt(String message) throws Exception {
        final MessageDigest md = MessageDigest.getInstance("md5");
        final byte[] digestOfPassword = md.digest("KEY"
                .getBytes("utf-8"));
        final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
        for (int j = 0, k = 16; j < 8;) {
            keyBytes[k++] = keyBytes[j++];
        }

        final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
        final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
        final Cipher cipher = Cipher.getInstance("DES/ECB/PKCS7Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key, iv);

        final byte[] plainTextBytes = message.getBytes("utf-8");
        final byte[] cipherText = cipher.doFinal(plainTextBytes);
        // final String encodedCipherText = new sun.misc.BASE64Encoder()
        // .encode(cipherText);

        return Base64.encodeBase64String(cipherText);
    }

    public String decrypt(String input) throws Exception {

        byte[] message = Base64.decodeBase64(input);

        final MessageDigest md = MessageDigest.getInstance("md5");
        final byte[] digestOfPassword = md.digest("KEY"
                .getBytes("utf-8"));
        final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
        for (int j = 0, k = 16; j < 8;) {
            keyBytes[k++] = keyBytes[j++];
        }

        final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
        final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
        final Cipher decipher = Cipher.getInstance("DES/ECB/PKCS7Padding");
        decipher.init(Cipher.DECRYPT_MODE, key, iv);

        // final byte[] encData = new
        // sun.misc.BASE64Decoder().decodeBuffer(message);
        final byte[] plainText = decipher.doFinal(message);

        return new String(plainText, "UTF-8");
    }
}

Refer to the main function for usage.

I have updated my code. Your C# program gives output as a base64 string. But in java the input of decrypt and output of encrypt is byte array. Convert the byte array to base64 and it will work.

For Base64 operation in java you need the Apache Commons codec.

In java 8 you can use java.util.Base64

K Neeraj Lal
  • 6,768
  • 3
  • 24
  • 33
  • thank you @K Neeraj Lal. but I already tested it and it doesn't work. I encrypt a string using my Encryption function in C# and decrypt it with yours in Java and it gets a BadPaddingException error. why it doesn't work? – user2826499 Mar 30 '15 at 03:00
  • you are using CBC while is he requesting ECB – user666 Aug 16 '18 at 09:22