65.9K
CodeProject 正在变化。 阅读更多。
Home

关于 .NET 中的密码学

starIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIconemptyStarIcon

1.15/5 (7投票s)

2004 年 12 月 21 日

CPOL

5分钟阅读

viewsIcon

77593

.NET 中可用的密码学类。

引言

在阅读了 MSDN 和其他网站上的大量文章后,我无法一次性获得足够的信息。所以,我想写一篇涵盖所有密码学并附带示例的文章。

描述

.NET Framework 提供了以下实现密码学的类:

  • 密钥加密算法:私钥算法相对较快,可用于加密和解密大量数据流。私钥算法被称为块密码,因为它们一次加密一个数据块。块密码会根据算法和密钥将相同的输入块加密成相同的输出块。如果数据的结构已知,则可以检测到模式,并且密钥可能会被逆向工程。为了解决这个问题,.NET Framework 中的类使用了一种称为链接的过程,其中前一个块的信息用于加密当前块。这有助于防止密钥被发现。它要求提供一个初始化向量 (IV) 来加密第一个数据块。
    • DESCryptoServiceProvider - 数据加密标准 (DES) 算法使用 64 位密钥加密和解密 64 位数据块。尽管密钥是 64 位,但有效密钥强度只有 56 位。有一些足够先进的硬件设备可以在合理的时间内搜索所有可能的 DES 密钥。这使得 DES 算法可以被破解,并且该算法被认为有些过时。
    • RC2CryptoServiceProvider - RC2 是一种可变密钥大小的块密码。密钥大小可以从 8 位到 64 位不等。它被专门设计为 DES 的更安全的替代品。处理速度比 DES 快两到三倍。然而,.NET Framework 中可用的 RC2CryptoServiceProvider 仅限于 8 个字符或 64 位密钥。8 字符的限制使其容易受到与 DES 相同的暴力攻击。
    • RijndaelManaged - Rijndael 算法是高级加密标准 (AES) 算法之一,旨在替代 DES 算法。其密钥强度强于 DES,并且旨在超越 DES 的性能。密钥长度可以从 128、192 到 256 位不等。
    • TripleDESCryptoServiceProvider - TripleDES 算法使用 DES 算法的三次连续迭代。该算法使用两个或三个密钥。与 DES 算法一样,每个密钥的密钥大小为 64 位,每个密钥的有效密钥强度为 56 位。TripleDES 算法旨在弥补 DES 算法的不足,但三次迭代导致处理速度比单独的 DES 慢三倍。
    算法名称 算法类(抽象) 有效密钥大小(位) 默认密钥大小(位) 默认实现类
    DES DES 64 64 DESCryptoServiceProvider
    TripleDES TripleDES 128, 192 192 TripleDESCryptoServiceProvider
    RC2 RC2 40-128 128 RC2CryptoServiceProvider
    RijnDael RijnDael 128, 192, 256 256 RijnDaelManaged
  • 公钥加密算法:公钥加密具有更大的密钥空间(即密钥的可能值范围),因此不太容易受到尝试所有可能密钥的穷举攻击。公钥易于分发,因为它不必保密。公钥算法可用于创建数字签名,以验证数据发送者的身份。然而,公钥算法非常慢(与密钥算法相比),并且不适合加密大量数据。公钥算法仅适用于传输少量数据。通常,公钥加密用于加密将由密钥算法使用的密钥和 IV。在密钥和 IV 传输后,密钥加密用于会话的其余部分。
  • 数字签名算法 (哈希):.NET Framework 支持以下哈希算法。
    • HMACSHA1 - 如果发送方和接收方共享一个密钥,HMAC 可用于确定通过不安全通道发送的消息是否被篡改。发送方计算原始数据的 HMAC,并将原始数据和 HMAC 作为一条消息发送。接收方重新计算接收消息的 HMAC,并检查计算出的 HMAC 是否与传输的 HMAC 匹配。

      对数据或 HMAC 的任何更改都将导致不匹配,因为更改消息并重新生成正确的 HMAC 需要知道密钥。因此,如果代码匹配,则消息被认证。

      HMACSHA1 接受任何大小的密钥,并生成长度为 20 字节的哈希序列。

    • MACTripleDES - MAC 可用于确定通过不安全通道发送的消息是否已被篡改,前提是发送方和接收方共享一个密钥。发送方计算原始数据的 MAC,并将其作为单个消息发送。接收方重新计算接收消息的 MAC,并检查计算出的 MAC 是否与传输的 MAC 匹配。

      对数据或 MAC 的任何更改都会导致不匹配,因为更改消息并重新生成正确的 MAC 需要知道密钥。因此,如果代码匹配,则消息经过身份验证。

      MACTripleDES 使用长度为 8、16 或 24 字节的密钥,并生成长度为 8 字节的哈希序列。

    • MD5CryptoServiceProvider
    • SHA1Managed - 哈希用作代表大量数据的固定大小的唯一值。两组数据的哈希应该匹配,当且仅当相应数据也匹配时。数据的微小更改会导致哈希中出现大的、不可预测的更改。

      这是 SHA1 的纯托管实现,不包装 CAPI。

      SHA1Managed 算法的哈希大小为 160 位。

    • SHA256Managed - SHA256Managed 算法的哈希大小为 256 位。
    • SHA384Managed - SHA384Managed 算法的哈希大小为 384 位。

      这是一个抽象类。该类的唯一实现是 SHA384Managed

    • SHA512Managed - SHA512Managed 算法的哈希大小为 512 位。

