Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encrypt Decrypt my own key not generated java

I am new to cryptography, so I have a question:

How can I create my own key (let`s say like a string "1234"). Because I need to encrypt a string with a key (defined by me), save the encrypted string in a database and when I want to use it, take it from the database and decrypt it with the key known by me.

I have this code :

   import java.security.InvalidKeyException;
   import java.security.*;
   import javax.crypto.BadPaddingException;
   import javax.crypto.Cipher;
   import javax.crypto.IllegalBlockSizeException;
   import javax.crypto.SecretKey;
   import javax.crypto.SecretKeyFactory;
   import javax.crypto.spec.DESedeKeySpec;

      public class LocalEncrypter {

    private static String algorithm = "PBEWithMD5AndDES";
   //private static Key key = null;
    private static Cipher cipher = null;
    private static SecretKey key;

    private static void setUp() throws Exception {
        ///key = KeyGenerator.getInstance(algorithm).generateKey();
        SecretKeyFactory factory = SecretKeyFactory.getInstance(algorithm);
        String pass1 = "thisIsTheSecretKeyProvidedByMe";
        byte[] pass = pass1.getBytes(); 
        SecretKey key = factory.generateSecret(new DESedeKeySpec(pass));
        cipher = Cipher.getInstance(algorithm);
    }

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

        byte[] encryptionBytes = null;
        String input = "1234";
        System.out.println("Entered: " + input);
        encryptionBytes = encrypt(input);
        System.out.println(
          "Recovered: " + decrypt(encryptionBytes));
    }

    private static byte[] encrypt(String input)
        throws InvalidKeyException, 
               BadPaddingException,
               IllegalBlockSizeException {
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] inputBytes = input.getBytes();
        return cipher.doFinal(inputBytes);
    }

    private static String decrypt(byte[] encryptionBytes)
        throws InvalidKeyException, 
               BadPaddingException,
               IllegalBlockSizeException {
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] recoveredBytes = 
          cipher.doFinal(encryptionBytes);
        String recovered = 
          new String(recoveredBytes);
        return recovered;
      }

}

   Exception in thread "main" java.security.spec.InvalidKeySpecException: Invalid key spec
at com.sun.crypto.provider.PBEKeyFactory.engineGenerateSecret(PBEKeyFactory.java:114)
at javax.crypto.SecretKeyFactory.generateSecret(SecretKeyFactory.java:335)
at LocalEncrypter.setUp(LocalEncrypter.java:22)
at LocalEncrypter.main(LocalEncrypter.java:28)
like image 364
user1069937 Avatar asked Apr 30 '26 18:04

user1069937


1 Answers

A KeyGenerator generates random keys. Since you know the secret key, what you need is a SecretKeyFactory. Get an instance for your algorithm (DESede), and then call its generateSecret méthode with an instance of DESedeKeySpec as argument:

SecretKeyFactory factory = SecretKeyFactory.getInstance("DESede");
SecretKey key = factory.generateSecret(new DESedeKeySpec(someByteArrayContainingAtLeast24Bytes));

Here is a complete example that works. As I said, DESedeKeySpec must be used with the DESede algorithm. Using a DESede key with PBEWithMD5AndDES makes no sense.

public class EncryptionTest {
    public static void main(String[] args) throws Exception {
        byte[] keyBytes = "1234567890azertyuiopqsdf".getBytes("ASCII");
        DESedeKeySpec keySpec = new DESedeKeySpec(keyBytes);
        SecretKeyFactory factory = SecretKeyFactory.getInstance("DESede");
        SecretKey key = factory.generateSecret(keySpec);
        byte[] text = "Hello world".getBytes("ASCII");

        Cipher cipher = Cipher.getInstance("DESede");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] encrypted = cipher.doFinal(text);

        cipher = Cipher.getInstance("DESede");
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] decrypted = cipher.doFinal(encrypted);
        System.out.println(new String(decrypted, "ASCII"));
    }
}
like image 158
JB Nizet Avatar answered May 03 '26 09:05

JB Nizet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!