本文整理汇总了C#中System.Security.Cryptography.MD5CryptoServiceProvider.TransformBlock方法的典型用法代码示例。如果您正苦于以下问题:C# MD5CryptoServiceProvider.TransformBlock方法的具体用法?C# MD5CryptoServiceProvider.TransformBlock怎么用?C# MD5CryptoServiceProvider.TransformBlock使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Security.Cryptography.MD5CryptoServiceProvider
的用法示例。
在下文中一共展示了MD5CryptoServiceProvider.TransformBlock方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Hash
public override byte[] Hash(byte[] data, byte[] salt, int version, int iterations = 1000, int outputLength = 64)
{
var crypto = new MD5CryptoServiceProvider();
var output = new byte[outputLength];
crypto.TransformBlock(data, 0, data.Length, output, 0);
salt.CopyTo(output, output.Length - salt.Length);
return output;
}
示例2: CalcHash
public void CalcHash()
{
using (var hash = new MD5CryptoServiceProvider()) {
foreach (var xt in mXmitTaskList) {
hash.TransformBlock(xt.xmitData, 0, xt.xmitData.Length, xt.xmitData, 0);
}
hash.TransformFinalBlock(new byte[0], 0, 0);
mXmitDataHash = hash.Hash;
}
}
示例3: CalcHash
public byte[] CalcHash()
{
mRecvFragmentList = mRecvFragmentList.OrderBy(o => o.StartPos).ToList();
using (var hash = new MD5CryptoServiceProvider()) {
foreach (var f in mRecvFragmentList) {
hash.TransformBlock(f.Content, 0, f.Content.Length, f.Content, 0);
}
hash.TransformFinalBlock(new byte[0], 0, 0);
byte[] result = new byte[HASH_BYTES];
Array.Copy(hash.Hash, result, HASH_BYTES);
return result;
}
}
示例4: MD5File
/// <summary>
/// ���ļ�����MD5����
/// </summary>
/// <param name="filePath"></param>
public static void MD5File(string filePath)
{
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
int bufferSize = 1048576; // ����������1MB
byte[] buff = new byte[bufferSize];
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
md5.Initialize();
long offset = 0;
while (offset < fs.Length)
{
long readSize = bufferSize;
if (offset + readSize > fs.Length)
{
readSize = fs.Length - offset;
}
fs.Read(buff, 0, Convert.ToInt32(readSize)); // ��ȡһ�����ݵ�������
if (offset + readSize < fs.Length) // �������һ��
{
md5.TransformBlock(buff, 0, Convert.ToInt32(readSize), buff, 0);
}
else // ���һ��
{
md5.TransformFinalBlock(buff, 0, Convert.ToInt32(readSize));
}
offset += bufferSize;
}
fs.Close();
byte[] result = md5.Hash;
md5.Clear();
StringBuilder sb = new StringBuilder(32);
for (int i = 0; i < result.Length; i++)
{
sb.Append(result[i].ToString("X2"));
}
Console.WriteLine(sb.ToString());
Console.ReadLine();
}
示例5: encodePapPassword
public static byte[] encodePapPassword(byte[] userPassBytes,byte[] requestAuthenticator,string sharedSecret)
{
if (userPassBytes.Length > 128)
throw new InvalidOperationException("the PAP password cannot be greater than 128 bytes...");
byte[] encryptedPass = null;
if (userPassBytes.Length % 16 == 0) {
encryptedPass = new byte[userPassBytes.Length];
} else {
encryptedPass = new byte[((userPassBytes.Length / 16) * 16) + 16];
}
System.Array.Copy(userPassBytes, 0, encryptedPass, 0, userPassBytes.Length);
for(int i = userPassBytes.Length; i < encryptedPass.Length; i++) {
encryptedPass[i] = 0;
}
byte[] sharedSecretBytes = System.Text.Encoding.ASCII.GetBytes(sharedSecret);
System.Security.Cryptography.MD5 md5;
for (int chunk = 0; chunk < (encryptedPass.Length / 16); chunk++)
{
md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
md5.TransformBlock(sharedSecretBytes, 0, sharedSecretBytes.Length, sharedSecretBytes, 0);
if (chunk == 0)
md5.TransformFinalBlock(requestAuthenticator, 0, requestAuthenticator.Length);
else
md5.TransformFinalBlock(encryptedPass, (chunk - 1) * 16, 16);
byte[] hash = md5.Hash;
for (int i = 0; i < 16; i++){
int j = i + chunk*16;
encryptedPass[j] = (byte) (hash[i] ^ encryptedPass[j]);
}
}
return encryptedPass;
}
示例6: GetFileMd5
/// <summary>
/// 获取文件的MD5值
/// </summary>
/// <param name="fileName"> 文件名 </param>
/// <returns> 32位MD5 </returns>
public static string GetFileMd5(string fileName)
{
FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
const int bufferSize = 1024 * 1024;
byte[] buffer = new byte[bufferSize];
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
md5.Initialize();
long offset = 0;
while (offset < fs.Length)
{
long readSize = bufferSize;
if (offset + readSize > fs.Length)
{
readSize = fs.Length - offset;
}
fs.Read(buffer, 0, (int)readSize);
if (offset + readSize < fs.Length)
{
md5.TransformBlock(buffer, 0, (int)readSize, buffer, 0);
}
else
{
md5.TransformFinalBlock(buffer, 0, (int)readSize);
}
offset += bufferSize;
}
fs.Close();
byte[] result = md5.Hash;
md5.Clear();
StringBuilder sb = new StringBuilder(32);
foreach (byte b in result)
{
sb.Append(b.ToString("X2"));
}
return sb.ToString();
}
示例7: InitializeCipherSuite
public static CipherSuite InitializeCipherSuite(byte[] master, byte[] clientrnd, byte[] serverrnd, CipherDefinition definition, ConnectionEnd entity)
{
CipherSuite ret = new CipherSuite();
SymmetricAlgorithm bulk = (SymmetricAlgorithm)Activator.CreateInstance(definition.BulkCipherAlgorithm);
if (definition.BulkIVSize > 0)
bulk.Mode = CipherMode.CBC;
bulk.Padding = PaddingMode.None;
bulk.BlockSize = definition.BulkIVSize * 8;
// get the keys and IVs
byte[] client_mac, server_mac, client_key, server_key, client_iv, server_iv;
Ssl3DeriveBytes prf = new Ssl3DeriveBytes(master, clientrnd, serverrnd, false);
client_mac = prf.GetBytes(definition.HashSize);
server_mac = prf.GetBytes(definition.HashSize);
client_key = prf.GetBytes(definition.BulkKeySize);
server_key = prf.GetBytes(definition.BulkKeySize);
client_iv = prf.GetBytes(definition.BulkIVSize);
server_iv = prf.GetBytes(definition.BulkIVSize);
prf.Dispose();
if (definition.Exportable) { // make some extra modifications if the keys are exportable
MD5 md5 = new MD5CryptoServiceProvider();
md5.TransformBlock(client_key, 0, client_key.Length, client_key, 0);
md5.TransformBlock(clientrnd, 0, clientrnd.Length, clientrnd, 0);
md5.TransformFinalBlock(serverrnd, 0, serverrnd.Length);
client_key = new byte[definition.BulkExpandedSize];
Buffer.BlockCopy(md5.Hash, 0, client_key, 0, client_key.Length);
md5.Initialize();
md5.TransformBlock(server_key, 0, server_key.Length, server_key, 0);
md5.TransformBlock(serverrnd, 0, serverrnd.Length, serverrnd, 0);
md5.TransformFinalBlock(clientrnd, 0, clientrnd.Length);
server_key = new byte[definition.BulkExpandedSize];
Buffer.BlockCopy(md5.Hash, 0, server_key, 0, server_key.Length);
md5.Initialize();
md5.TransformBlock(clientrnd, 0, clientrnd.Length, clientrnd, 0);
md5.TransformFinalBlock(serverrnd, 0, serverrnd.Length);
client_iv = new byte[definition.BulkIVSize];
Buffer.BlockCopy(md5.Hash, 0, client_iv, 0, client_iv.Length);
md5.Initialize();
md5.TransformBlock(serverrnd, 0, serverrnd.Length, serverrnd, 0);
md5.TransformFinalBlock(clientrnd, 0, clientrnd.Length);
server_iv = new byte[definition.BulkIVSize];
Buffer.BlockCopy(md5.Hash, 0, server_iv, 0, server_iv.Length);
md5.Clear();
}
// generate the cipher objects
if (entity == ConnectionEnd.Client) {
ret.Encryptor = bulk.CreateEncryptor(client_key, client_iv);
ret.Decryptor = bulk.CreateDecryptor(server_key, server_iv);
ret.LocalHasher = new Ssl3RecordMAC(definition.HashAlgorithmType, client_mac);
ret.RemoteHasher = new Ssl3RecordMAC(definition.HashAlgorithmType, server_mac);
} else {
ret.Encryptor = bulk.CreateEncryptor(server_key, server_iv);
ret.Decryptor = bulk.CreateDecryptor(client_key, client_iv);
ret.LocalHasher = new Ssl3RecordMAC(definition.HashAlgorithmType, server_mac);
ret.RemoteHasher = new Ssl3RecordMAC(definition.HashAlgorithmType, client_mac);
}
// clear sensitive data
Array.Clear(client_mac, 0, client_mac.Length);
Array.Clear(server_mac, 0, server_mac.Length);
Array.Clear(client_key, 0, client_key.Length);
Array.Clear(server_key, 0, server_key.Length);
Array.Clear(client_iv, 0, client_iv.Length);
Array.Clear(server_iv, 0, server_iv.Length);
return ret;
}
示例8: GenerateStaticContent
private void GenerateStaticContent ()
{
resources.Clear ();
var random = new Random ();
var root = "/tmp/hyena-download-test-server";
try {
Directory.Delete (root, true);
} catch {
}
Directory.CreateDirectory (root);
for (int i = 0; i < ResourceCount; i++) {
var md5 = new MD5CryptoServiceProvider ();
var resource = new Resource () {
Path = Path.Combine (root, i.ToString ()),
Length = random.Next (MinResourceSize, MaxResourceSize + 1)
};
if (Debug) Console.WriteLine ();
using (var stream = File.OpenWrite (resource.Path)) {
var buffer = new byte[32 << 10];
long written = 0;
long remaining;
while ((remaining = resource.Length - written) > 0) {
var buffer_length = remaining > buffer.Length
? (int)buffer.Length
: (int)remaining;
random.NextBytes (buffer);
stream.Write (buffer, 0, buffer_length);
written += buffer_length;
md5.TransformBlock (buffer, 0, buffer_length, null, 0);
if (Debug) Console.Write ("\rCreating resource: {0} ({1:0.00} MB): [{2}/{3}] {4:0.0}% ",
resource.Path, resource.Length / 1024.0 / 1024.0,
i + 1, ResourceCount,
written / (double)resource.Length * 100.0);
}
md5.TransformFinalBlock (buffer, 0, 0);
resource.Checksum = BitConverter.ToString (md5.Hash).Replace ("-", String.Empty).ToLower ();
}
resources.Add (resource);
}
}
示例9: GenMD5
/// <summary>
/// 生成某个文件的MD5
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
private string GenMD5(string fileName)
{
FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
int bufferSize = 1048576; // 缓冲区大小,1MB
byte[] buff = new byte[bufferSize];
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
md5.Initialize();
long offset = 0;
while (offset < fs.Length)
{
long readSize = bufferSize;
if (offset + readSize > fs.Length)
{
readSize = fs.Length - offset;
}
fs.Read(buff, 0, Convert.ToInt32(readSize)); // 读取一段数据到缓冲区
if (offset + readSize < fs.Length) // 不是最后一块
{
md5.TransformBlock(buff, 0, Convert.ToInt32(readSize), buff, 0);
}
else // 最后一块
{
md5.TransformFinalBlock(buff, 0, Convert.ToInt32(readSize));
}
offset += bufferSize;
}
fs.Close();
byte[] result = md5.Hash;
md5.Clear();
StringBuilder sb = new StringBuilder(32);
for (int i = 0; i < result.Length; i++)
{
sb.Append(result[i].ToString("X2"));
}
return sb.ToString();
}
示例10: HashTimer
void HashTimer()
{
byte[] inArray1 = new byte[24];
byte[] inArray2 = new byte[30000*sizeof(double)];
int i;
for (i = 0; i < 24; i++)
inArray1[i] = (byte)(23 + i*2);
MemoryStream binStream = new MemoryStream(inArray2);
BinaryWriter binWriter = new BinaryWriter(binStream);
for (i = 0; i < 30000; i++)
binWriter.Write(i * (double)2.2);
DateTime timerStart = DateTime.Now;
for (i = 0; i < nIter; i++)
{
MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
md5Hasher.TransformBlock(inArray1, 0, inArray1.Length, inArray1, 0);
md5Hasher.TransformFinalBlock(inArray2, 0, inArray2.Length);
byte[] hash1 = md5Hasher.Hash;
}
DateTime timerEnd = DateTime.Now;
TimeSpan timerDiff = timerEnd - timerStart;
TimeLabelBlob.Content = String.Format("ChkSum --- Iterations: {0}; Duration: {1:hh\\:mm\\:ss\\.f}", i, timerDiff);
i = 3;
}
示例11: DoRSAChallengeResponse
//RSA authentication
private void DoRSAChallengeResponse()
{
//read key
SSH1UserAuthKey key = new SSH1UserAuthKey(_param.IdentityFile, _param.Password);
Transmit(
new SSH1Packet(SSH1PacketType.SSH_CMSG_AUTH_RSA)
.WriteBigInteger(key.PublicModulus)
);
TraceTransmissionEvent(SSH1PacketType.SSH_CMSG_AUTH_RSA, "RSA challenge-reponse");
DataFragment response = ReceivePacket();
SSH1DataReader reader = new SSH1DataReader(response);
SSH1PacketType pt = (SSH1PacketType) reader.ReadByte();
if (pt == SSH1PacketType.SSH_SMSG_FAILURE)
throw new SSHException(Strings.GetString("ServerRefusedRSA"));
else if (pt != SSH1PacketType.SSH_SMSG_AUTH_RSA_CHALLENGE)
throw new SSHException(String.Format(Strings.GetString("UnexpectedResponse"), pt));
TraceReceptionEvent(SSH1PacketType.SSH_SMSG_AUTH_RSA_CHALLENGE, "received challenge");
//creating challenge
BigInteger challenge = key.decryptChallenge(reader.ReadMPInt());
byte[] rawchallenge = RSAUtil.StripPKCS1Pad(challenge, 2).GetBytes();
//building response
byte[] hash;
using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider()) {
md5.TransformBlock(rawchallenge, 0, rawchallenge.Length, rawchallenge, 0);
md5.TransformFinalBlock(_sessionID, 0, _sessionID.Length);
hash = md5.Hash;
}
Transmit(
new SSH1Packet(SSH1PacketType.SSH_CMSG_AUTH_RSA_RESPONSE)
.Write(hash)
);
TraceReceptionEvent(SSH1PacketType.SSH_CMSG_AUTH_RSA_RESPONSE, "received response");
}
示例12: ComputeMD5
public string ComputeMD5()
{
MD5 md5 = new MD5CryptoServiceProvider();
byte[] hash = null;
if (NumberOfFrames == 1) {
byte[] frame = GetFrameDataU8(0);
hash = md5.ComputeHash(frame);
} else {
for (int i = 0; i < NumberOfFrames; i++) {
byte[] frame = GetFrameDataU8(i);
if (i < (NumberOfFrames - 1))
md5.TransformBlock(frame, 0, frame.Length, frame, 0);
else
md5.TransformFinalBlock(frame, 0, frame.Length);
}
hash = md5.Hash;
}
return BitConverter.ToString(hash).Replace("-", "");
}
示例13: CreateUploadMsg
/// <summary>
/// Create the next upload message.
/// </summary>
private void CreateUploadMsg(MD5CryptoServiceProvider md5Hasher, out AnpMsg m, out List<UInt64> CompletedArray)
{
m = Share.CreateTransferMsg(KAnpType.KANP_CMD_KFS_PHASE_2);
CompletedArray = new List<UInt64>();
// Add the number of submessages field. It will be updated later.
m.AddUInt32(0);
// Count the number of submessages.
int nbSub = 0;
// Loop until the message is full or we run out of files to upload.
while (m.PayloadSize() < MAX_UPLOAD_SIZE && UploadIndex != FileArray.Length)
{
KfsUploadBatchFile ubf = FileArray[UploadIndex];
// The transfer of the current file was denied by the
// server during phase 1. Do not attempt to talk about
// it in phase 2.
if (ubf.Status == BatchStatus.Error)
{
UploadNextFile();
continue;
}
// The transfer of the current file has been cancelled. Add an
// abort submessage and pass to the next file.
if (ubf.Status == BatchStatus.Cancelled)
{
m.AddUInt32(2);
m.AddUInt32(KAnpType.KANP_KFS_SUBMESSAGE_ABORT);
nbSub++;
UploadNextFile();
continue;
}
// The current file is closed. Open the file and set the
// remaining size.
if (UploadedFile == null)
{
Debug.Assert(ubf.Status == BatchStatus.Queued);
ubf.Status = BatchStatus.Started;
UploadedFile = new FileStream(ubf.TransferPath, FileMode.Open, FileAccess.Read, FileShare.Read);
RemainingSize = UploadedFile.Length;
md5Hasher.Initialize();
}
// Add a chunk submessage.
if (RemainingSize > 0)
{
Debug.Assert(ubf.Status == BatchStatus.Started);
// Compute the chunk size.
UInt32 chunkSize = Math.Max(MIN_UPLOAD_CHUNK_SIZE, MAX_UPLOAD_SIZE - m.PayloadSize());
chunkSize = (UInt32)Math.Min((Int64)chunkSize, RemainingSize);
RemainingSize -= chunkSize;
// Read the chunk.
byte[] chunkData = new byte[chunkSize];
UploadedFile.Read(chunkData, 0, (Int32)chunkSize);
// Update the hash.
md5Hasher.TransformBlock(chunkData, 0, (int)chunkSize, chunkData, 0);
// Add the chunk submessage.
m.AddUInt32(3);
m.AddUInt32(KAnpType.KANP_KFS_SUBMESSAGE_CHUNK);
m.AddBin(chunkData);
nbSub++;
}
// Add a commit submessage, remember that the transfer of the file
// is being completed in this message and pass to the next file.
if (RemainingSize == 0)
{
Debug.Assert(ubf.Status == BatchStatus.Started);
ubf.Status = BatchStatus.Done;
// Update the hash. This call is required; Microsoft sucks.
md5Hasher.TransformFinalBlock(new byte[0], 0, 0);
m.AddUInt32(3);
m.AddUInt32(KAnpType.KANP_KFS_SUBMESSAGE_COMMIT);
m.AddBin(md5Hasher.Hash);
nbSub++;
CompletedArray.Add(ubf.OrderID);
UploadNextFile();
}
}
// Update the number of submessages.
m.Elements[0].UInt32 = (UInt32)nbSub;
// If there are no submessages, don't bother sending the message.
if (nbSub == 0) m = null;
}
示例14: Encode
public byte[] Encode(byte[] data)
{
byte[] buffer = new byte[data.Length + 128];
using (MemoryStream stream = new MemoryStream(data))
{
int num;
MemoryStream stream2 = new MemoryStream(buffer);
RSACryptoServiceProvider key = new RSACryptoServiceProvider(1024);
byte[] buffer2 = new byte[86];
byte[] outputBuffer = new byte[86];
HashAlgorithm algorithm = new MD5CryptoServiceProvider();
algorithm.Initialize();
while ((num = stream.Read(buffer2, 0, 86)) == 86)
{
algorithm.TransformBlock(buffer2, 0, 86, outputBuffer, 0);
stream2.Write(buffer2, 0, buffer2.Length);
}
buffer2 = algorithm.TransformFinalBlock(buffer2, 0, num);
stream2.Write(buffer2, 0, buffer2.Length);
RSAParameters parameters = new RSAParameters();
parameters.D = (byte[])this.rsaParameters.D.Clone();
parameters.DP = (byte[])this.rsaParameters.DP.Clone();
parameters.DQ = (byte[])this.rsaParameters.DQ.Clone();
parameters.Exponent = (byte[])this.rsaParameters.Exponent.Clone();
parameters.InverseQ = (byte[])this.rsaParameters.InverseQ.Clone();
parameters.Modulus = (byte[])this.rsaParameters.Modulus.Clone();
parameters.P = (byte[])this.rsaParameters.P.Clone();
parameters.Q = (byte[])this.rsaParameters.Q.Clone();
key.ImportParameters(parameters);
AsymmetricSignatureFormatter formatter = new RSAPKCS1SignatureFormatter(key);
formatter.SetHashAlgorithm("MD5");
outputBuffer = formatter.CreateSignature(algorithm.Hash);
stream2.Write(outputBuffer, 0, outputBuffer.Length);
stream2.Close();
stream.Close();
}
return buffer;
}
示例15: SSH1IRSAChallenge
/// <summary>
/// SSH1 RSA challenge
/// </summary>
/// <param name="e">public exponent</param>
/// <param name="n">public modulus</param>
/// <param name="encryptedChallenge">encrypted challenge</param>
/// <param name="sessionId">session id</param>
/// <param name="responseType">response type</param>
private void SSH1IRSAChallenge(BigInteger e, BigInteger n, BigInteger encryptedChallenge, byte[] sessionId, uint responseType)
{
if (responseType != 1) {
SendFailure();
return;
}
SSH1UserAuthKey key = SSH1FindKey(e, n);
if (key == null) {
SendFailure();
return;
}
BigInteger challenge = key.decryptChallenge(encryptedChallenge);
byte[] rawchallenge = RSAUtil.StripPKCS1Pad(challenge, 2).GetBytes();
byte[] hash;
using (var md5 = new MD5CryptoServiceProvider()) {
md5.TransformBlock(rawchallenge, 0, rawchallenge.Length, rawchallenge, 0);
md5.TransformFinalBlock(sessionId, 0, sessionId.Length);
hash = md5.Hash;
}
Send(
new OpenSSHAgentForwardingMessage(OpenSSHAgentForwardingMessageType.SSH_AGENT_RSA_RESPONSE)
.Write(hash)
);
}