简体   繁体   中英

Use private key in java using DES without generating key automatically

I have to encrypt/decrypt plain text in java using DES with a key. I have got a very good tutorial at IBM which can be found here . The problem with this example is that it is generating the key in the program itself. Now if I encrypt a string(eg password) and store in database then I would not be able to decrypt it because I would not know the key.

Below is the example at IBM

import java.security.*;
import javax.crypto.*;
//
// encrypt and decrypt using the DES private key algorithm
public class PrivateExample {

  public static void main (String[] args) throws Exception {
  //
  // check args and get plaintext
    if (args.length !=1) {
      System.err.println("Usage: java PrivateExample text");
      System.exit(1);
    }
  byte[] plainText = args[0].getBytes("UTF8");
  //
  // get a DES private key
  System.out.println( "\nStart generating DES key" );
  KeyGenerator keyGen = KeyGenerator.getInstance("DES");
  keyGen.init(56);
  Key key = keyGen.generateKey();
  System.out.println( "Finish generating DES key" );
//
// get a DES cipher object and print the provider
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
System.out.println( "\n" + cipher.getProvider().getInfo() );
//
// encrypt using the key and the plaintext
System.out.println( "\nStart encryption" );
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] cipherText = cipher.doFinal(plainText);
System.out.println( "Finish encryption: " );
System.out.println( new String(cipherText, "UTF8") );

//
// decrypt the ciphertext using the same key
System.out.println( "\nStart decryption" );
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] newPlainText = cipher.doFinal(cipherText);
System.out.println( "Finish decryption: " );

System.out.println( new String(newPlainText, "UTF8") );
}
}

Can anyone suggest how can I add my own key in this example?

Make the key one of the args instead of generateKey if you plan to supply the key.

Edit: generateKey generates a random key. It might be simpler to save this key to use for decryption than to add code to parse a key arg. Have a look at KeyGenerator and SecretKey .

Have a look at SecretKeyFactory and DESKeySpec . These can be used to construct a DES key from the key material (a byte array).

You can get the key material from a DES key using getEncoded() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM