(SOFT) SOFT (2009 год)

NetStringObfuscatorHelper - OpenSource моей библиотеки симметричного шифрования.

На этой страничке я опишу одну свою крошечную утилитку NetStringObfuscatorHelper, которая может быть использована в тех случаях, когда вам не нужна полная обфускация кода, которую делает например Eazfuscator.NET.

Наверное каждый программист хоть раз в жизни залазил встроенным бинарным редактором студии и менял что-то прямо в DLL, когда не было исходников под рукой для полной перекомпиляции. Я уже не говорю про тех, кто научился работать в IDA Pro и сделал такие изменения в DLL Своей профессией.

Я пользуюсь этой своей прогой для защиты тех строк в коде, которые я не хочу, чтобы увидел кто-то чужой и заменил их на другие. Мой Helper вы можете сгрузить и посмотреть как он работает. Комментировать в этом коде особо нечего. Я просто открою тут код моей библиотки симметричной криптографии.



   1:  Public Class Symmetric
   2:   
   3:      'выдает на выход сгененрированный ключ, IV и выходным параметром - криптованную строку
   4:      Public Shared Function EnCryptString(ByVal GenerateNewKeyAndIV As Boolean, ByVal InputStr As String, ByRef Key As Byte(), ByRef IV As Byte()) As String
   5:          Try
   6:              Dim RMCrypto As New Security.Cryptography.RijndaelManaged()
   7:              If GenerateNewKeyAndIV Then
   8:                  RMCrypto.GenerateIV()
   9:                  IV = RMCrypto.IV
  10:                  RMCrypto.GenerateKey()
  11:                  Key = RMCrypto.Key
  12:              Else
  13:                  RMCrypto.IV = IV
  14:                  RMCrypto.Key = Key
  15:              End If
  16:              Dim InputArr() As Byte = (New System.Text.UnicodeEncoding).GetBytes(InputStr)
  17:              Dim MemStream As New IO.MemoryStream(InputArr)
  18:              Dim CryptStream1 As New Security.Cryptography.CryptoStream(MemStream, RMCrypto.CreateEncryptor(Key, IV), Security.Cryptography.CryptoStreamMode.Read)
  19:              Dim CryptoArrLength As Integer = (InputStr.Length + 32) * 2 'размер буфера (примерный)
  20:              Dim OutArr(CryptoArrLength) As Byte, I As Integer, OneByte As Byte
  21:              While True
  22:                  Try
  23:                      OneByte = CryptStream1.ReadByte
  24:                  Catch ex As System.OverflowException
  25:                      Exit While
  26:                  End Try
  27:                  OutArr(I) = OneByte
  28:                  I += 1
  29:              End While
  30:              MemStream.Close()
  31:              CryptStream1.Close()
  32:              ReDim Preserve OutArr(I - 1)
  33:              Dim OutBuilder As New System.Text.StringBuilder
  34:              For j As Integer = 0 To OutArr.Length - 1
  35:                  OutBuilder.AppendFormat("{0:X2}", OutArr(j))
  36:              Next
  37:              Return OutBuilder.ToString
  38:          Catch ex As Exception
  39:              Throw New Exception(ex.Message)
  40:          End Try
  41:      End Function
  42:   
  43:   
  44:      'выдает на выход сгененрированный ключ, IV и выходным параметром - криптованный массив
  45:      Public Shared Function EnCryptArray(ByVal GenerateNewKeyAndIV As Boolean, ByVal InputArr As Byte(), ByRef Key As Byte(), ByRef IV As Byte()) As Byte()
  46:          Try
  47:              Dim RMCrypto As New Security.Cryptography.RijndaelManaged()
  48:              If GenerateNewKeyAndIV Then
  49:                  RMCrypto.GenerateIV()
  50:                  IV = RMCrypto.IV
  51:                  RMCrypto.GenerateKey()
  52:                  Key = RMCrypto.Key
  53:              Else
  54:                  RMCrypto.IV = IV
  55:                  RMCrypto.Key = Key
  56:              End If
  57:              Dim MemStream As New IO.MemoryStream(InputArr)
  58:              Dim CryptStream1 As New Security.Cryptography.CryptoStream(MemStream, RMCrypto.CreateEncryptor(Key, IV), Security.Cryptography.CryptoStreamMode.Read)
  59:              Dim OutArr(InputArr.Length * 16) As Byte, I As Integer, OneByte As Byte
  60:              While True
  61:                  Try
  62:                      OneByte = CryptStream1.ReadByte
  63:                  Catch ex As System.OverflowException
  64:                      Exit While
  65:                  End Try
  66:                  OutArr(I) = OneByte
  67:                  I += 1
  68:              End While
  69:              MemStream.Close()
  70:              CryptStream1.Close()
  71:              ReDim Preserve OutArr(I - 1)
  72:              Return OutArr
  73:          Catch ex As Exception
  74:              Throw New Exception(ex.Message)
  75:          End Try
  76:      End Function
  77:   
  78:   
  79:   
  80:      'кушает на входе ключ, IV, криптованную строку и выдает расшифрованную строку
  81:      Public Shared Function DeCryptString(ByVal Key As Byte(), ByVal IV As Byte(), ByVal InputStr As String) As String
  82:          Try
  83:              Dim RMCrypto As New Security.Cryptography.RijndaelManaged()
  84:              Dim CryptoArrLength As Integer = (InputStr.Length + 32) * 2 'размер буфера (примерный)
  85:              Dim InputArr(CryptoArrLength) As Byte, I As Integer, OneByte As Byte
  86:              For I = 0 To InputStr.Length / 2 - 1
  87:                  OneByte = Byte.Parse(InputStr.Substring(I * 2, 2), Globalization.NumberStyles.AllowHexSpecifier)
  88:                  InputArr(I) = OneByte
  89:              Next
  90:              ReDim Preserve InputArr(I - 1)
  91:              Dim MemStream As New IO.MemoryStream(InputArr)
  92:              Dim CryptStream1 As New Security.Cryptography.CryptoStream(MemStream, RMCrypto.CreateDecryptor(Key, IV), Security.Cryptography.CryptoStreamMode.Read)
  93:              Dim OutArr(CryptoArrLength) As Byte, j As Integer
  94:              While True
  95:                  Try
  96:                      OneByte = CryptStream1.ReadByte
  97:                  Catch ex As System.OverflowException
  98:                      Exit While
  99:                  End Try
 100:                  OutArr(j) = OneByte
 101:                  j += 1
 102:              End While
 103:              MemStream.Close()
 104:              CryptStream1.Close()
 105:              ReDim Preserve OutArr(j - 1)
 106:              Return (New System.Text.UnicodeEncoding).GetString(OutArr)
 107:          Catch ex As Exception
 108:              Throw New Exception(ex.Message)
 109:          End Try
 110:      End Function
 111:   
 112:      'кушает на входе ключ, IV, криптованную строку и выдает расшифрованный массив
 113:      Public Shared Function DeCryptArray(ByVal Key As Byte(), ByVal IV As Byte(), ByVal InputArr() As Byte) As Byte()
 114:          Try
 115:              Dim RMCrypto As New Security.Cryptography.RijndaelManaged()
 116:              Dim MemStream As New IO.MemoryStream(InputArr)
 117:              Dim CryptStream1 As New Security.Cryptography.CryptoStream(MemStream, RMCrypto.CreateDecryptor(Key, IV), Security.Cryptography.CryptoStreamMode.Read)
 118:              Dim OutArr(InputArr.Length * 16) As Byte, j As Integer, OneByte As Byte
 119:              While True
 120:                  Try
 121:                      OneByte = CryptStream1.ReadByte
 122:                  Catch ex As System.OverflowException
 123:                      Exit While
 124:                  End Try
 125:                  OutArr(j) = OneByte
 126:                  j += 1
 127:              End While
 128:              MemStream.Close()
 129:              CryptStream1.Close()
 130:              ReDim Preserve OutArr(j - 1)
 131:              Return OutArr
 132:          Catch ex As Exception
 133:              Throw New Exception(ex.Message)
 134:          End Try
 135:      End Function
 136:   
 137:      'это просто функция дополнения массива до 16 
 138:      Function PaddingArray16(ByVal InputArr As Byte()) As Byte()
 139:          Dim i As Integer
 140:          Dim extraBytes As Integer = 0
 141:          Dim len As Integer = InputArr.Length
 142:          If len Mod 16 <> 0 Then : extraBytes = 16 - (len Mod 16) : End If
 143:          If extraBytes <> 0 Then
 144:              ReDim Preserve InputArr(len + extraBytes - 1)
 145:              For i = len To (len + extraBytes - 1)
 146:                  InputArr(i) = 32 ' ascii value for space
 147:              Next i
 148:          End If
 149:          Return InputArr
 150:      End Function
 151:   
 152:      Public Shared Function ByteKeyToString(ByVal Key As Byte()) As String
 153:          Dim KeyBuilder = New System.Text.StringBuilder
 154:          For j As Integer = 0 To Key.Length - 1
 155:              KeyBuilder.AppendFormat("{0:X2}", Key(j))
 156:          Next
 157:          Return KeyBuilder.ToString
 158:      End Function

