2011-03-09 4 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

+0

@ 에릭도 내 질문에 봐 http://stackoverflow.com/questions/38007478/encrypt-and-decrypt-string-using-chacha20 – Nepster

+0

이 솔루션은 직접 암호화 키로 문자열을 사용하기 때문에 안전하지 않습니다. – Robert

0

Blowfish의 키 크기는 32 - 448 비트 여야합니다. 따라서 비트 수 (32 비트의 경우 4 바이트)와 부제에 따라 바이트 배열을 만드는 것이 필요합니다.

+0

코드를 명확하게 만드는 몇 줄의 코드를 추가 할 수 있습니까? – Trinimon

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

이 솔루션은 암호화 키로 String을 직접 사용하기 때문에 안전하지 않습니다. – Robert

+0

@ 로버트 (Robert) 이제 문제를 지적 했으니 대신 무엇을해야할지 설명하면 도움이 될 것입니다. – TheRealChx101

+0

@ TheRealChx101 : 짧은 대답은 PBKDF2, bcrypt, scrypt 또는 Argon2와 같은 키 유도 함수를 사용해야한다는 것입니다. 그러나 어떤 구성에서 사용할 것인지는 여러 요소에 따라 다릅니다. – Robert

관련 문제