Python索引错误字符串

时间:2017-11-05 19:24:11

标签: python rsa sage

我似乎收到以下错误 -

IndexError                                Traceback (most recent call last)
<ipython-input-46-582a33edccfc> in <module>()
 10         string = alphabet[i] + string
 11     return string
 ---> 12 ptext=number2string(int(dec))
 13 print ptext

 <ipython-input-46-582a33edccfc> in number2string(M)
  8         i = M % Integer(100)
  9         M = (M-i)/Integer(100)
 ---> 10         string = alphabet[i] + string
 11     return string
 12 ptext=number2string(int(dec))

 IndexError: string index out of range

以下代码 -

n = 80590779575522264848081505402281132333075026055511
d = 5096598073523319979793354769252907316734417084656927459986239265286821982150579957763648301138598311
cipher= 60411283179665957400593484939411104457866145531782
dec = pow(cipher,d,n)
print dec
alphabet='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ,.?!:;-\'\"'
def string2number(string):
   M=0
   for i in range(len(string)):
       M = 100*M + alphabet.index(string[i])
   return M
def number2string(M):
    string=''
    while M > 0:
        i = M % 100
        M = (M-i)/100
        string = alphabet[i] + string
    return string
ptext=number2string(int(dec))
print ptext

我正在尝试执行RSA加密和解密。代码工作正常。这只是我隔离的一段摘录。我知道还有其他这样的问题,但我无法用这些解决方案来解决这个问题。

1 个答案:

答案 0 :(得分:1)

基本上当你做%100时,它会获取最后2位数字,显示错误,所以替换i = M % 100&amp; M = (M-i)/100i = M % 10&amp; M = (M-i)/10

<强>输出:

5351520757559142628218193819530718324607905389694 5351520757559142628218193819530718324607905389694