如何将mcrypt_encrypt从PHP转换为.NET代码?

时间:2015-01-05 19:49:36

标签: php .net vb.net encryption

我正在寻找将此函数从PHP转换为VB。谁能帮我理解为什么输出不正确?

//get img
$img = file_get_contents('https://www.random.org/analysis/randbitmap-rdo-section.png');

//pad
$blocksize = 16;
$pad = $blocksize - (strlen($img) % $blocksize);
$paddedimg = $img . str_repeat(chr($pad), $pad);

//encrypt
$data = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, 'abcdefghijklmnop', $paddedimg, MCRYPT_MODE_ECB);

//output
echo base64_encode($data);

以上输出; wYkugZmmsCHNwFOr7sAgk6yUU2I+2rOtBmXAIcPleue+dT4zIvkSA6UYmW6tickeoIbyCylxrb5n ... [其余截断但继续,总数为29484个字符]

这是我在VB中的所有内容;

  Public Sub GetBase64EncryptedImg()
    Dim Img As Byte() = Nothing
    Using wc As New WebClient
      Img = wc.DownloadData("https://www.random.org/analysis/randbitmap-rdo-section.png")
    End Using
    MsgBox(EncryptECB(Img))
  End Sub

  Public Function EncryptECB(Data As Byte()) As String

    Dim Key As Byte() = Encoding.UTF8.GetBytes("abcdefghijklmnop")
    Dim Encrypted As Byte() = Nothing

    Using rj As New RijndaelManaged()
      Try
        rj.Padding = PaddingMode.PKCS7
        rj.Mode = CipherMode.ECB
        rj.KeySize = 128
        rj.BlockSize = 128
        rj.Key = Key

        Dim ms As New MemoryStream()

        Using cs As New CryptoStream(ms, rj.CreateEncryptor(rj.Key, rj.IV), CryptoStreamMode.Write)

          Using sr As New StreamWriter(cs)
            sr.Write(Data)
          End Using
          Encrypted = ms.ToArray()
        End Using
      Finally
        rj.Clear()
      End Try

    End Using

    Return Convert.ToBase64String(Encrypted)
  End Function

VB输出; pVngUaXYYv1tJSPzjDuwKw==

就是这样,没有接近正确数量的字符。我在哪里错了?

编辑:重新标记为重复,该问题/答案返回base64编码的字符串。 mcrypt_encrypt没有,所以我不确定如何在该答案中应用代码。

EDIT2:该副本使用了IV值,而上面的代码没有。这不能区分这两者是否值得一个独特的答案?或者它是否像删除设置RijndaelManaged对象的IV属性的行一样简单?

EDIT3:完全重写了这个问题

0 个答案:

没有答案