目录
从System.Security.Cryptography.ICryptoTransform派生的简单密码
从System.Security.Cryptography.ICryptoTransform派生的简单密码
这是用户定义的简单密码转换。
使用代码
这就是abstract类CryptoBlock的运作方式。它是用户定义CryptoBlock的Dictionary<byte, byte>,它的块大小必须为256,并且没有键值对可以匹配。
// This is the base CryptoBlock used for the CipherTransform class
using System.Collections.Generic;
namespace Chico.CipherCrypto>
{
public abstract class CryptoBlock : Dictionary<byte>,byte>
{
public const int BlockSize = 256;
protected CryptoBlock() : base(BlockSize)
{
}
}
}
在这里,我们将看看CipherTransform。此类基于ICryptoTransform并与CryptoStream一起使用。
using System;
using System.Linq;
using System.Diagnostics;
using System.Collections.Generic;
using System.Security.Cryptography;
namespace Chico.CipherCrypto
{
[DebuggerStepThrough]
public class CipherTransform : ICryptoTransform
{
private CryptoBlock cipher;
public CipherTransform(CryptoBlock cryptoBlock)
{
var cipher = typeof(CryptoBlock);
if (cryptoBlock == null)
{
throw new NotImplementedException(cipher + " can not be null.");
}
if (cryptoBlock.Count != CryptoBlock.BlockSize)
{
throw new NotSupportedException(cipher + "is not supported");
}
byte[] keys = cryptoBlock.Keys.ToArray();
byte[] values = cryptoBlock.Values.ToArray();
for (int i = 0; i < keys.Length; i++)
{
if (keys[i] == values[i])
{
throw new NotSupportedException(cipher + " is not supported.");
}
}
this.cipher = cryptoBlock;
}
public void Dispose() => this.cipher.Clear();
bool ICryptoTransform.CanReuseTransform => true;
bool ICryptoTransform.CanTransformMultipleBlocks => true;
int ICryptoTransform.InputBlockSize => CryptoBlock.BlockSize;
int ICryptoTransform.OutputBlockSize => CryptoBlock.BlockSize;
private void Cipher(byte[] buffer, int offset, int count)
{
for (int i = offset; i < count; i++)
{
byte current = buffer[i];
byte next = this.cipher[current];
buffer[i] = next;
}
}
public int TransformBlock(byte[] inputBuffer, int inputOffset,
int inputCount, byte[] outputBuffer, int outputOffset)
{
Array.Copy(inputBuffer, inputOffset, outputBuffer, outputOffset, inputCount);
Cipher(outputBuffer, outputOffset, inputCount);
return inputCount;
}
public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount)
{
byte[] outputBuffer = new byte[inputCount];
Array.Copy(inputBuffer, inputOffset, outputBuffer, 0, inputCount);
Cipher(outputBuffer, 0, inputCount);
return outputBuffer;
}
}
}
https://www.codeproject.com/Tips/5325293/A-Basic-Cipher-Transform