在VB.NET中使用BigInteger时出现溢出异常

时间:2013-06-17 18:49:22

标签: .net vb.net overflow biginteger

我正在尝试编写一个程序来加密和解密RSA中的短消息,所以我一直在使用BigInteger对象来存储大数字。加密工作正常,但是当我运行我的解密部分代码时,它会给我一个溢出异常错误,对于使用BigInteger.DivRem()方法的行中的Int32,Value太大或太小。这很奇怪,因为我甚至不在这段代码中使用任何Integer对象。谁能告诉我这里我做错了什么?

    Private Sub DecryptButton_Click(ByVal sender As System.Object, ByVal e As    System.EventArgs) Handles DecryptButton.Click
    Dim cipherText As BigInteger
    Dim cipherTextString As String
    Dim n, d, counter As BigInteger
    Dim f As BigInteger = 0
    Dim asciiArray() As Byte = Nothing
    Dim splits As String = ""
    Dim decryptedText As String
    counter = 0

    n = BigInteger.Parse("really large number")
    d = BigInteger.Parse("really large number")

    BigInteger.DivRem(BigInteger.Pow(BigInteger.Parse(CipherBox.Text), d), n, f)

    cipherText = f

    cipherTextString = cipherText.ToString

    For i As Integer = 0 To cipherTextString.Length - 1
        Dim c As Char = cipherTextString(i)
        If splits.Length < 2 Then
            splits = splits + c.ToString
        Else
            asciiArray(counter) = Byte.Parse(splits)
            splits = Nothing
            counter = counter + 1
        End If
    Next

    decryptedText = System.Text.ASCIIEncoding.ASCII.GetString(asciiArray)
    MessageText.Text = decryptedText

End Sub

1 个答案:

答案 0 :(得分:1)

是的,您在代码中使用了Integers。你只是没有意识到这一点。

切换Option Strict On,您的代码将无法编译,因为dcounter声明为BigInteger,可能导致数据丢失或溢出,这是Option Strict所做的事情不允许。

你应该always use Option Strict On并且只针对特殊情况(延迟绑定等)将其关闭,然后仅在部分类中关闭。