在JAVA中使用DES演算法加密資料

來源:互聯網
上載者:User

        在JDK的javax.crypto 的包中提供了對一些通用演算法的加密解密的支援,本文簡介一下使用DES演算法來對資料加密解密。通常是資料加密方用密鑰將資料加密,資料解密方用同樣的密鑰將資料解密。這個密鑰是包含8位byte的一個二進位的檔案,加密解密方可以是任何開發語言。

        用JAVA產生一個key並儲存到一個二進位檔案中去的方法如下:

    public static void saveBytePriveKey(String file) {

        try {
            KeyGenerator keyGen = KeyGenerator.getInstance("DES");

            SecretKey key = keyGen.generateKey();// 產生私密金鑰Key

            FileOutputStream fop = new FileOutputStream(file);
            fop.write(key.getEncoded());
            fop.close();
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }

     從密鑰檔案中讀取內容產生密鑰:

    public static SecretKey getBytePriveKey(String file) throws Exception {
        File keyf = new File(file);
        long length = keyf.length();
        byte[] bytes = new byte[(int) length];

        FileInputStream fis = new FileInputStream(keyf);

        // Read in the bytes
        int offset = 0;
        int numRead = 0;

        while (offset < bytes.length && (numRead = fis.read(bytes, offset, bytes.length - offset)) >= 0) {
            offset += numRead;
        }
        DESKeySpec dks = new DESKeySpec(bytes);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey key = keyFactory.generateSecret(dks);

        return key;
    }

        對檔案進行加密,對檔案的操作應該是以流的方式,加密後的資料是一個二進位流,它可能不能被對應到任何編碼的String,所以在操作過程中不應該將加密後的byte資料轉換為String。將一個檔案加密為另一個檔案的代碼如下:

    public static void encryptFile(String plainFile, String encryptedFile, String keyFile) {
        try {

            SecretKey key = getBytePriveKey(keyFile);
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.ENCRYPT_MODE, key);

            FileInputStream fis = new FileInputStream(plainFile);
            FileOutputStream fos = new FileOutputStream(encryptedFile);
            crypt(fis, fos, cipher);

            fis.close();
            fos.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void crypt(InputStream in, OutputStream out, Cipher cipher) throws IOException,
            GeneralSecurityException {
        int blockSize = cipher.getBlockSize();
        int outputSize = cipher.getOutputSize(blockSize);
        System.out.println("blockSize " + blockSize + " outputSize" + outputSize);

        byte[] inBytes = new byte[blockSize];
        byte[] outBytes = new byte[outputSize];

        int inLength = 0;
        boolean more = true;
        while (more) {
            inLength = in.read(inBytes);
            if (inLength == blockSize) {
                int outLength = cipher.update(inBytes, 0, blockSize, outBytes);
                out.write(outBytes, 0, outLength);
            } else {
                more = false;
            }
        }
        if (inLength > 0)
            outBytes = cipher.doFinal(inBytes, 0, inLength);
        else
            outBytes = cipher.doFinal();
        out.write(outBytes);
    }

      同樣,在解密過程中,對資料也應該以流的方式:

    public static void decryptFile(String encryptedFile, String decryptedFile, String keyFile) {
        try {

            SecretKey key = getBytePriveKey(keyFile);
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.DECRYPT_MODE, key);

            FileInputStream fis = new FileInputStream(encryptedFile);
            FileOutputStream fos = new FileOutputStream(decryptedFile);
            crypt(fis, fos, cipher);

            fis.close();
            fos.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

        如果是想把很多String一行一行的加密後儲存到一個檔案,應該先把這些String儲存到一個中間檔案,然後把中間檔案以流的方式讀入,以加密檔案的方式進行。我嘗試著把

加密一個String就寫到檔案中,但是發現最後解密的時候會有問題。

下面是整個類的原始碼:

package com.test.endecrypt;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.GeneralSecurityException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

public class DESCrypter {

    private static String bytekeyfile = "d://temp//bytekeyfile";

    private static String originalfile = "d://temp//originalfile";
    private static String encryptedfile = "d://temp//encryptedfile";
    private static String decryptedfile = "d://temp//decryptedfile";

    public static void main(String args[]) {

        saveBytePriveKey(bytekeyfile);

        encryptFile(originalfile, encryptedfile, bytekeyfile);

        decryptFile(encryptedfile, decryptedfile, bytekeyfile);

        String[] strings = { "要加密的串 the text to be encrypt", "AAAAAAAAAAA", "要加密的串 the text to be encrypt" };
        encryptStringsTofile(strings, encryptedfile, bytekeyfile);
        decryptFile(encryptedfile, decryptedfile, bytekeyfile);
    }

    public static void encryptFile(String plainFile, String encryptedFile, String keyFile) {
        try {

            SecretKey key = getBytePriveKey(keyFile);
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.ENCRYPT_MODE, key);

            FileInputStream fis = new FileInputStream(plainFile);
            FileOutputStream fos = new FileOutputStream(encryptedFile);
            crypt(fis, fos, cipher);

            fis.close();
            fos.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void encryptStringsTofile(String[] strings, String encryptedFile, String keyFile) {
        try {

            SecretKey key = getBytePriveKey(keyFile);
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.ENCRYPT_MODE, key);

            FileOutputStream fos = new FileOutputStream(encryptedFile);
            crypt(strings, fos, cipher);

            fos.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static void crypt(InputStream in, OutputStream out, Cipher cipher) throws IOException,
            GeneralSecurityException {
        int blockSize = cipher.getBlockSize();
        int outputSize = cipher.getOutputSize(blockSize);
        System.out.println("blockSize " + blockSize + " outputSize" + outputSize);

        byte[] inBytes = new byte[blockSize];
        byte[] outBytes = new byte[outputSize];

        int inLength = 0;
        boolean more = true;
        while (more) {
            inLength = in.read(inBytes);
            if (inLength == blockSize) {
                int outLength = cipher.update(inBytes, 0, blockSize, outBytes);
                out.write(outBytes, 0, outLength);
            } else {
                more = false;
            }
        }
        if (inLength > 0)
            outBytes = cipher.doFinal(inBytes, 0, inLength);
        else
            outBytes = cipher.doFinal();
        out.write(outBytes);
    }

    public static void crypt(String strings[], OutputStream out, Cipher cipher) throws IOException,
            GeneralSecurityException {
        for (String str : strings) {
            byte[] encryptedBytes = encrypt(str + "\r\n", "UTF8", cipher);
            out.write(encryptedBytes);
        }

    }

    public static byte[] encrypt(String in, String strEncode, Cipher cipher) throws IOException,
            GeneralSecurityException {
        byte[] originalBytes = in.getBytes(strEncode);
        byte[] encryptedBytes = cipher.doFinal(originalBytes);

        return encryptedBytes;
    }

    public static void decryptFile(String encryptedFile, String decryptedFile, String keyFile) {
        try {

            SecretKey key = getBytePriveKey(keyFile);
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.DECRYPT_MODE, key);

            FileInputStream fis = new FileInputStream(encryptedFile);
            FileOutputStream fos = new FileOutputStream(decryptedFile);
            crypt(fis, fos, cipher);

            fis.close();
            fos.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static SecretKey createSecretKey(String algorithm) {
        // 聲明KeyGenerator對象
        KeyGenerator keygen;
        // 聲明 金鑰組象
        SecretKey deskey = null;
        try {
            // 返回產生指定演算法的秘密密鑰的 KeyGenerator 對象
            keygen = KeyGenerator.getInstance(algorithm);
            // 產生一個密鑰
            deskey = keygen.generateKey();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        // 返回密匙
        return deskey;
    }

    // 把Key 寫到檔案中:產生一個私人Key對象,儲存在檔案中
    public static void saveBytePriveKey(String file) {

        try {
            KeyGenerator keyGen = KeyGenerator.getInstance("DES");

            SecretKey key = keyGen.generateKey();// 產生私密金鑰Key

            FileOutputStream fop = new FileOutputStream(file);
            fop.write(key.getEncoded());
            fop.close();
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }
    public static SecretKey getBytePriveKey(String file) throws Exception {
        File keyf = new File(file);
        long length = keyf.length();
        byte[] bytes = new byte[(int) length];

        FileInputStream fis = new FileInputStream(keyf);

        // Read in the bytes
        int offset = 0;
        int numRead = 0;

        while (offset < bytes.length && (numRead = fis.read(bytes, offset, bytes.length - offset)) >= 0) {
            offset += numRead;
        }
        DESKeySpec dks = new DESKeySpec(bytes);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey key = keyFactory.generateSecret(dks);

        return key;
    }

}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.