Hello. It is necessary to encrypt and decrypt the file Blowfish (em). I'm new to this business. I tried to do. It turned out that the file is encrypted, but not decrypted. Help to understand what the problem is. Thank you in advance.

import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.security.Key; import javax.crypto.Cipher; import javax.crypto.CipherInputStream; import javax.crypto.CipherOutputStream; import javax.crypto.KeyGenerator; public class Blowfish { public static void main(String[] args) { try { String key = "squirrel123"; FileInputStream fis = new FileInputStream("original.txt"); FileOutputStream fos = new FileOutputStream("encrypted.txt"); encrypt(key, fis, fos); FileInputStream fis2 = new FileInputStream("encrypted.txt"); FileOutputStream fos2 = new FileOutputStream("decrypted.txt"); decrypt(key, fis2, fos2); } catch (Throwable e) { e.printStackTrace(); } } public static void encrypt(String key, InputStream is, OutputStream os) throws Throwable { encryptOrDecrypt(key, Cipher.ENCRYPT_MODE, is, os); } public static void decrypt(String key, InputStream is, OutputStream os) throws Throwable { encryptOrDecrypt(key, Cipher.DECRYPT_MODE, is, os); } public static void encryptOrDecrypt(String key, int mode, InputStream is, OutputStream os) throws Throwable { KeyGenerator keyGenerator = KeyGenerator.getInstance("Blowfish"); keyGenerator.init(128); Key secretKey = keyGenerator.generateKey(); Cipher cipher = Cipher.getInstance("Blowfish/CFB/NoPadding"); if (mode == Cipher.ENCRYPT_MODE) { cipher.init(Cipher.ENCRYPT_MODE, secretKey); CipherInputStream cis = new CipherInputStream(is, cipher); doCopy(cis, os); } else if (mode == Cipher.DECRYPT_MODE) { cipher.init(Cipher.DECRYPT_MODE, secretKey); CipherOutputStream cos = new CipherOutputStream(os, cipher); doCopy(is, cos); } } public static void doCopy(InputStream is, OutputStream os) throws IOException { byte[] bytes = new byte[64]; int numBytes; while ((numBytes = is.read(bytes)) != -1) { os.write(bytes, 0, numBytes); } os.flush(); os.close(); is.close(); } 

}

    1 answer 1

    The key parameter is not used, it turns out that you encrypt with one key, but try to decrypt it with another:

     Key secretKey = keyGenerator.generateKey(); 
    • Ie, this string is not needed at all. Key secretKey = keyGenerator.generateKey (); - Evilleks
    • 2
      When encrypting, you generate a random key through generateKey() , while decrypting, do the same, that is, generate a random key again. As you might guess, the key that you encrypt and the key that you decrypt must be identical. I'm just trying to push you to solve the problem on your own: you need to generate a key on the basis of a given string once or generate a random key once and transfer it during encryption and decryption. - Barmaley
    • Thank you, now I understand. - Evilleks