Cryptography -

CryptoServiceProvider (CSP)

  • The CryptoServiceProvider (CSP) classes in the System.Security.Cryptography namespace provide cryptography services.
  • Generating cryptographic Random Number Generator (RNG): System.Security.Cryptography.RNGCryptoServiceProvider
  • Asymmetric Encryption (2 public-key CSP)
    • System.Security.Cryptography.DSACryptoServiceProvider
    • System.Security.Cryptography.RSACryptoServiceProvider 
  • Symmetric Encryption (4 private-key cryptographic algorithms)
    • System.Security.Cryptography.DES
    • System.Security.Cryptography.TripleDES
    • System.Security.Cryptography.RC2
    • System.Security.Cryptography.Rijndael


  • Compute Salt
    Dim rng As New RNGCryptoServiceProvider()
    Dim buff As Byte() = New Byte(size)
    Return Convert.ToBase64String(buff)
  • Hash Value
    ' Create a new instance of the hash crypto service provider.
    Dim hashAlg As HashAlgorithm = New SHA256CryptoServiceProvider()
    ' Convert the data to hash to an array of Bytes.
    Dim bytValue As Byte() = System.Text.Encoding.UTF8.GetBytes(stringDataToHash)
    ' Compute the Hash. This returns an array of Bytes.
    Dim bytHashValue As Byte() = hashAlg.ComputeHash(bytValue)
    ' Optionally, represent the hash value as a base64-encoded string.
    Dim bytHashValue64 As String = Convert.ToBase64String(bytHashValue)
    Return bytHashValue64
  • Rfc2898DeriveBytes
    • An implementation of PBKDF2.
    • Creates salt value.
    • Has iteration function to repeatedly hash the user password along with the salt.
      Public Shared Sub SaltAndHashPassword(ByVal password As String, ByRef saltvalue() As Byte, ByRef passwordhashed() As Byte)
           Dim rdb As New Rfc2898DeriveBytes(password, SALT_SIZE, ITERATIONS)
           saltvalue = rdb.Salt
           passwordhashed = rdb.GetBytes(HASH_SIZE)
      End Sub

Encryption and Decryption

  • General Coding Practices
    • All CSP objects have two important methods: CreateEncryptor & CreateDecryptor
    • CryptoStream: handles all encryption and decryption.
    • MemoryStream: handles strings as streams and flow them through the CryptoStream.
    • Key: derived by a function to perform the encryption and decryption.
    • Initialization Vector (IV): a block of bits (a salt value) required to allow a stream to be executed to produce a unique stream independent from other streams produced by the same encryption key
  • Preparation
    • Decide what to encrypt and decrypt.
      • Session IDs
      • Data columns (not all columns)
      • Encryption key
      • Configuration settings (e.g., connection string, appsettings, sessionstate, etc.)
      • Querystring
      • ViewState
  • Store the encrypted data (size)

    Key & IV Generator
    Private Function IV_192()
        Dim strKey As String = ReturnKey()
        Dim strIV1 As String = Left(strKey, 10)
        Dim strIV2 As String = Right(strKey, 25)
        Dim strIV3 As String = strIV1 & strIV2
        Dim IV_192() As Byte = Encoding.ASCII.GetBytes(strIV3.ToCharArray)
        Return IV_192
    End Function
    Private Function KEY_192()
        Dim strKey As String = ReturnKey()
        Dim strK1 As String = Left(strKey, 30)
        Dim strK2 As String = Right(strKey, 5)
        Dim strK3 As String = strK1 & strK2
        vKey = EncryptVariable(strK3)
        Dim KEY_192() As Byte = Encoding.ASCII.GetBytes(strKey.ToCharArray)
        Return KEY_192
    End Function

    Key Generation with Rfc2898DeriveBytes
        Rfc2898DeriveBytes(Byte(), Byte(), Int32)
        (Initializes a new instance of the Rfc2898DeriveBytes class using a password, a salt, and number of iterations to derive the key.)
        (Gets or sets the key salt value for the operation.) 
        (Returns the pseudo-random key for this object.)   

    Encryption Function
    Private Function Encrypt(ByVal Value As String) As String
        Dim cspDES As New TripleDESCryptoServiceProvider()
        Dim ct As ICryptoTransform
        Dim ms As MemoryStream = New MemoryStream()
        Dim cs As CryptoStream Dim byt() As Byte
        ' convert a binary string representation of a key/iv into a byte array
        cspDES.Key = Convert.FromBase64String(KEY_192)
        cspDES.IV = Convert.FromBase64String(IV_192)
        ' convert the input string into a byte array
        byt = Encoding.UTF8.GetBytes(Value)
        ' create an object to perform the actual encryption
        ct = cspDES.CreateEncryptor()
        ' the encryption
        cs = New CryptoStream(ms, ct, CryptoStreamMode.Write)
        cs.Write(byt, 0, byt.Length)
        ' ensure all the data has been written into the MemoryStream object
        ' use ToArray() method to get the array of bytes out of the memory stream ' convert the
            memory stream from an array of bytes back into a string
        Return Convert.ToBase64String(ms.ToArray())
    End Function
  • Decryption Function
    • The procedures are the same as the encryption function.
    • But use the CreateDecryptor method.

Hashing Functions

    Public Shared Sub SaltAndHashPassword(ByVal password As String, ByRef saltvalue() As Byte, ByRef passwordhashed() As Byte)
        Dim rdb As New Rfc2898DeriveBytes(password, SALT_SIZE, ITERATIONS)
        saltvalue = rdb.Salt
        passwordhashed = rdb.GetBytes(HASH_SIZE)
    End Sub

Encrypt Session IDs and Querystrings

  • Create the encryption and decrption functions.
  • Call the functions

Encrypt Connection Strings

  • Use the apnet_regiis command line tool located in the .NET Framework 2.0 system folder: %windir%\\Framework\
  • Use the two providers:
    • RSAProtectedConfigurationProvider, which uses RSA encryption
    • DataProtectionConfigurationProvider, which uses DPAPI (easier)
  • Decide how to store the encryption key.
  • Machine-level: if the machine is under your physical control
  • User-level: if the application is in a shared hosting environment
  • Example connection string to be encrypted:
        <add name="Northwind" connectionString="initial catalog=Northwind; data
            source=localhost; Integrated security= SSPI"; providername =
  • Encrypt by executing the aspnet_regiis command:
    aspnet_regiis -pe "connectionStrings" -app "/SampleApplication"
  • Decrypt by executing the aspnet_regiis command:
    aspnet_regiis -pd "connectionStrings" -app "/SampleApplication"

Decryption Viewstate

  • The State of ViewState
    • It is base64-encoded string stored in a hidden field called __VIEWSTATE in the HTML of the web page.
    • By default the it is not encrypted.
  • 2 Ways To Encrypt Viewstate
    • Using hashcode (MD5 or SHA1) will reduce the likelihood of someone tampering with ViewState to try to spoof your application.
    • Upon postback, the EnableViewStateMAC in ASP.Net will generate a hashcode for the ViewState data and compare it to the hashcode store in the posted value. If they don't match, the ViewState data will be discarded and the controls will revert to their original settings.