2011-03-09 75 views
10

以下代碼適用於我使用BlowFish加密對字符串進行加密。在Java中使用BlowFish加密

  // create a key generator based upon the Blowfish cipher 
    KeyGenerator keygenerator = KeyGenerator.getInstance("Blowfish"); 

    // create a key 
    SecretKey secretkey = keygenerator.generateKey(); 

    // create a cipher based upon Blowfish 
    Cipher cipher = Cipher.getInstance("Blowfish"); 

    // initialise cipher to with secret key 
    cipher.init(Cipher.ENCRYPT_MODE, secretkey); 

    // get the text to encrypt 
    String inputText = "MyTextToEncrypt"; 

    // encrypt message 
    byte[] encrypted = cipher.doFinal(inputText.getBytes()); 

如果我想定義我自己的密鑰,我該怎麼做?

回答

25
String Key = "Something"; 
byte[] KeyData = Key.getBytes(); 
SecretKeySpec KS = new SecretKeySpec(KeyData, "Blowfish"); 
Cipher cipher = Cipher.getInstance("Blowfish"); 
cipher.init(Cipher.ENCRYPT_MODE, KS); 
+0

非常感謝了迅速的回答! – StefanE 2011-03-09 11:42:49

+0

@Erik也看看我的問題http://stackoverflow.com/questions/38007478/encrypt-and-decrypt-string-using-chacha20 – Nepster 2016-06-24 10:19:30

+0

該解決方案是不安全的,因爲它直接使用字符串作爲加密密鑰。 – Robert 2016-07-21 07:15:42

0

河豚的關鍵尺寸必須是32-448位。所以有必要根據位號(32位爲4字節)和反之。你

+0

你可以添加一些代碼,使其更清晰? – Trinimon 2013-03-19 18:30:40

0

也可以嘗試這個

String key = "you_key_here"; 
SecretKey secret_key = new SecretKeySpec(key.getBytes(), ALGORITM); 

和一點點here

0
String strkey="MY KEY"; 
    SecretKeySpec key = new SecretKeySpec(strkey.getBytes("UTF-8"), "Blowfish"); 
     Cipher cipher = Cipher.getInstance("Blowfish"); 
     if (cipher == null || key == null) { 
      throw new Exception("Invalid key or cypher"); 
     } 
     cipher.init(Cipher.ENCRYPT_MODE, key); 
String encryptedData =new String(cipher.doFinal(to_encrypt.getBytes("UTF-8")); 

解密:

  SecretKeySpec key = new SecretKeySpec(strkey.getBytes("UTF-8"), "Blowfish"); 
     Cipher cipher = Cipher.getInstance("Blowfish"); 
     cipher.init(Cipher.DECRYPT_MODE, key); 
     byte[] decrypted = cipher.doFinal(encryptedData); 
     return new String(decrypted); 
+0

此解決方案不安全,因爲它直接使用字符串作爲加密密鑰。 – Robert 2016-07-21 06:29:31

+0

@Robert現在你指出了一個問題,也許解釋做什麼可能會更有幫助。 – TheRealChx101 2018-02-17 21:12:35

+0

@ TheRealChx101:簡短的答案是你應該使用像PBKDF2,bcrypt,scrypt或者Argon2這樣的密鑰派生函數。然而,哪種配置取決於多種因素。 – Robert 2018-02-18 12:41:32