2012-12-31 50 views
0

我想使用JCE API加密和解密文件和字符串與DES算法 ,我想給我自己的密鑰 ,但是當我找到一個例證,我發現關鍵是這樣產生的:在jce api中給我自己的密鑰加密java

import java.security.InvalidKeyException; 
import java.security.NoSuchAlgorithmException; 


import javax.crypto.BadPaddingException; 
import javax.crypto.Cipher; 
import javax.crypto.IllegalBlockSizeException; 
import javax.crypto.KeyGenerator; 
import javax.crypto.NoSuchPaddingException; 
import javax.crypto.SecretKey; 


public class JEncrytion 
{  
    public static void main(String[] argv) { 

     try{ 

      KeyGenerator keygenerator = KeyGenerator.getInstance("DES"); 
      SecretKey myDesKey = keygenerator.generateKey(); 
        String key = "zertyuio"; 
      Cipher desCipher; 

      // Create the cipher 
      desCipher = Cipher.getInstance("DES"); 

      // Initialize the cipher for encryption 
      desCipher.init(Cipher.ENCRYPT_MODE, myDesKey); 

      //sensitive information 
      byte[] text = "No body can see me".getBytes(); 

      System.out.println("Text [Byte Format] : " + text); 
      System.out.println("Text : " + new String(text)); 

      // Encrypt the text 
      byte[] textEncrypted = desCipher.doFinal(text); 

      System.out.println("Text Encryted : " + textEncrypted); 

      // Initialize the same cipher for decryption 
      desCipher.init(Cipher.DECRYPT_MODE, myDesKey); 

      // Decrypt the text 
      byte[] textDecrypted = desCipher.doFinal(textEncrypted); 

      System.out.println("Text Decryted : " + new String(textDecrypted)); 

     }catch(NoSuchAlgorithmException e){ 
      e.printStackTrace(); 
     }catch(NoSuchPaddingException e){ 
      e.printStackTrace(); 
     }catch(InvalidKeyException e){ 
      e.printStackTrace(); 
     }catch(IllegalBlockSizeException e){ 
      e.printStackTrace(); 
     }catch(BadPaddingException e){ 
      e.printStackTrace(); 
     } 

    } 
} 

你有什麼想法

預先感謝您

+1

你確定要使用DES?由於它的小關鍵,DES非常薄弱。 – CodesInChaos

回答

3

看一看類javax.crypto.spec.SecretKeySpec。它允許你使用一個保存密鑰的字節數組。

該實例可以作爲密鑰傳遞給Cipher.init方法。

2

對於DES您可以創建你的密鑰了DESKeySpec的:

SecretKey myDesKey = 
    SecretKeyFactory.getInstance("DES").generateSecret(new DESKeyspec(key.getBytes())); 
相關問題