试试吧
[C#] 纯文本查看 复制代码 using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Modes;
using Org.BouncyCastle.Crypto.Paddings;
using Org.BouncyCastle.Crypto.Parameters;
using System;
using System.Text;
public class Program
{
static void Main(string[] args)
{
byte[] key = Encoding.UTF8.GetBytes("0123456789abcdef");
byte[] iv = Encoding.UTF8.GetBytes("fedcba9876543210");
string plaintext = "Hello, world!";
byte[] ciphertext = EncryptCBC(Encoding.UTF8.GetBytes(plaintext), key, iv);
string ciphertextString = Convert.ToBase64String(ciphertext);
Console.WriteLine("Ciphertext: " + ciphertextString);
byte[] decrypted = DecryptCBC(ciphertext, key, iv);
string decryptedString = Encoding.UTF8.GetString(decrypted);
Console.WriteLine("Decrypted: " + decryptedString);
}
public static byte[] EncryptCBC(byte[] plaintext, byte[] key, byte[] iv)
{
IBlockCipher cipher = new AesFastEngine();
cipher = new CbcBlockCipher(cipher);
cipher = new PaddedBufferedBlockCipher(cipher);
cipher.Init(true, new ParametersWithIV(new KeyParameter(key), iv));
byte[] output = new byte[cipher.GetOutputSize(plaintext.Length)];
int bytesProcessed = cipher.ProcessBytes(plaintext, 0, plaintext.Length, output, 0);
cipher.DoFinal(output, bytesProcessed);
return output;
}
public static byte[] DecryptCBC(byte[] ciphertext, byte[] key, byte[] iv)
{
IBlockCipher cipher = new AesFastEngine();
cipher = new CbcBlockCipher(cipher);
cipher = new PaddedBufferedBlockCipher(cipher);
cipher.Init(false, new ParametersWithIV(new KeyParameter(key), iv));
byte[] output = new byte[cipher.GetOutputSize(ciphertext.Length)];
int bytesProcessed = cipher.ProcessBytes(ciphertext, 0, ciphertext.Length, output, 0);
cipher.DoFinal(output, bytesProcessed);
return output;
}
}
|