【问题标题】:Displaying in hex form instead of special characters以十六进制形式而不是特殊字符显示
【发布时间】:2014-04-29 17:25:28
【问题描述】:

在这里,我想获取以下格式的文本: \x10\x11\x12\x13\x15\x14\x16\x17 ,当显示控制台时我该如何获取

   from pyDes import *
   import base64,string,random
   letters = [chr(i) for i in range(0,128)]
   key = '12345678'
   obj1= des(key, ECB)
   obj2 = des(key, ECB)
   text = '\x10\x11\x12\x13\x15\x14\x16\x17'
   print len(text)
   cipher_text = obj1.encrypt(text)
   decoded_text= obj2.decrypt(cipher_text)

   print; print 'plain text: ', text
   print; print 'Actual key: ', key 
   print; print 'Cipher text: ',cipher_text

【问题讨论】:

    标签: python cryptography hex des


    【解决方案1】:

    使用repr()%r 字符串格式占位符打印表示:

    print '\nplain text: %r' % text
    print '\nActual key: %r' % key 
    print '\nCipher text: %r' % cipher_text
    

    或者您可以将文本显式编码为string_escape 编码:

    print '\nplain text:', text.encode('string_escape')
    print '\nActual key:', key.encode('string_escape')
    print '\nCipher text:', cipher_text.encode('string_escape')
    

    这两种方法都不会将所有字节转换为\xhh转义序列,只有那些超出可打印ASCII字符范围的字符。

    要将所有字符转换为转义序列,您必须使用以下内容:

    def tohex(string):
        return ''.join('\\x{:02x}'.format(ord(c)) for c in string)
    

    然后

    print '\nplain text:', tohex(text)
    print '\nActual key:', tohex(key)
    print '\nCipher text:', tohex(cipher_text)
    

    【讨论】:

    • +1 为.encode('string_escape'),太棒了!但这不会用'\x68' 替换像'h' 这样的ASCII 可打印文件,对吗?
    • @lmjohns3:不,不会。这还需要更多的工作,继续努力。
    • 那真是太糟糕了,谢谢:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-23
    • 2013-06-06
    • 2012-07-08
    • 2013-04-03
    • 1970-01-01
    • 2014-12-05
    相关资源
    最近更新 更多