Чтобы вызвать функции этой библиотечки, объявите ключи и пользуйтесь ими на протяжении всей сессии:


   1:  Dim Symm_Key(32) As Byte, Symm_IV(16) As Byte            
   2:  'генерим сеансовый симметричный ключ
   3:  Symmetric.EnCryptString(True, " ", Symm_Key, Symm_IV)
   4:  'запишем что-нибудь в выходной поток браузера
   5:  Response.Write(Symmetric.EnCryptString(False, "йцукен ", Symm_Key, Symm_IV))

Помните, что сеансовые ключи в открытом виде (естественно) передавать низзя. Для этого их шифруют ассимметрично, например так:


   5:  'шифруем симметричные ключи его ассимметричным
   6:  RsaCrypt_Symm_Key = RSA.Encrypt(Symm_Key, False)
   7:  RsaCrypt_Symm_IV = RSA.Encrypt(Symm_IV, False)

Подробнее о работе с ассимметричными ключами шифрования вы можете познакомится в топиках:





Comments ( )
<00>  <01>  <02>  <03>  <04>  <05>  <06>  <07>  <08>  <09>  <10>  <11>  <12>  <13>  <14>  <15>  <16>  <17>  <18>  <19>  <20>  <21>  <22>  <23
Link to this page: //www.vb-net.com/NetStringObfuscatorHelper/index.htm
<SITEMAP>  <MVC>  <ASP>  <NET>  <DATA>  <KIOSK>  <FLEX>  <SQL>  <NOTES>  <LINUX>  <MONO>  <FREEWARE>  <DOCS>  <ENG>  <CHAT ME>  <ABOUT ME>  < THANKS ME>