使用DES在java中使用私钥而不自动生成密钥

时间:2012-12-11 19:52:59

标签: java des encryption-symmetric

我必须使用带密钥的DES加密/解密java中的纯文本。我在IBM找到了一个非常好的教程,可以找到here。这个例子的问题是它正在程序本身生成密钥。现在,如果我加密一个字符串(例如密码)并存储在数据库中,那么我将无法解密它,因为我不知道密钥。

以下是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") );
}
}

任何人都可以建议我如何在此示例中添加自己的密钥?

2 个答案:

答案 0 :(得分:1)

如果您打算提供密钥,请将密钥设为args而不是generateKey。

编辑:generateKey生成一个随机密钥。保存此密钥以用于解密可能比添加代码以解析密钥arg更简单。请查看KeyGeneratorSecretKey

答案 1 :(得分:1)

查看SecretKeyFactoryDESKeySpec。这些可用于从密钥材料(字节数组)构造DES密钥。

您可以使用getEncoded()从DES密钥获取密钥材料。