到目前为止,我们已经学习了许多关于密码学和 .NET Framework 1.1 中提供的支持。现在我们来看一个文本加密/解密的例子。

以下是使用“Rijndael”算法进行加密的代码。这是一个用 C# 开发的类库。您可以将此代码作为插件,用于加密、解密和哈希。

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Diagnostics;

namespace JackTheGreat.Encryption.Cryptography
{
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Diagnostics;

namespace JackTheGreat.Encryption.Cryptography
{
  /// <summary>
  /// Summary description for EncryptData.
  /// </summary>
  public class CryptoLib
  {

    public System.Security.Cryptography.SymmetricAlgorithm mCryptProv;
    public System.Diagnostics.EventLog objEventLog;

    #region "Encrypt Function"
    public string Encrypt(string EncryptProvider, string EncryptStr, 
        int BlckSize, int KySize, string Key, string IV)
    {
      //Check if something Algo is Selected 
      if(EncryptProvider.Length<=0)
      {
        return("Pass an Algo to use to Encrypt.");
      }
    
      //Since, The selected algo may not be Symmetric, So Try it
      try
      {
        mCryptProv = SymmetricAlgorithm.Create(EncryptProvider);
        mCryptProv.Mode = CipherMode.CBC;
      }
      catch(Exception ee)
      {
        return("Exception : " + ee.Message);
      }
      try
      {
        //Each Algo has different Size of Key and Block, So let's try
        mCryptProv.BlockSize = BlckSize;
        mCryptProv.KeySize = KySize;
      }
      catch
      {
        //Invalid Block or Key Size. Show the Default Ones
        string mStr;
        mStr = mCryptProv.BlockSize.ToString();
        mStr += "Invalid Block or Key Size.Valid Sizes are : "; 
        mStr += "Block Size = " + 
             mCryptProv.LegalBlockSizes[0].MinSize.ToString() + 
             " - " + mCryptProv.LegalBlockSizes[0].MaxSize.ToString() + 
             " With Increment of " + 
             mCryptProv.LegalBlockSizes[0].SkipSize.ToString();
        mStr += "Key  Size = " + 
             mCryptProv.LegalKeySizes[0].MinSize.ToString() + 
             " - " + mCryptProv.LegalKeySizes[0].MaxSize.ToString() + 
             " With Increment of " + 
             mCryptProv.LegalKeySizes[0].SkipSize.ToString();
        return(mStr);
        //Show the Valid Block Size 
      }
      
      try
      {
        //Change the supplied key to a byte array
        byte[] thisKey = stringtoByte(Key,KySize);
        
        //Hash the Supplied Secret key
        byte[] resultKey = HashOfByteArray(thisKey);
        
        int loopTill=0;
        if(BlckSize==128)loopTill=16;
        if(BlckSize==192)loopTill=24;
        if(BlckSize==256)loopTill=32;

        byte[] BlockKey = new byte[loopTill];
        for(int loop=0; loop<loopTill; loop++ ) 
          BlockKey[loop] = resultKey[loop];


        //Change the supplied IV to a byte array
        byte[] thisIV = stringtoByte(IV,BlckSize);
        //Hash the Supplied IV

        byte[] resultIV = HashOfByteArray(thisIV);
        //byte[] resultIV = thisIV;

      
        byte[] BlockIV = new byte[loopTill];
        for( int loop=0; loop<loopTill; loop++ )
          BlockIV[loop] = resultIV[loop];

        //Create the Encryptor, Passing that the Key and IV
        
        ICryptoTransform mEncryptor = 
             mCryptProv.CreateEncryptor(BlockKey, BlockIV);
      
        //Create Memory Stream
        System.IO.MemoryStream mMemStr = new MemoryStream();

        //Create the Crypto Stream,
        // Passing that the Memory Stream and Encryptor
        CryptoStream mCryptStr= new CryptoStream(mMemStr, 
                 mEncryptor, CryptoStreamMode.Write);
      
        //Convert the Supplied plaintext into a byte array
        byte[] bInput = stringtoByte(EncryptStr,512);
        //System.Text.Encoding.UTF8.GetBytes(EncryptStr);
        //stringtoByte(EncryptStr,512);

        // write out encrypted content into MemoryStream 
        mCryptStr.Write(bInput, 0, bInput.Length); 
        mCryptStr.FlushFinalBlock(); 
        
        // get the output and trim the '\0' bytes 
        byte[] bOutput = mMemStr.GetBuffer(); 

        int MemLength = System.Convert.ToInt32(mMemStr.Length);
      
        //Clean up the memory
        mCryptStr.Close();
        mMemStr.Close();
        mEncryptor.Dispose();

        // convert into Base64 so that the result can be used in xml 
        
        return Convert.ToBase64String(bOutput,0,MemLength); 
      }
      catch(System.Security.Cryptography.CryptographicException ee)
      {
        objEventLog = new System.Diagnostics.EventLog();
        objEventLog.Source = "SMP-CryptoGraphy";
        objEventLog.WriteEntry("Exception Occured in Encryption Process." +
                  " Error is = " +
                  ee.Message ,System.Diagnostics.EventLogEntryType.Error);
        objEventLog.Dispose();
        return("");
      }
     }
    #endregion
  
