Encrypt Decrypt File dengan DES di Java

 


        Disini saya akan sharing bagaimana encrypt sebuah file dengan java. Umumnya yang diencrypt itu biasanya text disini saya akan mencoba mengencrypt sebuah filenya. apa yang diencrypt ?  jadi yang diencrypt adalah bytes code nya. jadi sebenarnya kalau di break down lagi file itu adalah kumpulan code yaitu bytes, nah disini kumpulan bytes itu kita encrypt. 
Gimana cara encryptnya ? disini cara encryptnya sebenarnya adalah kita punya plan text(text yang ingin kita encrypt) terus kita buat key nya yang mana hanya kita yang punya. kunci ini nantinya digunakan buat ngebuka enkripannya dan mengunci kembali. ingat kuncinya jangan lupa yaah heheh :)

Requirement: 
   - Java 1.8
   - IDE



Encrypt
encrypt adalah cara mengunci file dengan menggunakan key yang tadi kita buat.

public static byte[] compressGzip(byte[] val) throws IOException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream(val.length);
        GZIPOutputStream gos = null;
        try {
            gos = new GZIPOutputStream(bos);
            gos.write(val, 0, val.length);
            gos.finish();
            gos.flush();
            bos.flush();
            val = bos.toByteArray();
        } finally {
            if (gos != null)
                gos.close();
            if (bos != null)
                bos.close();
        }
        return val;
    }

public static byte[] encrypt(String key, InputStream is) throws Throwable {

        byte[] bytes = key.getBytes();
        System.out.println("bytes.length = " + bytes.length);

        DESKeySpec dks = new DESKeySpec(bytes);
        SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
        SecretKey desKey = skf.generateSecret(dks);

        String des = "DES";  // DES/ECB/PKCS5Padding for SunJCE
        des="DES/CBC/PKCS5Padding";
        Cipher cipher = Cipher.getInstance(des);

        IvParameterSpec ivParameterSpec = new IvParameterSpec(bytes);
        cipher.init(Cipher.ENCRYPT_MODE, desKey, ivParameterSpec);

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(2048);
        CipherOutputStream cos = new CipherOutputStream(byteArrayOutputStream, cipher);

        writeData(is, cos);

        return byteArrayOutputStream.toByteArray();
    }


    private static void writeData(InputStream is, OutputStream os) throws IOException {
        byte[] buf = new byte[1024];
        int numRead = 0;
        // read and write operation
        while ((numRead = is.read(buf)) >= 0) {
            os.write(buf, 0, numRead);
        }
        os.close();
        is.close();
    }

disini kita tambahin compress gzip agar lebih secure.
public static void main(String[] args) throws Throwable {
        // ENCRYPT
        Path path = Paths.get("/home/fluex404/Downloads/coba5/data.csv");
        byte[] data = Files.readAllBytes(path);
        String csv = "/home/fluex404/Downloads/coba5/data-ecrypt.csv";
        FileOutputStream fos = new FileOutputStream(csv);

        byte[] hasilEncryptBytes = compressGzip(encrypt("@Str1k3@", new ByteArrayInputStream(data)));

        System.out.println(hasilEncryptBytes);
        
        fos.write(hasilEncryptBytes);
    }

Decrypt
decrypt adalah cara membuka file yang sudah terkunci(encrypt) dengan sebuah key.

public static byte[] decompressGzip(byte[] inputBytes) throws IOException, FileNotFoundException {

        try (GZIPInputStream gis = new GZIPInputStream(
                new ByteArrayInputStream(inputBytes)
        );

             ByteArrayOutputStream fos = new ByteArrayOutputStream(2048)) {

            byte[] buffer = new byte[1024];
            int len;
            while ((len = gis.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
            }

            return fos.toByteArray();

        }

    }

public static byte[] decrypt(String key, InputStream is) throws Throwable {

        byte[] bytes = key.getBytes();
        System.out.println("bytes.length = " + bytes.length);

        DESKeySpec dks = new DESKeySpec(bytes);
        SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
        SecretKey desKey = skf.generateSecret(dks);

        String des = "DES";  // DES/ECB/PKCS5Padding for SunJCE
        des="DES/CBC/PKCS5Padding";
        Cipher cipher = Cipher.getInstance(des);

        IvParameterSpec ivParameterSpec = new IvParameterSpec(bytes);
        cipher.init(Cipher.DECRYPT_MODE, desKey, ivParameterSpec);

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(2048);
        CipherOutputStream cos = new CipherOutputStream(byteArrayOutputStream, cipher);

        writeData(is, cos);

        return byteArrayOutputStream.toByteArray();
    }

private static void writeData(InputStream is, OutputStream os) throws IOException {
        byte[] buf = new byte[1024];
        int numRead = 0;
        // read and write operation
        while ((numRead = is.read(buf)) >= 0) {
            os.write(buf, 0, numRead);
        }
        os.close();
        is.close();
    }

public static void main(String[] args) throws Throwable {
        Path path = Paths.get("/home/fluex404/Downloads/coba5/data-encrypt.csv");
        byte[] data = Files.readAllBytes(path);
        byte[] bs = decompressGzip(data);
        System.out.println("bs = " + new String(bs));

        FileOutputStream fos = new FileOutputStream("/home/fluex404/Downloads/coba5/data-decrypt.csv");
        byte[] obs = decrypt("@Str1k3@", new ByteArrayInputStream(bs));

        fos.write(obs);

    }



Komentar

Postingan populer dari blog ini

whois

Membuat export dan import Excel di spring boot

Spring Boot CRUD Thymeleaf-Pagination + Bootstrap Dynamic Modals