imodeTwiter(通称、いもつい)の暗号化にはTripleDESを使用しています。
暗号化/複合部分については、以下のMSDN Onlineのサンプルを参考にしています。
MSDN Online = 10 行シリーズ~ 10 行でズバリ !! 暗号化 (VB.NET) ~
http://www.microsoft.com/japan/msdn/thisweek/10lines/encrypt_vb.aspx
しかしながら、このサンプルには重大なバグがあり、バイト配列をEncoding.Unicode.GetStringで文字列化しているために、暗号化した結果のバイト配列の中にUnicodeとして定義されていない値が入ってきた場合、その文字列を再び複合しようとするとエラーが発生します。
これは、暗号化/複合するときの2つのキー値、暗号化/複合する文字列の3つの組み合わせにより発生するもので恒常的に発生しません。そのため、なかなか見つからない、分からないというのが実情でしょう。
それを回避するには、Encoding.Unicode.GetString、Encoding.Unicode.GetBytesを使わずにSystem.Convert.ToBase64String、System.Convert.FromBase64Stringを使います。
Imports System.Text
Imports System.Security.Cryptography
Public Class TripleDESCrypto
Private Sub Execute_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Execute_Button.Click
Me.Crypto_TextBox.Text = TextToCryp(Me.Original_TextBox.Text.Trim, "hogehogexxxxxxxxxxxxxxxx")
Me.Plain_TextBox.Text = CrypToText(Me.Crypto_TextBox.Text.Trim, "hogehogexxxxxxxxxxxxxxxx")
End Sub
Public Function TextToCryp(ByVal plainText As String, ByVal keyValue As String) As String
Dim key() As Byte = Encoding.ASCII.GetBytes(keyValue.Substring(0, 16))
Dim iv() As Byte = Encoding.ASCII.GetBytes(keyValue.Substring(0, 8))
Dim des As New TripleDESCryptoServiceProvider
des.Key = key
des.IV = iv
Dim transform As ICryptoTransform = des.CreateEncryptor
Dim destination As Byte()
Using ms As System.IO.MemoryStream = New System.IO.MemoryStream
Using cs As CryptoStream = New CryptoStream(ms, transform, CryptoStreamMode.Write)
Try
Dim source As Byte() = Encoding.Unicode.GetBytes(plainText)
cs.Write(source, 0, source.Length) 'sourceの内容を暗号化してmsに書き出す()
cs.FlushFinalBlock()
destination = ms.ToArray()
Catch ex As Exception
Throw
Finally
cs.Close()
ms.Close()
End Try
End Using
End Using
Return System.Convert.ToBase64String(destination) '<-----暗号化後のバイナリ値にGetStringは使わない
End Function
Public Function CrypToText(ByVal crypText As String, ByVal keyValue As String) As String
Dim key() As Byte = Encoding.ASCII.GetBytes(keyValue.Substring(0, 16))
Dim iv() As Byte = Encoding.ASCII.GetBytes(keyValue.Substring(0, 8))
Dim source As Byte() = System.Convert.FromBase64String(crypText) 'GetBytesは使わない
Dim des As New TripleDESCryptoServiceProvider
des.Key = key
des.IV = iv
Dim transform As ICryptoTransform = des.CreateDecryptor
Dim destination As Byte()
Using ms As System.IO.MemoryStream = New System.IO.MemoryStream
Using cs As CryptoStream = New CryptoStream(ms, transform, CryptoStreamMode.Write)
Try
cs.Write(source, 0, source.Length) 'sourceの内容を複合してmsに書き出す()
cs.FlushFinalBlock()
destination = ms.ToArray()
Catch ex As Exception
Throw
Finally
cs.Close()
ms.Close()
End Try
End Using
End Using
Return Encoding.Unicode.GetString(destination)
End Function
End Class