Search code examples
androidtripledes

Triple DES Algorithm in Android JAVA


I am new to Android-Java. I have below function in C# for Encryption (Triple DES)

public string Encrypt(string data)
    {
        try
        {
            if (!string.IsNullOrEmpty(data))
            {
                //byte[] keyArray;
                byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(data);
                //System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader();

                byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key);
                TripleDESCryptoServiceProvider CryptDesECB = new TripleDESCryptoServiceProvider();
                CryptDesECB.Key = keyArray;
                CryptDesECB.Mode = CipherMode.ECB;
                CryptDesECB.Padding = PaddingMode.PKCS7;
                ICryptoTransform cTransform = CryptDesECB.CreateEncryptor();
                byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
                CryptDesECB.Clear();
                return Convert.ToBase64String(resultArray, 0, resultArray.Length);
            }
            return string.Empty;
        }
        catch (Exception)
        {
            return string.Empty;
        }
    }

I have tried below code for having same Encryption function in Android platform:

public static String EncryptText(String message) throws Exception {
        MessageDigest md = MessageDigest.getInstance("SHA-1");
        byte[] digestOfPassword = md.digest(secretKey.getBytes("utf-8"));
        byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);

        SecretKey key = new SecretKeySpec(keyBytes, "DESede");
        Cipher cipher = Cipher.getInstance("DESede");
        cipher.init(Cipher.ENCRYPT_MODE, key);

        byte[] plainTextBytes = message.getBytes("utf-8");
        byte[] buf = cipher.doFinal(plainTextBytes);
        byte [] base64Bytes = Base64.encode(buf,Base64.DEFAULT);
        String base64EncryptedString = new String(base64Bytes);

        return base64EncryptedString;
}

But, the encryption result is different on both platforms? If anyone can help me in pointing the issue in Android function.

Thanks in advance.


Solution

  • I wrote below class for Triple DES ECB mode PKCS5/7 padding mode encryption-decryption and it worked for me:

    public class DESedeEncryption {
    
        private static final String UNICODE_FORMAT = "UTF8";
        public static final String DESEDE_ENCRYPTION_SCHEME = "DESede";
        private KeySpec myKeySpec;
        private SecretKeyFactory mySecretKeyFactory;
        private Cipher cipher;
        byte[] keyAsBytes;
        private String myEncryptionKey;
        private String myEncryptionScheme;
        SecretKey key;
    
        public DESedeEncryption() throws Exception
        {
            myEncryptionKey = "YOURPRIVATEKEY";
            myEncryptionScheme = DESEDE_ENCRYPTION_SCHEME;
            keyAsBytes = myEncryptionKey.getBytes(UNICODE_FORMAT);
            myKeySpec = new DESedeKeySpec(keyAsBytes);
            mySecretKeyFactory = SecretKeyFactory.getInstance(myEncryptionScheme);
            cipher = Cipher.getInstance(myEncryptionScheme);
            key = mySecretKeyFactory.generateSecret(myKeySpec);
        }
    
        /**
         * Method To Encrypt The String
         */
        public String encrypt(String unencryptedString) {
            String encryptedString = null;
            try {
                cipher.init(Cipher.ENCRYPT_MODE, key);
                byte[] plainText = unencryptedString.getBytes(UNICODE_FORMAT);
                byte[] encryptedText = cipher.doFinal(plainText);
                encryptedString = Base64.encodeToString(encryptedText, Base64.DEFAULT);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return encryptedString.endsWith("\n") ? encryptedString.replace("\n","") : encryptedString;
        }
        /**
         * Method To Decrypt An Ecrypted String
         */
        public String decrypt(String encryptedString) {
            String decryptedText=null;
            try {
                cipher.init(Cipher.DECRYPT_MODE, key);
                byte[] encryptedText = Base64.decode(encryptedString, Base64.DEFAULT);
                byte[] plainText = cipher.doFinal(encryptedText);
                decryptedText= bytes2String(plainText);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return decryptedText;
        }
        /**
         * Returns String From An Array Of Bytes
         */
        private static String bytes2String(byte[] bytes) {
            StringBuffer stringBuffer = new StringBuffer();
            for (int i = 0; i > bytes.length; i++) {
                stringBuffer.append((char) bytes[i]);
            }
            return stringBuffer.toString();
        }
    }