文字列を暗号化する

本文介绍了一种使用共有密钥暗号方式对字符串进行加密和解密的方法。通过创建DESCryptoServiceProvider对象并利用MemoryStream来处理加密过程,实现了字符串到加密字符串的转换,并提供了相应的VB.NET代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 http://dobon.net/vb/dotnet/string/encryptstring.html

共有キー暗号方式により文字列(String型データ)を暗号化し、文字列として取得する方法を紹介します。

方法は「ファイルを暗号化する」と同じですが、「ファイルを暗号化する」ではファイルから読み込んだデータを暗号化し、ファイルに書き込んでいるため、CryptoStreamオブジェクトを作成する際に、暗号化の対象とするストリームとしてFileStreamオブジェクトを指定していましたが、ここではMemoryStreamオブジェクトを指定することにします。

 

[VB.NET]
''' <summary>
''' 文字列を暗号化する
''' </summary>
''' <param name="str">暗号化する文字列</param>
''' <param name="key">パスワード</param>
''' <returns>暗号化された文字列</returns>
Public Shared Function EncryptString(ByVal str As String, _
                                ByVal key As String) As String
    '文字列をバイト型配列にする
    Dim bytesIn As Byte() = System.Text.Encoding.UTF8.GetBytes(str)

    'DESCryptoServiceProviderオブジェクトの作成
    Dim des As New System.Security.Cryptography.DESCryptoServiceProvider

    '共有キーと初期化ベクタを決定
    'パスワードをバイト配列にする
    Dim bytesKey As Byte() = System.Text.Encoding.UTF8.GetBytes(key)
    '共有キーと初期化ベクタを設定
    des.Key = ResizeBytesArray(bytesKey, des.Key.Length)
    des.IV = ResizeBytesArray(bytesKey, des.IV.Length)

    '暗号化されたデータを書き出すためのMemoryStream
    Dim msOut As New System.IO.MemoryStream
    'DES暗号化オブジェクトの作成
    Dim desdecrypt As System.Security.Cryptography.ICryptoTransform = _
        des.CreateEncryptor()
    '書き込むためのCryptoStreamの作成
    Dim cryptStreem As New System.Security.Cryptography.CryptoStream( _
        msOut, desdecrypt, _
        System.Security.Cryptography.CryptoStreamMode.Write)
    '書き込む
    cryptStreem.Write(bytesIn, 0, bytesIn.Length)
    cryptStreem.FlushFinalBlock()
    '暗号化されたデータを取得
    Dim bytesOut As Byte() = msOut.ToArray()

    '閉じる
    cryptStreem.Close()
    msOut.Close()

    'Base64で文字列に変更して結果を返す
    Return System.Convert.ToBase64String(bytesOut)
End Function

''' <summary>
''' 暗号化された文字列を復号化する
''' </summary>
''' <param name="str">暗号化された文字列</param>
''' <param name="key">パスワード</param>
''' <returns>復号化された文字列</returns>
Public Shared Function DecryptString(ByVal str As String, _
                            ByVal key As String) As String
    'DESCryptoServiceProviderオブジェクトの作成
    Dim des As New System.Security.Cryptography.DESCryptoServiceProvider

    '共有キーと初期化ベクタを決定
    'パスワードをバイト配列にする
    Dim bytesKey As Byte() = System.Text.Encoding.UTF8.GetBytes(key)
    '共有キーと初期化ベクタを設定
    des.Key = ResizeBytesArray(bytesKey, des.Key.Length)
    des.IV = ResizeBytesArray(bytesKey, des.IV.Length)

    'Base64で文字列をバイト配列に戻す
    Dim bytesIn As Byte() = System.Convert.FromBase64String(str)
    '暗号化されたデータを読み込むためのMemoryStream
    Dim msIn As New System.IO.MemoryStream(bytesIn)
    'DES復号化オブジェクトの作成
    Dim desdecrypt As System.Security.Cryptography.ICryptoTransform = _
        des.CreateDecryptor()
    '読み込むためのCryptoStreamの作成
    Dim cryptStreem As New System.Security.Cryptography.CryptoStream( _
        msIn, desdecrypt, _
        System.Security.Cryptography.CryptoStreamMode.Read)

    '復号化されたデータを取得するためのStreamReader
    Dim srOut As New System.IO.StreamReader( _
        cryptStreem, System.Text.Encoding.UTF8)
    '復号化されたデータを取得する
    Dim result As String = srOut.ReadToEnd()

    '閉じる
    srOut.Close()
    cryptStreem.Close()
    msIn.Close()

    Return result
End Function

''' <summary>
''' 共有キー用に、バイト配列のサイズを変更する
''' </summary>
''' <param name="bytes">サイズを変更するバイト配列</param>
''' <param name="newSize">バイト配列の新しい大きさ</param>
''' <returns>サイズが変更されたバイト配列</returns>
Private Shared Function ResizeBytesArray(ByVal bytes() As Byte, _
                            ByVal newSize As Integer) As Byte()
    Dim newBytes(newSize - 1) As Byte
    If bytes.Length <= newSize Then
        Dim i As Integer
        For i = 0 To bytes.Length - 1
            newBytes(i) = bytes(i)
        Next i
    Else
        Dim pos As Integer = 0
        Dim i As Integer
        For i = 0 To bytes.Length - 1
            newBytes(pos) = newBytes(pos) Xor bytes(i)
            pos += 1
            If pos >= newBytes.Length Then
                pos = 0
            End If
        Next i
    End If
    Return newBytes
End Function
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值