2014-01-10 68 views
1

我在這裏尋找一些幫助我的程序。該程序可以基於CBC操作模式使用DES對稱密碼來加密和解密短語加密和解密文本文件的內容(Java)

我現在要做的是改變它,以便它可以使用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]+" "); 
    } 
+0

那麼到底發生了什麼問題,實際問題是什麼?如何解密?環顧Google呢? –

+0

**步驟1:**讀取文件的內容**步驟2:**加密/解密內容,如您之前所做的那樣**步驟3:**將加密/解密的內容寫入文件**步驟4:** **第5步:**利潤 –

+0

@CeilingGecko謝謝我需要這個。一步一步分解做什麼。現在開始Google搜索。 –

回答

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,這取決於你的文本文件的字符集。