RSACryptoServiceProvider从C#转换为VB

时间:2014-03-18 16:08:47

标签: c# vb.net public-key-encryption

我被第三方客户端发送了以下代码块,以允许我访问一些网络服务:

    RSACryptoServiceProvider rsaCryptoServiceProvider = new
    RSACryptoServiceProvider(dwKeySize);
    rsaCryptoServiceProvider.FromXmlString(xmlString);
    int keySize = dwKeySize / 8;
    byte[] bytes = Encoding.UTF32.GetBytes(inputString);
    int maxLength = keySize - 42;
    int dataLength = bytes.Length;
    int iterations = dataLength / maxLength;
    StringBuilder stringBuilder = new StringBuilder();
    for (int i = 0; i <= iterations; i++)
   {
     byte[] tempBytes = new byte[(dataLength - maxLength * i > maxLength) ?
     maxLength : dataLength - maxLength * i];
     Buffer.BlockCopy(bytes, maxLength * i, tempBytes, 0, tempBytes.Length);
     byte[] encryptedBytes = rsaCryptoServiceProvider.Encrypt(tempBytes, true);
     Array.Reverse(encryptedBytes);
     stringBuilder.Append(Convert.ToBase64String(encryptedBytes));
    }
    return stringBuilder.ToString();

我已将它从C#转换为VB.Net:

    Dim objEncrypter As New RSACryptoServiceProvider(Me.m_intKeySize)
    objEncrypter.FromXmlString(m_strEncryptionString)
    Dim intKeySize = Me.m_intKeySize / 8
    Dim objByte() As Byte = Encoding.UTF32.GetBytes(p_strXMLString.InnerXml)
    Dim intMaxLength As Integer = intKeySize - 42
    Dim intDataLength As Integer = objByte.Length
    Dim intIterations As Integer = intDataLength / intMaxLength
    Dim strResult As StringBuilder = New StringBuilder

    For intCounter As Integer = 0 To intIterations
        Dim tempBytes(IIf(intDataLength - intMaxLength * intCounter > intMaxLength, intMaxLength, intDataLength - intMaxLength * intCounter)) As Byte
        Buffer.BlockCopy(objByte, intMaxLength * intCounter, tempBytes, 0, tempBytes.Length)
        Dim objEncryptedBytes() As Byte = objEncrypter.Encrypt(tempBytes, True)
        Array.Reverse(objEncryptedBytes)
        strResult.Append(Convert.ToBase64String(objEncryptedBytes))
    Next

    Return strResult.ToString

问题是它不断抛出以下异常:

System.ArgumentException:偏移量和长度超出数组的范围,或者计数大于从索引到源集合末尾的元素数。

我可以看到它在做什么,尝试解决不存在的字节数组的区域,但我看不出原因。除非C#代码不起作用或翻译中丢失了某些内容。有什么建议吗?

凯文

1 个答案:

答案 0 :(得分:1)

使用上限而不是长度声明VB数组。 所以使用:

Dim tempBytes(If(dataLength - maxLength * i > maxLength, maxLength, dataLength - maxLength * i) - 1) As Byte

此外,您应该使用VB整数除法:

Dim iterations As Integer = dataLength \ maxLength