1

我在这里寻求有关我的程序的帮助。该程序可以使用基于 CBC 操作模式的 DES 对称密码对短语进行加密和解密。

我现在要做的是对其进行更改,使其可以使用 CBC 操作模式的 DES 对称密码加密和解密文本文件的内容。

任何人都可以帮我解决这个问题吗?

谢谢!

import java.security.*;

import javax.crypto.*;

import java.security.spec.*;

import javax.crypto.spec.*;

import javax.crypto.spec.IvParameterSpec;



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

    String text = "Hello World;

    SecureRandom sr = new SecureRandom();
    byte [] iv = new byte[8];
    sr.nextBytes(iv);
    IvParameterSpec IV = new IvParameterSpec(iv);
    KeyGenerator kg = KeyGenerator.getInstance("DES");
    Key mykey = kg.generateKey();
    Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, mykey,IV);

    byte[] plaintext = text.getBytes("UTF8");



    byte[] ciphertext = cipher.doFinal(plaintext);

    System.out.println("\n\nCiphertext: ");
    for (int i=0;i<ciphertext.length;i++) {

        if (chkEight(i)) {
            System.out.print("\n");
        }
        System.out.print(ciphertext[i]+" ");
    }
4

1 回答 1

0

所以你只想知道如何读写文件?

看看apache.commons.io.FileUtils。它提供了从文件读取和写入字符串的两种方法。这里有些例子:

// info.txt represents the path to the file
File someFile = new File("info.txt");

// Create String from File
try {
  String filecontent = FileUtils.readFileToString(someFile, Charset.defaultCharset());
  System.out.println(filecontent);

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

// Encode / Decode string here

// Write String to file     
try {
  FileUtils.writeStringToFile(someFile, "your new file content string", Charset.defaultCharset());
  System.out.println("Success!");

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

您可能希望使用不同的Charset,具体取决于文本文件的字符集。

于 2014-01-10T12:25:50.407 回答