    #region "Decrypt Function"
    public string Decrypt(string EncryptProvider, string EncryptStr, 
            int BlckSize, int KySize, string Key, string IV)
    {
      //Check if something Algo is Selected 
      if(EncryptProvider.Length<=0)
      {
        return("Pass an Algo to use to Encrypt.");
      }
    
      //Since, The selected algo may not be Symmetric, So Try it
      try
      {
        mCryptProv = SymmetricAlgorithm.Create(EncryptProvider);
        mCryptProv.Mode = CipherMode.CBC;
      }
      catch(Exception ee)
      {
        return("Exception-1: " + ee.Message);
      }
      try
      {
        //Each Algo has different Size of Key and Block, So let's try
        mCryptProv.BlockSize = BlckSize;
        mCryptProv.KeySize = KySize;
      }
      catch
      {
        //Invalid Block or Key Size. Show the Default Ones
        string mStr;
        mStr = mCryptProv.BlockSize.ToString();
        mStr += "Invalid Block or Key Size.Valid Sizes are : "; 
        mStr += "Block Size = " + 
              mCryptProv.LegalBlockSizes[0].MinSize.ToString() + 
              " - " + mCryptProv.LegalBlockSizes[0].MaxSize.ToString() + 
              " With Increment of " + 
              mCryptProv.LegalBlockSizes[0].SkipSize.ToString();
        mStr += "Key  Size = " + 
              mCryptProv.LegalKeySizes[0].MinSize.ToString() + 
              " - " + mCryptProv.LegalKeySizes[0].MaxSize.ToString() + 
              " With Increment of " + 
              mCryptProv.LegalKeySizes[0].SkipSize.ToString();
        return(mStr);
        //Show the Valid Block Size 
      }
      
      try
      {
        //Change the supplied key to a byte array
        byte[] thisKey = stringtoByte(Key,KySize);
        //Hash the Supplied Secret key

        byte[] resultKey = HashOfByteArray(thisKey);
        int loopTill=0;
        if(BlckSize==128)loopTill=16;
        if(BlckSize==192)loopTill=24;
        if(BlckSize==256)loopTill=32;

        byte[] BlockKey = new byte[loopTill];
        for(int loop=0; loop<loopTill; loop++ ) 
          BlockKey[loop] = resultKey[loop];

        //Change the supplied IV to a byte array
        byte[] thisIV = stringtoByte(IV,BlckSize);

        //Hash the Supplied IV
        byte[] resultIV = HashOfByteArray(thisIV);
      
        byte[] BlockIV = new byte[loopTill];
        for( int loop=0; loop<loopTill; loop++ )
          BlockIV[loop] = resultIV[loop];

        //Try to Decrypt values in the memory
        //First Create the Decryptor, By Passing Key and IV
        ICryptoTransform mDecrypt = 
            mCryptProv.CreateDecryptor(thisKey, thisIV);
          
        byte[] bInput = System.Convert.FromBase64String(EncryptStr); 
        
        // create a MemoryStream with the input 
        System.IO.MemoryStream ms = 
              new System.IO.MemoryStream(bInput, 0, bInput.Length); 

        //Create Crypto Stream
        CryptoStream mCSReader = 
              new CryptoStream(ms, mDecrypt, CryptoStreamMode.Read);

        // read out the result from the Crypto Stream 
        System.IO.StreamReader sr = new System.IO.StreamReader(mCSReader); 
      
        //Close the crypto stream
        mCSReader.Close();
        ms.Close();
        mDecrypt.Dispose();
        return sr.ReadToEnd(); 
      }
      catch(System.Exception ee)
      {
        return("Exception in processing " + ee.Message);
      }
    }
    #endregion

