Java Network(Socket) Daha iyi kod için…
May 01
import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import java.io.*;
import java.security.spec.AlgorithmParameterSpec;
 
public class FileEncrypt {
 
    Cipher ecipher;
    Cipher dcipher;
 
    public FileEncrypt(SecretKey key) {
        // 8-byte başlangıç vektörümüz
        byte[] iv = new byte[]{
                (byte) 0x8E, 0x12, 0x39, (byte) 0x9C,
                0x07, 0x72, 0x6F, 0x5A
        };
        AlgorithmParameterSpec paramSpec = new IvParameterSpec(iv);
        try {
            ecipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
            dcipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
 
            ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
            dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
        } catch (Exception exc) {
            exc.printStackTrace();
        }
    }
 
    byte[] buffer = new byte[1024];
 
    public void encrypt(InputStream in, OutputStream out) {
        try {
            out = new CipherOutputStream(out, ecipher);
 
            int numRead = 0;
            while ((numRead = in.read(buffer)) >= 0) {
                out.write(buffer, 0, numRead);
            }
            out.close();
        } catch (IOException exc) {
            exc.printStackTrace();
        }
    }
 
    public void decrypt(InputStream in, OutputStream out) {
        try {
            in = new CipherInputStream(in, dcipher);
 
            int numRead = 0;
            while ((numRead = in.read(buffer)) >= 0) {
                out.write(buffer, 0, numRead);
            }
            out.close();
        } catch (IOException exc) {
            exc.printStackTrace();
        }
    }
 
    public static void main(String[] args) {
        try {
            // Bir random KEY oluşturalım
            SecretKey key = null;
            key=KeyGenerator.getInstance("DES").generateKey();
 
            // Sınıfımızı oluşturalım
            FileEncrypt encrypter = new FileEncrypt(key);
 
            // şifrele
            encrypter.encrypt(new FileInputStream("a.txt"),
                    new FileOutputStream("b.txt"));
 
            // şifreyi çöz
            encrypter.decrypt(new FileInputStream("b.txt"),
                    new FileOutputStream("a.txt"));
 
           // Şifreli dosyayı çözmeye çalışırken 
           // aynı şifreyi kullanmayı unutmayın.
        } catch (Exception exc) {
            exc.printStackTrace();
        }
    }
}

yazan Erol KOCAMAN

Cevapla