19

I convert the secretkey into bytes with following code

SecretKey key = KeyGenerator.getInstance("DES").generateKey();
byte[] bkey=key.getEncoded();

Now how do I get the key from bkey? I tried:

SecretKeySpec secretkey = new SecretKeySpec(bkey,"DES");   
SecretKeyFactory sfkey = SecretKeyFactory.getInstance("DES");
SecretKey skey = sfkey.generateSecret(secretkey);

I get the following error:

Error during Exception java.security.spec.InvalidKeySpecException: Inappropriate key specification
Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
Princeyesuraj
  • 5,228
  • 6
  • 22
  • 27
  • 1
    Why do you need to do this? Just pass `key` to your cipher. – user634618 Mar 19 '11 at 19:31
  • why was this down voted? seems like a reasonable question to me. – MeBigFatGuy Mar 19 '11 at 19:31
  • @user634618: I actually use that bytes format to save it in database and use it back to decrypt – Princeyesuraj Mar 19 '11 at 19:40
  • Using DES in 2011? Stop bothering and use cleartext, it's not any less secure... – Bruno Rohée Mar 31 '11 at 11:35
  • 1
    @Bruno Ya But I was just learning how DES works – Princeyesuraj Apr 04 '11 at 11:04
  • 18
    @BrunoRohée: Some people just want their questions answered without a condescending, elitist response. Comments like that make inexperienced users afraid to post their questions; I would know because I was (and still sort of am) in that situation myself... – araisbec Nov 11 '12 at 19:16
  • 3
    @araisbec It wasn't an answer but a comment, and some people actually do appreciate being stopped early when their wandering leads them straight to the abyss. Example abound on this very site of people using grossly insecure crypto because no one told them early enough. – Bruno Rohée Nov 12 '12 at 09:32
  • 1
    @BrunoRohée, I'm assuming you are talking PKCS container when you say cleartext. Is the key saved in cleartext smaller than its size in byte format? – AaA Aug 16 '17 at 09:53

2 Answers2

35

This should work

    SecretKey key = KeyGenerator.getInstance("DES").generateKey();
    byte[] data = key.getEncoded();
    SecretKey key2 = new SecretKeySpec(data, 0, data.length, "DES");
MeBigFatGuy
  • 28,272
  • 7
  • 61
  • 66
3

Try some of this code...

import javax.crypto.Cipher;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.security.InvalidKeyException;

public class DESede {
    private static String algorithm = "DESede";
    private static Key key = null;
    private static SecretKey secretKey = null;
    private static Cipher cipher = null;
    private static DESede obj = new DESede();

    private DESede() {
        try {
            key = KeyGenerator.getInstance(algorithm).generateKey();
            KeyGenerator.getInstance(algorithm).getProvider();
            byte[] keyBytes = key.getEncoded();
            String keyFormat = key.getFormat();
            String keyAlgorithm = key.getAlgorithm();
            String keyString = new String(keyBytes);
            System.out.println("Key Format::" + keyFormat);
            System.out.println("Key Algorithm::" + keyAlgorithm);
            System.out.println("Key String::" + keyString);
            keyString.getBytes();
            secretKey = new SecretKeySpec(keyBytes, 0, keyBytes.length, "DESede");
            byte[] secretKeyBytes = key.getEncoded();
            String secretKeyFormat = key.getFormat();
            String secretKeyAlgorithm = key.getAlgorithm();
            String secretKeyString = new String(secretKeyBytes);
            System.out.println("Secret Key Format::" + secretKeyFormat);
            System.out.println("Secret Key Algorithm::" + secretKeyAlgorithm);
            System.out.println("Secret Key String::" + secretKeyString);
            String keyNewString = "bXŒ*êÂÕê›æOÄ’Îý‘ãô|8¶Ë1­";
            byte[] keyNewBytes = keyString.getBytes();
            secretKey = new SecretKeySpec(keyBytes, 0, keyBytes.length, "DESede");
            cipher = Cipher.getInstance(algorithm);
        } catch (Exception e) {
        }
    }

    public static DESede getInstance() {
        return obj;
    }

    public static byte[] encrypt(String input) throws InvalidKeyException,
            BadPaddingException, IllegalBlockSizeException {
        System.out.println("Inside encrypt()");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] inputBytes = input.getBytes();
        System.out.println("Exit encrypt()");
        return cipher.doFinal(inputBytes);
    }

    public static String decrypt(byte[] encryptionBytes)
            throws InvalidKeyException, BadPaddingException,
            IllegalBlockSizeException {
        System.out.println("Inside decrypt()");
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] recoveredBytes = cipher.doFinal(encryptionBytes);
        String recovered = new String(recoveredBytes);
        System.out.println("Exiting decrypt()");
        return recovered;
    }

    public static void main(String args[]) throws InvalidKeyException,
            BadPaddingException, IllegalBlockSizeException {
        byte[] encryptedValue = DESede.encrypt("plz try encrypt and decrypt me");
        System.out.println("encryptedValue::" + encryptedValue);
        String decryptedValue = DESede.decrypt(encryptedValue);
        System.out.println("decryptedValue::" + decryptedValue);
    }
}
wattostudios
  • 8,666
  • 13
  • 43
  • 57
Manoj
  • 31
  • 1