    #region "Hashing of a BYTE Array by using SHA512Managed -" +
            " return value is a Byte Array"
    private byte[] HashOfByteArray(byte[] ByteArray)
    {
      SHA512Managed sha512Key = new SHA512Managed();
      Sha512Key.ComputeHash(ByteArray);
      return(sha512Key.Hash);
    }
    #endregion
  
    #region "Hashing of a String by using SHA512Managed - " +
             "return value is a Base64 string"
    public string HashOfString(string PlainText)
    {
      //Change the supplied string to a byte array
      try
      {
        int thisSize = PlainText.Length*8;
        int temp;
        if(PlainText.Length<1)
        {
          return("Please enter a Valid String to Hash. String passed is " + 
                    PlainText.ToString());
          
        }
        byte[] thisStr = new byte[thisSize];
        int lastBound = PlainText.Length;
        if(lastBound > thisSize)lastBound = thisSize;
        for(temp = 0;temp<=lastBound - 1;temp++)
        {
          thisStr[temp] = Convert.ToByte(PlainText[temp]);
        }
      
        SHA512Managed sha512Key = new SHA512Managed();
        Sha512Key.ComputeHash(thisStr);
        return(Convert.ToBase64String(sha512Key.Hash));
      }
      catch(System.Security.Cryptography.CryptographicException ee)
      {
        return("Exception Occured in Hashing Process. Error is = " +
                ee.Message);
    
      }
    }
    #endregion
    
    #region "String to a byte array conversion -" +
          " return value is a BYTE array"
    private byte[] stringtoByte(string textdata,int keySize)
    {
      int thisSize = (keySize / 8);
      int temp;
      byte[] returnByteArray = new byte[thisSize];
      int lastBound = textdata.Length;
      if(lastBound > thisSize)lastBound = thisSize;
      for(temp = 0;temp<=lastBound - 1;temp++)
      {
        returnByteArray[temp] = Convert.ToByte(textdata[temp]);
      }
      return(returnByteArray);
    }
    #endregion
  }

}
/// <summary>
  /// Summary description for EncryptData.
  /// </summary>
  public class CryptoLib
  {

    public System.Security.Cryptography.SymmetricAlgorithm mCryptProv;
    public System.Diagnostics.EventLog objEventLog;

