我尝试使用.NET加密库加密和解密文件。但是,它似乎不起作用,因为解密文件总是乱码。问题所在的任何想法,即加密或解密?
请参阅下面的源代码。
open System
open System.IO
open System.Security.Cryptography
open System.Text
// Encrypt
let encrypt (key : string) inFile outFile =
let aes = new RijndaelManaged()
let encryptor = aes.CreateEncryptor(ASCIIEncoding.UTF8.GetBytes(key), ASCIIEncoding.UTF8.GetBytes(key))
let fsOut = new FileStream(outFile, FileMode.Create)
let cs = new CryptoStream(fsOut, encryptor, CryptoStreamMode.Write)
cs.Write(buf, 0, buf.Length)
fsOut.Close()
// Decrypt 2
let decrypt (key : string) inFile outFile =
let aes = new RijndaelManaged()
let decryptor = aes.CreateEncryptor(ASCIIEncoding.UTF8.GetBytes(key), ASCIIEncoding.UTF8.GetBytes(key))
let fsIn = new FileStream(inFile, FileMode.Open)
let cs = new CryptoStream(fsIn, decryptor, CryptoStreamMode.Read)
let (buf : byte[]) = Array.zeroCreate (int fsIn.Length)
cs.Read(buf, 0, buf.Length)
File.WriteAllBytes(outFile, buf)
encrypt "1234512345678976" @"D:\file.txt" @"D:\file.txt.enc"
decrypt "1234512345678976" @"D:\file.txt.enc" @"D:\file.dec.txt"