用Java加密和解密文本文件的关键

时间:2015-10-08 02:38:29

标签: java string encryption integer

我正在使用Java加密/解密程序。我正在使用一个名为“secret1234”的密钥来加密和解密来自文本文件的消息。该程序使用字符串作为密钥。但是,我有兴趣使用数字(整数)作为密钥,因此我可以生成随机数。那么,如何修改此程序以允许密钥为整数而不是用于加密和解密消息的字符串?

这是该计划:

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

public class Program {

    public static void main(String[] args) {

        try {
            String key = "secret1234";// This is the key

            FileInputStream fis = new FileInputStream("text.txt");//text.txt is a text file with a short message                                        
            FileOutputStream fos = new FileOutputStream("encryptedText.txt");
            encrypt(key, fis, fos);

            FileInputStream fis2 = new FileInputStream("encryptedText.txt");
            FileOutputStream fos2 = new FileOutputStream("decryptedText.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 {

        DESKeySpec dks = new DESKeySpec(key.getBytes());
        SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
        SecretKey desKey = skf.generateSecret(dks);
        Cipher cipher = Cipher.getInstance("DES");

        if (mode == Cipher.ENCRYPT_MODE) {
            cipher.init(Cipher.ENCRYPT_MODE, desKey);
            CipherInputStream cis = new CipherInputStream(is, cipher);
            doCopy(cis, os);
        } else if (mode == Cipher.DECRYPT_MODE) {
            cipher.init(Cipher.DECRYPT_MODE, desKey);
            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 个答案:

答案 0 :(得分:1)

在代码中使用它来生成密钥:

String key = String.valueOf(SecureRandom.getInstance("SHA1PRNG").nextInt());