从字符串生成用于加密的整数,反之亦然 [英] Generate an integer for encryption from a sting and vice versa

查看:62
本文介绍了从字符串生成用于加密的整数,反之亦然的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 python3 中编写 RSA 代码.我需要将用户输入字符串(包含任何字符,而不仅仅是数字)转换为整数,然后对它们进行加密.在没有 3-rd 方模块的情况下,在 Python 3.6 中将 sting 转换为整数的最佳方法是什么?

I am trying to write an RSA code in python3. I need to turn user input strings (containing any characters, not only numbers) into integers to then encrypt them. What is the best way to turn a sting into an integer in Python 3.6 without 3-rd party modules?

推荐答案

如何将字符串编码为整数远非唯一...有很多方法!这是其中之一:

how to encode a string to an integer is far from unique... there are many ways! this is one of them:

strg = 'user input'
i = int.from_bytes(strg.encode('utf-8'), byteorder='big')

另一个方向的转换是:

s = int.to_bytes(i, length=len(strg), byteorder='big').decode('utf-8')

是的,在转换回来之前,您需要知道结果字符串的长度.如果 length 太大,字符串将从左边用 chr(0) 填充(使用 byteorder='big');如果 length 太小,int.to_bytes 将引发 OverflowError: int too big to convert.

and yes, you need to know the length of the resulting string before converting back. if length is too large, the string will be padded with chr(0) from the left (with byteorder='big'); if length is too small, int.to_bytes will raise an OverflowError: int too big to convert.

这篇关于从字符串生成用于加密的整数,反之亦然的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