Java DES 加密/解密

2018-07-20    来源:open-open

容器云强势上线!快速搭建集群,上万Linux镜像随意使用
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.Security;
import java.security.spec.AlgorithmParameterSpec;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;

public class Main {

    static Cipher ce;
    static Cipher cd;

    public static void main(String args[]) throws Exception {

        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

        SecretKey skey = KeyGenerator.getInstance("DES").generateKey();

        byte[] initializationVector = new byte[]{0x10, 0x10, 0x01, 0x04, 0x01, 0x01, 0x01, 0x02};

        AlgorithmParameterSpec algParameters = new IvParameterSpec(initializationVector);
        ce = Cipher.getInstance("DES/CBC/PKCS5Padding");
        cd = Cipher.getInstance("DES/CBC/PKCS5Padding");

        ce.init(Cipher.ENCRYPT_MODE, skey, algParameters);
        cd.init(Cipher.DECRYPT_MODE, skey, algParameters);

        FileInputStream is = new FileInputStream("C:/Users/nikos7/Desktop/output.txt");
        FileOutputStream os = new FileOutputStream("C:/Users/nikos7/Desktop/output2.txt");
        int dataSize = is.available();

        byte[] inbytes = new byte[dataSize];
        is.read(inbytes);

        String str2 = new String(inbytes);
        System.out.println("Input file content\n" + str2 + "\n");

        write_encode(inbytes, os);

        os.flush();
        is.close();
        os.close();

        System.out.println("Ecrypted Content to output2.txt\n");

        is = new FileInputStream("C:/Users/nikos7/Desktop/output2.txt");

        byte[] decBytes = new byte[dataSize];

        read_decode(decBytes, is);

        is.close();

        String str = new String(decBytes);

        System.out.println("Decrypted file contents:\n" + str);

    }

    public static void write_encode(byte[] bytes, OutputStream output) throws Exception {
        CipherOutputStream cOutputStream = new CipherOutputStream(output, ce);
        cOutputStream.write(bytes, 0, bytes.length);
        cOutputStream.close();
    }

    public static void read_decode(byte[] bytes, InputStream input) throws Exception {
        CipherInputStream cInputStream = new CipherInputStream(input, cd);
        int position = 0, i;

        while ((i = cInputStream.read()) != -1) {
            bytes[position] = (byte) i;
            position++;
        }
    }
}

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。

上一篇:jQuery 获取DOM节点的两种方式

下一篇:Java实现简单的HTTP服务器代码