文档在.net充气城堡AES 256加密? [英] Documentation for Bouncy Castle AES 256 encryption in .Net?
本文介绍了文档在.net充气城堡AES 256加密?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想实现一个.NET项目的充气城堡加密库,但我没有找到很多.Net的相关文档。类/方法结构甚至还没有接近到足够的与Java相关的例子。
有没有人有一些很好的.Net例子吗?
感谢。
解决方案
使用系统;
使用System.Collections.Generic;
使用System.Linq的;
使用System.Text;
使用System.IO;
使用Org.BouncyCastle.Crypto;
使用Org.BouncyCastle.Crypto.Engines;
使用Org.BouncyCastle.Crypto.Generators;
使用Org.BouncyCastle.Crypto.Modes;
使用Org.BouncyCastle.Crypto.Paddings;
使用Org.BouncyCastle.Crypto.Parameters;
使用Org.BouncyCastle.Security;
使用Org.BouncyCastle.Utilities.En codeRS;
命名空间BouncyCastleProject
{
公共类DesExample
{
//加密或解密?
私人布尔加密= TRUE;
//要保持初始化DESede密码
私人PaddedBufferedBlockCipher密码= NULL;
//字节的输入流进行加密处理
专用流INSTR = NULL;
//字节的输出流进行procssed
专用流outStr = NULL;
// 钥匙
私人字节[]键= NULL;
/ *
*启动应用程序
* /
//////公共静态无效的主要(字串[] args)
////// {
//////布尔加密= TRUE;
//////字符串INFILE = NULL;
//////字符串OUTFILE = NULL;
//////字符串密钥文件= NULL;
//////如果(args.Length 2)
////// {
////// // Console.Error.WriteLine(用法:java的+ typeof运算(DesExample).Name点+INFILE OUTFILE [密钥文件]);
////// Console.Error.WriteLine(用法:+ typeof运算(DesExample).Name点+INFILE OUTFILE [密钥文件]);
////// Environment.Exit(1);
//////}
//////密钥文件=deskey.dat;
////// INFILE =的args [0];
////// OUTFILE =的args [1];
//////如果(args.Length→2)
////// {
//////加密= FALSE;
//////密钥文件=的args [2];
//////}
////// DesExample德=新DesExample(INFILE,OUTFILE,密钥文件,加密);
////// de.process();
//////}
//默认构造函数,用于使用信息
公共DesExample()
{
}
/ *
*构造,这需要合适的参数
*处理命令行指令。
* /
公共DesExample(
串INFILE,
串OUTFILE,
字符串密钥文件,
布尔加密)
{
/ *
*首先,确定INFILE和放大器;密钥文件存在合适的。
*
*根据需要这也将创造的BufferedInputStream
*用于读取输入文件。所有输入文件处理
*好像他们是二进制的,即使它们包含文本,它是
*已加密字节。
* /
this.encrypt =加密;
尝试
{
INSTR = File.OpenRead(INFILE);
}
赶上(FileNotFoundException异常)
{
//Console.Error.WriteLine("Input文件未找到[+ INFILE +]);
Environment.Exit(1);
}
尝试
{
outStr = File.Create(OUTFILE);
}
赶上(IOException异常)
{
//Console.Error.WriteLine("Output文件未创建[+ OUTFILE +]);
Environment.Exit(1);
}
如果(加密)
{
尝试
{
/ *
*创建一个新的密钥的过程需要
*的步数。
*
*首先,创建参数密钥生成器
*这是一个安全随机数生成器,和
*的密钥的长度(位)。
* /
SecureRandom的SR =新的SecureRandom();
KeyGenerationParameters KGP =新KeyGenerationParameters(
SR,
DesEdeParameters.DesEdeKeyLength * 8);
/ *
*第二,初始化用参数的密钥生成
* /
DesEdeKeyGenerator公斤=新DesEdeKeyGenerator();
kg.Init(KGP);
/ *
*第三,最后,生成密钥
* /
键= kg.GenerateKey();
/ *
*我们现在可以输出的关键文件,但第一
*六角恩code键,以便我们可以看看
*它使用文本编辑器,如果我们愿意的话
* /
流密钥流= File.Create(密钥文件);
byte []的keyhex = Hex.En code(键);
keystream.Write(keyhex,0,keyhex.Length);
keystream.Flush();
keystream.Close();
}
赶上(IOException异常)
{
//Console.Error.WriteLine("Could不译码创建密钥文件[+密钥文件+]);
Environment.Exit(1);
}
}
其他
{
尝试
{
// TODO此块是有些冒险
//读取密钥,并从十六进制编码德code
流密钥流= File.OpenRead(密钥文件);
// INT的len = keystream.available();
INT LEN =(INT)keystream.Length;
byte []的keyhex =新的字节[长度];
keystream.Read(keyhex,0,的len);
键= Hex.De code(keyhex);
}
赶上(IOException异常)
{
//Console.Error.WriteLine("Decryption密钥文件找不到,或者无效[+密钥文件+]);
Environment.Exit(1);
}
}
}
公共无效过程()
{
/ *
*设置的DESede加密引擎,创建PaddedBufferedBlockCipher
* CBC模式。
* /
密码=新PaddedBufferedBlockCipher(
新函数CBCBlockCipher(新DesEdeEngine()));
/ *
*的输入和输出流当前设置
*适当,关键的字节已经准备好要
*使用。
*
* /
如果(加密)
{
performEncrypt(键);
}
其他
{
performDecrypt(键);
}
//处理清理后的文件
尝试
{
inStr.Close();
outStr.Flush();
outStr.Close();
}
赶上(IOException异常)
{
}
}
/ *
*此方法执行所有的加密和写入
*密文到所创建的缓冲输出流
* previously。
* /
私人无效performEncrypt(字节[]键)
{
//初始化与密钥字节的密码,用于加密
cipher.Init(真正的,新的KeyParameter的(键));
/ *
*在使用创建一些临时性的字节数组
*加密,使他们一个合理的规模,使
*我们不会花永远读取小块
* 一份文件。
*
*有使用getBlockSize没有特别的原因()
*以确定输入块的大小。它只是
*是一个方便的号码为示例。
* /
// INT inBlockSize = cipher.getBlockSize()* 5;
INT inBlockSize = 47;
INT outBlockSize = cipher.GetOutputSize(inBlockSize);
byte []的inblock =新的字节[inBlockSize]
byte []的outblock =新的字节[outBlockSize]
/ *
*现在,阅读文件,并输出块
* /
尝试
{
诠释INL;
INT OUTL;
byte []的RV = NULL;
而((INL = inStr.Read(inblock,0,inBlockSize))大于0)
{
OUTL = cipher.ProcessBytes(inblock,0,INL,outblock,0);
/ *
*在我们写东西的时候,我们需要确保
*我们已经得到的东西写出来。
* /
如果(OUTL大于0)
{
RV = Hex.En code(outblock,0,OUTL);
outStr.Write(RV,0,rv.Length);
outStr.WriteByte((字节)'\ N');
}
}
尝试
{
/ *
*现在,过程字节仍在缓冲
*密码之内。
* /
OUTL = cipher.DoFinal(outblock,0);
如果(OUTL大于0)
{
RV = Hex.En code(outblock,0,OUTL);
outStr.Write(RV,0,rv.Length);
outStr.WriteByte((字节)'\ N');
}
}
赶上(CryptoException)
{
}
}
赶上(IOException异常ioeread)
{
// Console.Error.WriteLine(ioeread.StackTrace);
}
}
/ *
*此方法执行所有的解密和写入
*纯文本来创建的缓冲输出流
* previously。
* /
私人无效performDecrypt(字节[]键)
{
//初始化密码进行解密
cipher.Init(假,新的KeyParameter的(键));
/ *
*由于解密是从我们的preformatted文件,
*我们知道这是一个十六进制的连接codeD格式,然后
*我们换用一个BufferedReader InputStream的
*让我们可以轻松地阅读它。
* /
//的BufferedReader BR =新的BufferedReader(新的StreamReader(INSTR));
StreamReader的BR =新的StreamReader(INSTR); //'INSTR'已经缓冲
/ *
*现在,阅读文件,并输出块
* /
尝试
{
INT OUTL;
byte []的inblock = NULL;
byte []的outblock = NULL;
字符串RV = NULL;
而((RV = br.ReadLine())!= NULL)
{
inblock = Hex.De code(RV);
outblock =新的字节[cipher.GetOutputSize(inblock.Length)];
OUTL = cipher.ProcessBytes(inblock,0,inblock.Length,outblock,0);
/ *
*在我们写东西的时候,我们需要确保
*我们已经得到的东西写出来。
* /
如果(OUTL大于0)
{
outStr.Write(outblock,0,OUTL);
}
}
尝试
{
/ *
*现在,过程字节仍在缓冲
*密码之内。
* /
OUTL = cipher.DoFinal(outblock,0);
如果(OUTL大于0)
{
outStr.Write(outblock,0,OUTL);
}
}
赶上(CryptoException)
{
}
}
赶上(IOException异常ioeread)
{
//Console.Error.WriteLine(ioeread.StackTrace);
}
}
}
}
I'm trying to implement the Bouncy Castle encryption library in a .Net project, but am not finding a lot of .Net-related documentation. The class/method structure isn't even close to the ample Java-related examples.
Does anyone have some good .Net examples for this?
Thanks.
解决方案
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Modes;
using Org.BouncyCastle.Crypto.Paddings;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities.Encoders;
namespace BouncyCastleProject
{
public class DesExample
{
// Encrypting or decrypting ?
private bool encrypt = true;
// To hold the initialised DESede cipher
private PaddedBufferedBlockCipher cipher = null;
// The input stream of bytes to be processed for encryption
private Stream inStr = null;
// The output stream of bytes to be procssed
private Stream outStr = null;
// The key
private byte[] key = null;
/*
* start the application
*/
//////public static void Main(string[] args)
//////{
////// bool encrypt = true;
////// string infile = null;
////// string outfile = null;
////// string keyfile = null;
////// if (args.Length < 2)
////// {
////// // Console.Error.WriteLine("Usage: java " + typeof(DesExample).Name + " infile outfile [keyfile]");
////// Console.Error.WriteLine("Usage: " + typeof(DesExample).Name + " infile outfile [keyfile]");
////// Environment.Exit(1);
////// }
////// keyfile = "deskey.dat";
////// infile = args[0];
////// outfile = args[1];
////// if (args.Length > 2)
////// {
////// encrypt = false;
////// keyfile = args[2];
////// }
////// DesExample de = new DesExample(infile, outfile, keyfile, encrypt);
////// de.process();
//////}
// Default constructor, used for the usage message
public DesExample()
{
}
/*
* Constructor, that takes the arguments appropriate for
* processing the command line directives.
*/
public DesExample(
string infile,
string outfile,
string keyfile,
bool encrypt)
{
/*
* First, determine that infile & keyfile exist as appropriate.
*
* This will also create the BufferedInputStream as required
* for reading the input file. All input files are treated
* as if they are binary, even if they contain text, it's the
* bytes that are encrypted.
*/
this.encrypt = encrypt;
try
{
inStr = File.OpenRead(infile);
}
catch (FileNotFoundException)
{
//Console.Error.WriteLine("Input file not found [" + infile + "]");
Environment.Exit(1);
}
try
{
outStr = File.Create(outfile);
}
catch (IOException)
{
//Console.Error.WriteLine("Output file not created [" + outfile + "]");
Environment.Exit(1);
}
if (encrypt)
{
try
{
/*
* The process of creating a new key requires a
* number of steps.
*
* First, create the parameters for the key generator
* which are a secure random number generator, and
* the length of the key (in bits).
*/
SecureRandom sr = new SecureRandom();
KeyGenerationParameters kgp = new KeyGenerationParameters(
sr,
DesEdeParameters.DesEdeKeyLength * 8);
/*
* Second, initialise the key generator with the parameters
*/
DesEdeKeyGenerator kg = new DesEdeKeyGenerator();
kg.Init(kgp);
/*
* Third, and finally, generate the key
*/
key = kg.GenerateKey();
/*
* We can now output the key to the file, but first
* hex Encode the key so that we can have a look
* at it with a text editor if we so desire
*/
Stream keystream = File.Create(keyfile);
byte[] keyhex = Hex.Encode(key);
keystream.Write(keyhex, 0, keyhex.Length);
keystream.Flush();
keystream.Close();
}
catch (IOException)
{
//Console.Error.WriteLine("Could not decryption create key file [" + keyfile + "]");
Environment.Exit(1);
}
}
else
{
try
{
// TODO This block is a bit dodgy
// read the key, and Decode from hex encoding
Stream keystream = File.OpenRead(keyfile);
// int len = keystream.available();
int len = (int)keystream.Length;
byte[] keyhex = new byte[len];
keystream.Read(keyhex, 0, len);
key = Hex.Decode(keyhex);
}
catch (IOException)
{
//Console.Error.WriteLine("Decryption key file not found, or not valid [" + keyfile + "]");
Environment.Exit(1);
}
}
}
public void process()
{
/*
* Setup the DESede cipher engine, create a PaddedBufferedBlockCipher
* in CBC mode.
*/
cipher = new PaddedBufferedBlockCipher(
new CbcBlockCipher(new DesEdeEngine()));
/*
* The input and output streams are currently set up
* appropriately, and the key bytes are ready to be
* used.
*
*/
if (encrypt)
{
performEncrypt(key);
}
else
{
performDecrypt(key);
}
// after processing clean up the files
try
{
inStr.Close();
outStr.Flush();
outStr.Close();
}
catch (IOException)
{
}
}
/*
* This method performs all the encryption and writes
* the cipher text to the buffered output stream created
* previously.
*/
private void performEncrypt(byte[] key)
{
// initialise the cipher with the key bytes, for encryption
cipher.Init(true, new KeyParameter(key));
/*
* Create some temporary byte arrays for use in
* encryption, make them a reasonable size so that
* we don't spend forever reading small chunks from
* a file.
*
* There is no particular reason for using getBlockSize()
* to determine the size of the input chunk. It just
* was a convenient number for the example.
*/
// int inBlockSize = cipher.getBlockSize() * 5;
int inBlockSize = 47;
int outBlockSize = cipher.GetOutputSize(inBlockSize);
byte[] inblock = new byte[inBlockSize];
byte[] outblock = new byte[outBlockSize];
/*
* now, read the file, and output the chunks
*/
try
{
int inL;
int outL;
byte[] rv = null;
while ((inL = inStr.Read(inblock, 0, inBlockSize)) > 0)
{
outL = cipher.ProcessBytes(inblock, 0, inL, outblock, 0);
/*
* Before we write anything out, we need to make sure
* that we've got something to write out.
*/
if (outL > 0)
{
rv = Hex.Encode(outblock, 0, outL);
outStr.Write(rv, 0, rv.Length);
outStr.WriteByte((byte)'\n');
}
}
try
{
/*
* Now, process the bytes that are still buffered
* within the cipher.
*/
outL = cipher.DoFinal(outblock, 0);
if (outL > 0)
{
rv = Hex.Encode(outblock, 0, outL);
outStr.Write(rv, 0, rv.Length);
outStr.WriteByte((byte)'\n');
}
}
catch (CryptoException)
{
}
}
catch (IOException ioeread)
{
// Console.Error.WriteLine(ioeread.StackTrace);
}
}
/*
* This method performs all the decryption and writes
* the plain text to the buffered output stream created
* previously.
*/
private void performDecrypt(byte[] key)
{
// initialise the cipher for decryption
cipher.Init(false, new KeyParameter(key));
/*
* As the decryption is from our preformatted file,
* and we know that it's a hex encoded format, then
* we wrap the InputStream with a BufferedReader
* so that we can read it easily.
*/
// BufferedReader br = new BufferedReader(new StreamReader(inStr));
StreamReader br = new StreamReader(inStr); // 'inStr' already buffered
/*
* now, read the file, and output the chunks
*/
try
{
int outL;
byte[] inblock = null;
byte[] outblock = null;
string rv = null;
while ((rv = br.ReadLine()) != null)
{
inblock = Hex.Decode(rv);
outblock = new byte[cipher.GetOutputSize(inblock.Length)];
outL = cipher.ProcessBytes(inblock, 0, inblock.Length, outblock, 0);
/*
* Before we write anything out, we need to make sure
* that we've got something to write out.
*/
if (outL > 0)
{
outStr.Write(outblock, 0, outL);
}
}
try
{
/*
* Now, process the bytes that are still buffered
* within the cipher.
*/
outL = cipher.DoFinal(outblock, 0);
if (outL > 0)
{
outStr.Write(outblock, 0, outL);
}
}
catch (CryptoException)
{
}
}
catch (IOException ioeread)
{
//Console.Error.WriteLine(ioeread.StackTrace);
}
}
}
}
这篇关于文档在.net充气城堡AES 256加密?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文