<p>Every method I write to encode a string in Java using 3DES can't be decrypted back to the original string.  Does anyone have a simple code snippet that can just encode and then decode the string back to the original string?</p>

<p>I know I'm making a very silly mistake somewhere in this code. Here's what I've been working with so far:</p>

<p>** note, I am not returning the BASE64 text from the encrypt method, and I am not base64 un-encoding in the decrypt method because I was trying to see if I was making a mistake in the BASE64 part of the puzzle.</p>

<pre><code>public class TripleDESTest {

    public static void main(String[] args) {

        String text = "kyle boon";

        byte[] codedtext = new TripleDESTest().encrypt(text);
        String decodedtext  = new TripleDESTest().decrypt(codedtext);

        System.out.println(codedtext);
        System.out.println(decodedtext);
    }

    public byte[] encrypt(String message) {
        try {
            final MessageDigest md = MessageDigest.getInstance("md5");
            final byte[] digestOfPassword = md.digest("HG58YZ3CR9".getBytes("utf-8"));
            final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
            for (int j = 0,  k = 16; j &lt; 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("DESede/CBC/PKCS5Padding");
            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 cipherText;    
        }
        catch (java.security.InvalidAlgorithmParameterException e) { System.out.println("Invalid Algorithm"); }
        catch (javax.crypto.NoSuchPaddingException e) { System.out.println("No Such Padding"); }
        catch (java.security.NoSuchAlgorithmException e) { System.out.println("No Such Algorithm"); }
        catch (java.security.InvalidKeyException e) { System.out.println("Invalid Key"); }
        catch (BadPaddingException e) { System.out.println("Invalid Key");}
        catch (IllegalBlockSizeException e) { System.out.println("Invalid Key");}
        catch (UnsupportedEncodingException e) { System.out.println("Invalid Key");}

        return null;
    }

    public String decrypt(byte[] message) {
        try
        {
            final MessageDigest md = MessageDigest.getInstance("md5");
            final byte[] digestOfPassword = md.digest("HG58YZ3CR9".getBytes("utf-8"));
            final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
            for (int j = 0,  k = 16; j &lt; 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("DESede/CBC/PKCS5Padding");
            decipher.init(Cipher.DECRYPT_MODE, key, iv);

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

            return plainText.toString();            
        }
        catch (java.security.InvalidAlgorithmParameterException e) { System.out.println("Invalid Algorithm"); }
        catch (javax.crypto.NoSuchPaddingException e) { System.out.println("No Such Padding"); }
        catch (java.security.NoSuchAlgorithmException e) { System.out.println("No Such Algorithm"); }
        catch (java.security.InvalidKeyException e) { System.out.println("Invalid Key"); }
        catch (BadPaddingException e) { System.out.println("Invalid Key");}
        catch (IllegalBlockSizeException e) { System.out.println("Invalid Key");}
        catch (UnsupportedEncodingException e) { System.out.println("Invalid Key");}     
        catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return null;
    }
}
</code></pre>

[{'answer_id': 20670, 'author': 'Boris Terzic', 'author_id': 1996, 'author_profile': 'https://Stackoverflow.com/users/1996', 'pm_score': 7, 'selected': True, 'text': '<p>Your code was fine except for the Base 64 encoding bit (which you mentioned was a test), the reason the output may not have made sense is that you were displaying a raw byte array (doing toString() on a byte array returns its internal Java reference, not the String representation of the <strong>contents</strong>). Here\'s a version that\'s just a teeny bit cleaned up and which prints "kyle boon" as the decoded string:</p>\n\n<pre><code>import java.security.MessageDigest;\nimport java.util.Arrays;\n\nimport javax.crypto.Cipher;\nimport javax.crypto.SecretKey;\nimport javax.crypto.spec.IvParameterSpec;\nimport javax.crypto.spec.SecretKeySpec;\n\npublic class TripleDESTest {\n\n    public static void main(String[] args) throws Exception {\n\n        String text = "kyle boon";\n\n        byte[] codedtext = new TripleDESTest().encrypt(text);\n        String decodedtext = new TripleDESTest().decrypt(codedtext);\n\n        System.out.println(codedtext); // this is a byte array, you\'ll just see a reference to an array\n        System.out.println(decodedtext); // This correctly shows "kyle boon"\n    }\n\n    public byte[] encrypt(String message) throws Exception {\n        final MessageDigest md = MessageDigest.getInstance("md5");\n        final byte[] digestOfPassword = md.digest("HG58YZ3CR9"\n                .getBytes("utf-8"));\n        final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);\n        for (int j = 0, k = 16; j &lt; 8;) {\n            keyBytes[k++] = keyBytes[j++];\n        }\n\n        final SecretKey key = new SecretKeySpec(keyBytes, "DESede");\n        final IvParameterSpec iv = new IvParameterSpec(new byte[8]);\n        final Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");\n        cipher.init(Cipher.ENCRYPT_MODE, key, iv);\n\n        final byte[] plainTextBytes = message.getBytes("utf-8");\n        final byte[] cipherText = cipher.doFinal(plainTextBytes);\n        // final String encodedCipherText = new sun.misc.BASE64Encoder()\n        // .encode(cipherText);\n\n        return cipherText;\n    }\n\n    public String decrypt(byte[] message) throws Exception {\n        final MessageDigest md = MessageDigest.getInstance("md5");\n        final byte[] digestOfPassword = md.digest("HG58YZ3CR9"\n                .getBytes("utf-8"));\n        final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);\n        for (int j = 0, k = 16; j &lt; 8;) {\n            keyBytes[k++] = keyBytes[j++];\n        }\n\n        final SecretKey key = new SecretKeySpec(keyBytes, "DESede");\n        final IvParameterSpec iv = new IvParameterSpec(new byte[8]);\n        final Cipher decipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");\n        decipher.init(Cipher.DECRYPT_MODE, key, iv);\n\n        // final byte[] encData = new\n        // sun.misc.BASE64Decoder().decodeBuffer(message);\n        final byte[] plainText = decipher.doFinal(message);\n\n        return new String(plainText, "UTF-8");\n    }\n}\n</code></pre>\n'}, {'answer_id': 10164989, 'author': 'jlmontesdeoca', 'author_id': 1334941, 'author_profile': 'https://Stackoverflow.com/users/1334941', 'pm_score': 4, 'selected': False, 'text': '<p>I had hard times figuring it out myself and this post helped me to find the right answer for my case. When working with financial messaging as ISO-8583 the 3DES requirements are quite specific, so for my especial case the "DESede/CBC/PKCS5Padding" combinations wasn\'t solving the problem. After some comparative testing of my results against some 3DES calculators designed for the financial world I found the the value "DESede/ECB/Nopadding" is more suited for the the specific task.</p>\n\n<p>Here is a demo implementation of my TripleDes class (using the Bouncy Castle provider)</p>\n\n<pre><code>\n\n    import java.security.InvalidKeyException;\n    import java.security.NoSuchAlgorithmException;\n    import java.security.NoSuchProviderException;\n    import java.security.Security;\n    import javax.crypto.BadPaddingException;\n    import javax.crypto.Cipher;\n    import javax.crypto.IllegalBlockSizeException;\n    import javax.crypto.NoSuchPaddingException;\n    import javax.crypto.SecretKey;\n    import javax.crypto.spec.SecretKeySpec;\n    import org.bouncycastle.jce.provider.BouncyCastleProvider;\n\n\n    /**\n     *\n     * @author Jose Luis Montes de Oca\n     */\n    public class TripleDesCipher {\n       private static String TRIPLE_DES_TRANSFORMATION = "DESede/ECB/Nopadding";\n       private static String ALGORITHM = "DESede";\n       private static String BOUNCY_CASTLE_PROVIDER = "BC";\n       private Cipher encrypter;\n       private Cipher decrypter;\n\n       public TripleDesCipher(byte[] key) throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException,\n             InvalidKeyException {\n          Security.addProvider(new BouncyCastleProvider());\n          SecretKey keySpec = new SecretKeySpec(key, ALGORITHM);\n          encrypter = Cipher.getInstance(TRIPLE_DES_TRANSFORMATION, BOUNCY_CASTLE_PROVIDER);\n          encrypter.init(Cipher.ENCRYPT_MODE, keySpec);\n          decrypter = Cipher.getInstance(TRIPLE_DES_TRANSFORMATION, BOUNCY_CASTLE_PROVIDER);\n          decrypter.init(Cipher.DECRYPT_MODE, keySpec);\n       }\n\n       public byte[] encode(byte[] input) throws IllegalBlockSizeException, BadPaddingException {\n          return encrypter.doFinal(input);\n       }\n\n       public byte[] decode(byte[] input) throws IllegalBlockSizeException, BadPaddingException {\n          return decrypter.doFinal(input);\n       }\n    }\n\n</code></pre>\n'}, {'answer_id': 11367849, 'author': 'siliconsmiley', 'author_id': 1024005, 'author_profile': 'https://Stackoverflow.com/users/1024005', 'pm_score': 2, 'selected': False, 'text': '<p>Here\'s a very simply static encrypt/decrypt class biased on the Bouncy Castle no padding example by Jose Luis Montes de Oca.  This one is using "DESede/ECB/PKCS7Padding" so I don\'t have to bother manually padding.</p>\n\n<pre><code>\n    package com.zenimax.encryption;\n\n    import java.security.InvalidKeyException;\n    import java.security.NoSuchAlgorithmException;\n    import java.security.NoSuchProviderException;\n    import java.security.Security;\n    import javax.crypto.BadPaddingException;\n    import javax.crypto.Cipher;\n    import javax.crypto.IllegalBlockSizeException;\n    import javax.crypto.NoSuchPaddingException;\n    import javax.crypto.SecretKey;\n    import javax.crypto.spec.SecretKeySpec;\n    import org.bouncycastle.jce.provider.BouncyCastleProvider;\n\n    /**\n     * \n     * @author Matthew H. Wagner\n     */\n    public class TripleDesBouncyCastle {\n        private static String TRIPLE_DES_TRANSFORMATION = "DESede/ECB/PKCS7Padding";\n        private static String ALGORITHM = "DESede";\n        private static String BOUNCY_CASTLE_PROVIDER = "BC";\n\n        private static void init()\n        {\n            Security.addProvider(new BouncyCastleProvider());\n        }\n\n        public static byte[] encode(byte[] input, byte[] key)\n                throws IllegalBlockSizeException, BadPaddingException,\n                NoSuchAlgorithmException, NoSuchProviderException,\n                NoSuchPaddingException, InvalidKeyException {\n            init();\n            SecretKey keySpec = new SecretKeySpec(key, ALGORITHM);\n            Cipher encrypter = Cipher.getInstance(TRIPLE_DES_TRANSFORMATION,\n                    BOUNCY_CASTLE_PROVIDER);\n            encrypter.init(Cipher.ENCRYPT_MODE, keySpec);\n            return encrypter.doFinal(input);\n        }\n\n        public static byte[] decode(byte[] input, byte[] key)\n                throws IllegalBlockSizeException, BadPaddingException,\n                NoSuchAlgorithmException, NoSuchProviderException,\n                NoSuchPaddingException, InvalidKeyException {\n            init();\n            SecretKey keySpec = new SecretKeySpec(key, ALGORITHM);\n            Cipher decrypter = Cipher.getInstance(TRIPLE_DES_TRANSFORMATION,\n                    BOUNCY_CASTLE_PROVIDER);\n            decrypter.init(Cipher.DECRYPT_MODE, keySpec);\n            return decrypter.doFinal(input);\n        }\n    }\n</code>\n</pre>\n'}, {'answer_id': 13612902, 'author': 'oneiros', 'author_id': 861832, 'author_profile': 'https://Stackoverflow.com/users/861832', 'pm_score': 4, 'selected': False, 'text': '<p>Here is a solution using the <strong>javax.crypto</strong> library and the apache commons codec library for encoding and decoding in Base64: </p>\n\n<pre><code>import java.security.spec.KeySpec;\nimport javax.crypto.Cipher;\nimport javax.crypto.SecretKey;\nimport javax.crypto.SecretKeyFactory;\nimport javax.crypto.spec.DESedeKeySpec;\nimport org.apache.commons.codec.binary.Base64;\n\npublic class TrippleDes {\n\n    private static final String UNICODE_FORMAT = "UTF8";\n    public static final String DESEDE_ENCRYPTION_SCHEME = "DESede";\n    private KeySpec ks;\n    private SecretKeyFactory skf;\n    private Cipher cipher;\n    byte[] arrayBytes;\n    private String myEncryptionKey;\n    private String myEncryptionScheme;\n    SecretKey key;\n\n    public TrippleDes() throws Exception {\n        myEncryptionKey = "ThisIsSpartaThisIsSparta";\n        myEncryptionScheme = DESEDE_ENCRYPTION_SCHEME;\n        arrayBytes = myEncryptionKey.getBytes(UNICODE_FORMAT);\n        ks = new DESedeKeySpec(arrayBytes);\n        skf = SecretKeyFactory.getInstance(myEncryptionScheme);\n        cipher = Cipher.getInstance(myEncryptionScheme);\n        key = skf.generateSecret(ks);\n    }\n\n\n    public String encrypt(String unencryptedString) {\n        String encryptedString = null;\n        try {\n            cipher.init(Cipher.ENCRYPT_MODE, key);\n            byte[] plainText = unencryptedString.getBytes(UNICODE_FORMAT);\n            byte[] encryptedText = cipher.doFinal(plainText);\n            encryptedString = new String(Base64.encodeBase64(encryptedText));\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n        return encryptedString;\n    }\n\n\n    public String decrypt(String encryptedString) {\n        String decryptedText=null;\n        try {\n            cipher.init(Cipher.DECRYPT_MODE, key);\n            byte[] encryptedText = Base64.decodeBase64(encryptedString);\n            byte[] plainText = cipher.doFinal(encryptedText);\n            decryptedText= new String(plainText);\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n        return decryptedText;\n    }\n\n\n    public static void main(String args []) throws Exception\n    {\n        TrippleDes td= new TrippleDes();\n\n        String target="imparator";\n        String encrypted=td.encrypt(target);\n        String decrypted=td.decrypt(encrypted);\n\n        System.out.println("String To Encrypt: "+ target);\n        System.out.println("Encrypted String:" + encrypted);\n        System.out.println("Decrypted String:" + decrypted);\n\n    }\n\n}\n</code></pre>\n\n<p>Running the above program results with the following output: </p>\n\n<pre><code>String To Encrypt: imparator\nEncrypted String:FdBNaYWfjpWN9eYghMpbRA==\nDecrypted String:imparator\n</code></pre>\n'}, {'answer_id': 25397364, 'author': 'shiv', 'author_id': 3728540, 'author_profile': 'https://Stackoverflow.com/users/3728540', 'pm_score': -1, 'selected': False, 'text': '<pre><code>import java.io.IOException;\nimport java.io.UnsupportedEncodingException;\nimport java.security.Key;\nimport javax.crypto.Cipher;\nimport javax.crypto.SecretKeyFactory;\nimport javax.crypto.spec.DESedeKeySpec;\nimport javax.crypto.spec.IvParameterSpec;\nimport java.util.Base64;\nimport java.util.Base64.Encoder;\n\n\n/**\n * \n * @author shivshankar pal\n * \n *         this code is working properly. doing proper encription and decription\n           note:- it will work only with jdk8\n\n * \n\n * \n */\n\npublic class TDes {\n    private static byte[] key = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n            0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x02,\n            0x02, 0x02, 0x02, 0x02, 0x02, 0x02 };\n\n    private static byte[] keyiv = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n            0x00 };\n\n\n\n     public static String encode(String args) {\n\n\n        System.out.println("plain data==&gt;  " + args);\n\n        byte[] encoding;\n        try {\n            encoding = Base64.getEncoder().encode(args.getBytes("UTF-8"));\n\n        System.out.println("Base64.encodeBase64==&gt;" + new String(encoding));\n        byte[] str5 = des3EncodeCBC(key, keyiv, encoding);\n\n        System.out.println("des3EncodeCBC==&gt;  " + new String(str5));\n\n        byte[] encoding1 = Base64.getEncoder().encode(str5);\n        System.out.println("Base64.encodeBase64==&gt; " + new String(encoding1));\n        return new String(encoding1);\n        } catch (UnsupportedEncodingException e) {\n            // TODO Auto-generated catch block\n            e.printStackTrace();\n        }\n        return null;\n    }\n\n\n    public static String decode(String args) {\n        try {\n            System.out.println("encrypted data==&gt;" + new String(args.getBytes("UTF-8")));\n\n\n        byte[] decode = Base64.getDecoder().decode(args.getBytes("UTF-8"));\n        System.out.println("Base64.decodeBase64(main encription)==&gt;" + new String(decode));\n\n        byte[] str6 = des3DecodeCBC(key, keyiv, decode);\n        System.out.println("des3DecodeCBC==&gt;" + new String(str6));\n        String data=new String(str6);\n        byte[] decode1 = Base64.getDecoder().decode(data.trim().getBytes("UTF-8"));\n        System.out.println("plaintext==&gt;  " + new String(decode1));\n        return new String(decode1);\n        } catch (UnsupportedEncodingException e) {\n            // TODO Auto-generated catch block\n            e.printStackTrace();\n        }\n        return "u mistaken in try block";\n\n        }\n\n\n\n    private static byte[] des3EncodeCBC(byte[] key, byte[] keyiv, byte[] data) {\n        try {\n            Key deskey = null;\n            DESedeKeySpec spec = new DESedeKeySpec(key);\n            SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");\n            deskey = keyfactory.generateSecret(spec);\n\n            Cipher cipher = Cipher.getInstance("desede/ CBC/PKCS5Padding");\n            IvParameterSpec ips = new IvParameterSpec(keyiv);\n            cipher.init(Cipher.ENCRYPT_MODE, deskey, ips);\n            byte[] bout = cipher.doFinal(data);\n            return bout;\n\n        } catch (Exception e) {\n            System.out.println("methods qualified name" + e);\n        }\n        return null;\n\n    }\n\n    private static byte[] des3DecodeCBC(byte[] key, byte[] keyiv, byte[] data) {\n        try {\n            Key deskey = null;\n            DESedeKeySpec spec = new DESedeKeySpec(key);\n            SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");\n            deskey = keyfactory.generateSecret(spec);\n\n            Cipher cipher = Cipher.getInstance("desede/ CBC/NoPadding");//PKCS5Padding NoPadding\n            IvParameterSpec ips = new IvParameterSpec(keyiv);\n            cipher.init(Cipher.DECRYPT_MODE, deskey, ips);\n\n            byte[] bout = cipher.doFinal(data);\n\n\n            return bout;\n\n        } catch (Exception e) {\n            System.out.println("methods qualified name" + e);\n        }\n\n        return null;\n\n    }\n\n}\n</code></pre>\n'}, {'answer_id': 70600508, 'author': 'Ayomide Joysbright Oyediran', 'author_id': 15661514, 'author_profile': 'https://Stackoverflow.com/users/15661514', 'pm_score': 0, 'selected': False, 'text': '<pre><code>private static final String UNICODE_FORMAT = &quot;UTF8&quot;;\nprivate static final String DESEDE_ENCRYPTION_SCHEME = &quot;DESede&quot;;\nprivate KeySpec ks;\nprivate SecretKeyFactory skf;\nprivate Cipher cipher;\nbyte[] arrayBytes;\nprivate String encryptionSecretKey = &quot;ThisIsSpartaThisIsSparta&quot;;\nSecretKey key;\n\npublic TripleDesEncryptDecrypt() throws Exception {\n    convertStringToSecretKey(encryptionSecretKey);\n}\n\npublic TripleDesEncryptDecrypt(String encryptionSecretKey) throws Exception {\n    convertStringToSecretKey(encryptionSecretKey);\n}\n\npublic SecretKey convertStringToSecretKey (String encryptionSecretKey) throws Exception {\n    arrayBytes = encryptionSecretKey.getBytes(UNICODE_FORMAT);\n    ks = new DESedeKeySpec(arrayBytes);\n    skf = SecretKeyFactory.getInstance(DESEDE_ENCRYPTION_SCHEME);\n    cipher = Cipher.getInstance(DESEDE_ENCRYPTION_SCHEME);\n    key = skf.generateSecret(ks);\n    return key;\n}\n\n/**\n * Encrypt without specifying secret key\n * \n * @param unencryptedString\n * @return String\n */\npublic String encrypt(String unencryptedString) {\n    String encryptedString = null;\n    try {\n        cipher.init(Cipher.ENCRYPT_MODE, key);\n        byte[] plainText = unencryptedString.getBytes(UNICODE_FORMAT);\n        byte[] encryptedText = cipher.doFinal(plainText);\n        encryptedString = new String(Base64.encodeBase64(encryptedText));\n    } catch (Exception e) {\n        e.printStackTrace();\n    }\n    return encryptedString;\n}\n\n/**\n * Encrypt with specified secret key\n * \n * @param unencryptedString\n * @return String\n */\npublic String encrypt(String encryptionSecretKey, String unencryptedString) {\n    String encryptedString = null;\n    try {\n        key = convertStringToSecretKey(encryptionSecretKey);\n        cipher.init(Cipher.ENCRYPT_MODE, key);\n        byte[] plainText = unencryptedString.getBytes(UNICODE_FORMAT);\n        byte[] encryptedText = cipher.doFinal(plainText);\n        encryptedString = new String(Base64.encodeBase64(encryptedText));\n    } catch (Exception e) {\n        e.printStackTrace();\n    }\n    return encryptedString;\n}\n\n\n/**\n * Decrypt without specifying secret key\n * @param encryptedString\n * @return\n */\npublic String decrypt(String encryptedString) {\n    String decryptedText=null;\n    try {\n        cipher.init(Cipher.DECRYPT_MODE, key);\n        byte[] encryptedText = Base64.decodeBase64(encryptedString);\n        byte[] plainText = cipher.doFinal(encryptedText);\n        decryptedText= new String(plainText);\n    } catch (Exception e) {\n        e.printStackTrace();\n    }\n    return decryptedText;\n}\n\n/**\n * Decrypt with specified secret key\n * @param encryptedString\n * @return\n */\npublic String decrypt(String encryptionSecretKey, String encryptedString) {\n    String decryptedText=null;\n    try {\n        key = convertStringToSecretKey(encryptionSecretKey);\n        cipher.init(Cipher.DECRYPT_MODE, key);\n        byte[] encryptedText = Base64.decodeBase64(encryptedString);\n        byte[] plainText = cipher.doFinal(encryptedText);\n        decryptedText= new String(plainText);\n    } catch (Exception e) {\n        e.printStackTrace();\n    }\n    return decryptedText;\n}\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/20227', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1486/']