    #region "Encrypt Function"
    public string Encrypt(string EncryptProvider, string EncryptStr, 
         int BlckSize, int KySize, string Key, string IV)
    {
      //Check if something Algo is Selected 
      if(EncryptProvider.Length<=0)
      {
              return("Pass an Algo to use to Encrypt.");
      }
    
      //Since, The selected algo may not be Symmetric, So Try it
      try
      {
        mCryptProv = SymmetricAlgorithm.Create(EncryptProvider);
        mCryptProv.Mode = CipherMode.CBC;
      }
      catch(Exception ee)
      {
        return("Exception : " + ee.Message);
      }
      try
      {
        //Each Algo has different Size of Key and Block, So let's try
        mCryptProv.BlockSize = BlckSize;
        mCryptProv.KeySize = KySize;
      }
      catch
      {
        //Invalid Block or Key Size. Show the Default Ones
        string mStr;
        mStr = mCryptProv.BlockSize.ToString();
        mStr += "Invalid Block or Key Size.Valid Sizes are : "; 
        mStr += "Block Size = " + 
              mCryptProv.LegalBlockSizes[0].MinSize.ToString() + 
              " - " + mCryptProv.LegalBlockSizes[0].MaxSize.ToString() + 
              " With Increment of " + 
              mCryptProv.LegalBlockSizes[0].SkipSize.ToString();
        mStr += "Key  Size = " + 
              mCryptProv.LegalKeySizes[0].MinSize.ToString() + 
              " - " + mCryptProv.LegalKeySizes[0].MaxSize.ToString() + 
              " With Increment of " + 
              mCryptProv.LegalKeySizes[0].SkipSize.ToString();
        return(mStr);
        //Show the Valid Block Size 
      }
      
      try
      {
        //Change the supplied key to a byte array
        byte[] thisKey = stringtoByte(Key,KySize);
        
        //Hash the Supplied Secret key
        byte[] resultKey = HashOfByteArray(thisKey);
        
        int loopTill=0;
        if(BlckSize==128)loopTill=16;
        if(BlckSize==192)loopTill=24;
        if(BlckSize==256)loopTill=32;

        byte[] BlockKey = new byte[loopTill];
        for(int loop=0; loop<loopTill; loop++ ) 
          BlockKey[loop] = resultKey[loop];


        //Change the supplied IV to a byte array
        byte[] thisIV = stringtoByte(IV,BlckSize);
        //Hash the Supplied IV

        byte[] resultIV = HashOfByteArray(thisIV);
        //byte[] resultIV = thisIV;

      
        byte[] BlockIV = new byte[loopTill];
        for( int loop=0; loop<loopTill; loop++ )
          BlockIV[loop] = resultIV[loop];

        //Create the Encryptor, Passing that the Key and IV
        
        ICryptoTransform mEncryptor = 
             mCryptProv.CreateEncryptor(BlockKey, BlockIV);
      
        //Create Memory Stream
        System.IO.MemoryStream mMemStr = new MemoryStream();

        //Create the Crypto Stream, 
        //Passing that the Memory Stream and Encryptor
        CryptoStream mCryptStr= 
           new CryptoStream(mMemStr, mEncryptor, CryptoStreamMode.Write);
      
        //Convert the Supplied plaintext into a byte array
        byte[] bInput = stringtoByte(EncryptStr,512);
        //System.Text.Encoding.UTF8.GetBytes(EncryptStr);
        //stringtoByte(EncryptStr,512);

        // write out encrypted content into MemoryStream 
        mCryptStr.Write(bInput, 0, bInput.Length); 
        mCryptStr.FlushFinalBlock(); 
        
        // get the output and trim the '\0' bytes 
        byte[] bOutput = mMemStr.GetBuffer(); 

        int MemLength = System.Convert.ToInt32(mMemStr.Length);
      
        //Clean up the memory
        mCryptStr.Close();
        mMemStr.Close();
        mEncryptor.Dispose();

        // convert into Base64 so that the result can be used in xml 
        
        return Convert.ToBase64String(bOutput,0,MemLength); 
      }
      catch(System.Security.Cryptography.CryptographicException ee)
      {
        objEventLog = new System.Diagnostics.EventLog();
        objEventLog.Source = "SMP-CryptoGraphy";
        objEventLog.WriteEntry("Exception Occured in Encryption " +
                "Process. Error is = " + ee.Message, 
                System.Diagnostics.EventLogEntryType.Error);
        objEventLog.Dispose();
        return("");
      }
     }
    #endregion
  
