-2

There are other similar questions on SO but none of them solve my problem. So, I ask a new question.

I have text to encrypt (String) and 8-byte key to DES encrypt it (and 16-byte key for EDE triple DES encrypt it) as byte-array.

How do I use Java's inbuilt Cipher class to encrypt and then decrypt my text?

Even If anyone suggests any other third party code, jar etc. as far as it supports this specific use case, it is also accepted.

Richard Chambers
  • 16,643
  • 4
  • 81
  • 106
vish4071
  • 5,135
  • 4
  • 35
  • 65

1 Answers1

0

Some code I use:

import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import javax.xml.bind.DatatypeConverter;

        public class CryptoPropio {


            /**
             * Master password.
             */
            private static char[] PASSWORD;

            /** The Constant SALT. */
            private static final byte[] SALT = { (byte) 0xde, (byte) 0x33, (byte) 0x10,
                    (byte) 0x12, (byte) 0xde, (byte) 0x33, (byte) 0x10, (byte) 0x12, };

            /** The error des. */
            private static String errorDes = "Error al des/encriptar";

            /** The Constant ALGORITMO. */
            private static final String ALGORITMO = "PBEWithMD5AndDES";

            /**
             * Instantiates a new crypto propio.
             * 
             * @param pass
             *            the pass
             */
            public CryptoPropio(String pass) {
                super();
                PASSWORD = pass.toCharArray();

            }


            public String encrypt(String property) {
                SecretKeyFactory keyFactory;
                String result = null;

                try {
                    keyFactory = SecretKeyFactory.getInstance(ALGORITMO);

                    SecretKey key = keyFactory.generateSecret(new PBEKeySpec(PASSWORD));
                    Cipher pbeCipher = Cipher.getInstance(ALGORITMO);
                    pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(SALT,
                            20));
                    result = base64Encode(
                                    pbeCipher.doFinal(property.getBytes("UTF-8")))
                                    .toString();
                } catch (InvalidKeyException | InvalidAlgorithmParameterException
                        | NoSuchAlgorithmException | InvalidKeySpecException
                        | NoSuchPaddingException | IllegalBlockSizeException
                        | BadPaddingException | UnsupportedEncodingException e) {
                  e.printStackTrace();
                }

                return result;
            }

            /**
             * Base64 encode.
             * 
             * @param bytes
             *            the bytes
             * @return the string
             */
            private String base64Encode(byte[] bytes) {
                return DatatypeConverter.printBase64Binary(bytes);
            }


            public String decrypt(String propert) {
                String property = propert;
                String result = null;
                try {
                    SecretKeyFactory keyFactory = SecretKeyFactory
                            .getInstance(ALGORITMO);
                    SecretKey key = keyFactory.generateSecret(new PBEKeySpec(PASSWORD));
                    Cipher pbeCipher = Cipher.getInstance(ALGORITMO);
                    pbeCipher.init(Cipher.DECRYPT_MODE, key, new PBEParameterSpec(SALT,
                            20));
                    result = new String(pbeCipher.doFinal(base64Decode(property)),
                            "UTF-8");
                } catch (InvalidKeyException | InvalidAlgorithmParameterException
                        | NoSuchAlgorithmException | InvalidKeySpecException
                        | NoSuchPaddingException | IllegalBlockSizeException
                        | BadPaddingException | UnsupportedEncodingException e) {
                   e.printStackTrace();
                }
                return result;
            }

            /**
             * Base64 decode.
             * 
             * @param property
             *            the property
             * @return the byte[]
             */
            private byte[] base64Decode(String property) {

                return DatatypeConverter.parseBase64Binary(property);
            }

        }
David Herrero
  • 704
  • 5
  • 17
  • What is this `ALGORITMO` doing? I mean, I don't get what it is for. We are encrypting the `PASSWORD` and using the 8-sized byte array to generate the key. But in my case, 8/16 sized byte array *is* my key. – vish4071 Sep 15 '15 at 09:38
  • http://docs.oracle.com/javase/7/docs/technotes/guides/security/StandardNames.html#SecretKeyFactory – ThreeSidedCoin Sep 15 '15 at 09:41
  • ALGORITMO is the Algorithm used by the Cipher, as @ThreeSidedCoin said there are a lot of possibilities, any of them with pros and cons...use the algorithm that fits in your code. – David Herrero Sep 15 '15 at 09:54
  • @DavidHerrero and threesidedcoin, this is fine as far as my use case is concerned. But my problem is, I have the key as 8-byte byte[]. So why would I generate a key. – vish4071 Sep 15 '15 at 10:05
  • @ThreeSidedCoin and davidherrero, if this line `SecretKey key = keyFactory.generateSecret(new PBEKeySpec(PASSWORD));` is generating a key, why does it use `PASSWORD`, which is the text to be encrypted? – vish4071 Sep 15 '15 at 10:06
  • the answer is incomplete: Constantes.MYENC – ThreeSidedCoin Sep 15 '15 at 11:18
  • In this case, PASSWORD is the key will be used for encrypt/decrypt. An example of use would be: `CryptoPropio instance = new CryptoPropio(yourPasswordAsString); instance.encrypt("TextToEncrypt");` – David Herrero Sep 15 '15 at 12:19
  • I sincerely hope this translates to "my crypto" instead of "proper crypto". – Maarten Bodewes Sep 15 '15 at 13:06
  • If `PASSWORD` is being used as key, this, in no way now, solves my scenario. – vish4071 Sep 15 '15 at 13:34