2011-03-09 6 views
10

ब्लॉफिश एन्क्रिप्शन के साथ स्ट्रिंग को एन्क्रिप्ट करने के लिए निम्नलिखित कोड ठीक काम करता है।जावा में ब्लोफिश के साथ एन्क्रिप्शन

  // 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

@Erik भी मेरे प्रश्न पर एक नज़र डालें http://stackoverflow.com/questions/38007478/encrypt-and-decrypt-string-using-chacha20 – Nepster

+0

यह समाधान असुरक्षित है क्योंकि यह सीधे स्ट्रिंग को क्रिप्टोग्राफिक कुंजी के रूप में उपयोग करता है। – Robert

0

ब्लोफिश का मुख्य आकार 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

यह समाधान असुरक्षित है क्योंकि यह सीधे स्ट्रिंग को क्रिप्टोग्राफिक कुंजी के रूप में उपयोग करता है। – Robert

+0

@Robert अब जब आप किसी समस्या की ओर इशारा करते हैं, तो शायद यह समझाएं कि इसके बजाय क्या करना है और अधिक सहायक हो सकता है। – TheRealChx101

+0

@ TheRealChx101: संक्षिप्त उत्तर यह है कि आपको एक प्रमुख व्युत्पन्न कार्य का उपयोग करना चाहिए जैसे PBKDF2, bcrypt, scrypt या Argon2। हालांकि कौन सा कॉन्फ़िगरेशन उपयोग करने के लिए कई कारकों पर निर्भर करता है। – Robert

संबंधित मुद्दे