    #region "Decrypt Function"
    public string Decrypt(string EncryptProvider, string EncryptStr, 
           int BlckSize, int KySize, string Key, string IV)
    {
      //Check if something Algo is Selected 
      if(EncryptProvider.Length<=0)
      {
        return("Pass an Algo to use to Encrypt.");
      }
    
      //Since, The selected algo may not be Symmetric, So Try it
      try
      {
        mCryptProv = SymmetricAlgorithm.Create(EncryptProvider);
        mCryptProv.Mode = CipherMode.CBC;
      }
      catch(Exception ee)
      {
        return("Exception-1: " + ee.Message);
      }
      try
      {
        //Each Algo has different Size of Key and Block, So let's try
        mCryptProv.BlockSize = BlckSize;
        mCryptProv.KeySize = KySize;
      }
      catch
      {
        //Invalid Block or Key Size. Show the Default Ones
        string mStr;
        mStr = mCryptProv.BlockSize.ToString();
        mStr += "Invalid Block or Key Size.Valid Sizes are : "; 
        mStr += "Block Size = " + 
               mCryptProv.LegalBlockSizes[0].MinSize.ToString() + 
               " - " + mCryptProv.LegalBlockSizes[0].MaxSize.ToString() + 
               " With Increment of " + 
               mCryptProv.LegalBlockSizes[0].SkipSize.ToString();
        mStr += "Key  Size = " + 
               mCryptProv.LegalKeySizes[0].MinSize.ToString() + 
               " - " + mCryptProv.LegalKeySizes[0].MaxSize.ToString() + 
               " With Increment of " + 
               mCryptProv.LegalKeySizes[0].SkipSize.ToString();
        return(mStr);
        //Show the Valid Block Size 
      }
      
      try
      {
        //Change the supplied key to a byte array
        byte[] thisKey = stringtoByte(Key,KySize);
        //Hash the Supplied Secret key

        byte[] resultKey = HashOfByteArray(thisKey);
        int loopTill=0;
        if(BlckSize==128)loopTill=16;
        if(BlckSize==192)loopTill=24;
        if(BlckSize==256)loopTill=32;

        byte[] BlockKey = new byte[loopTill];
        for(int loop=0; loop<loopTill; loop++ )
          BlockKey[loop] = resultKey[loop];

        //Change the supplied IV to a byte array
        byte[] thisIV = stringtoByte(IV,BlckSize);

        //Hash the Supplied IV
        byte[] resultIV = HashOfByteArray(thisIV);
      
        byte[] BlockIV = new byte[loopTill];
        for( int loop=0; loop<loopTill; loop++ )
          BlockIV[loop] = resultIV[loop];

        //Try to Decrypt values in the memory
        //First Create the Decryptor, By Passing Key and IV
        ICryptoTransform mDecrypt = 
             mCryptProv.CreateDecryptor(thisKey, thisIV);
          
        byte[] bInput = System.Convert.FromBase64String(EncryptStr); 
        
        // create a MemoryStream with the input 
        System.IO.MemoryStream ms = 
             new System.IO.MemoryStream(bInput, 0, bInput.Length); 

        //Create Crypto Stream
        CryptoStream mCSReader = 
             new CryptoStream(ms, mDecrypt, CryptoStreamMode.Read);

        // read out the result from the Crypto Stream 
        System.IO.StreamReader sr = new System.IO.StreamReader(mCSReader); 
      
        //Close the crypto stream
        mCSReader.Close();
        ms.Close();
        mDecrypt.Dispose();
        return sr.ReadToEnd(); 
      }
      catch(System.Exception ee)
      {
        return("Exception in processing " + ee.Message);
      }
    }
    #endregion

    #region "Hashing of a BYTE Array by using SHA512Managed -" +
                   " return value is a Byte Array"
    private byte[] HashOfByteArray(byte[] ByteArray)
    {
      SHA512Managed sha512Key = new SHA512Managed();
      Sha512Key.ComputeHash(ByteArray);
      return(sha512Key.Hash);
    }
    #endregion
  
    #region "Hashing of a String by using SHA512Managed - " +
                   "return value is a Base64 string"
    public string HashOfString(string PlainText)
    {
      //Change the supplied string to a byte array
      try
      {
        int thisSize = PlainText.Length*8;
        int temp;
        if(PlainText.Length<1)
        {
          return("Please enter a Valid String to Hash. String passed is " + 
                  PlainText.ToString());
          
        }
        byte[] thisStr = new byte[thisSize];
        int lastBound = PlainText.Length;
        if(lastBound > thisSize)lastBound = thisSize;
        for(temp = 0;temp<=lastBound - 1;temp++)
        {
          thisStr[temp] = Convert.ToByte(PlainText[temp]);
        }
      
        SHA512Managed sha512Key = new SHA512Managed();
        Sha512Key.ComputeHash(thisStr);
        return(Convert.ToBase64String(sha512Key.Hash));
      }
      catch(System.Security.Cryptography.CryptographicException ee)
      {
        return("Exception Occured in Hashing Process. Error is = " + 
                 ee.Message);
    
      }
    }
    #endregion
    
    #region "String to a byte array conversion - " +
          "return value is a BYTE array"
    private byte[] stringtoByte(string textdata,int keySize)
    {
      int thisSize = (keySize / 8);
      int temp;
      byte[] returnByteArray = new byte[thisSize];
      int lastBound = textdata.Length;
      if(lastBound > thisSize)lastBound = thisSize;
      for(temp = 0;temp<=lastBound - 1;temp++)
      {
        returnByteArray[temp] = Convert.ToByte(textdata[temp]);
      }
      return(returnByteArray);
    }
    #endregion
  }

}
© . All rights reserved.