Java文本文件加密和解密密钥



我正在用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();
    }
}

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

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

最新更新