Python 中使用 OpenSSL 的 RSA 加密和解密

RSA encryption and decryption in Python using OpenSSL

我有 public 密钥、私钥和加密消息(e、n、d、消息)。我想在 Python.

中使用 OpenSSL 进行加密和解密

我有密钥,但不需要生成它们。我看到很多关于 RSA 的问题,但它们都是通过 generate 方法创建密钥的。没看到关于加解密的问题

如何在 Python usomg OpenSSL 中执行 RSA 加密和解密?


我有以下内容:

#Public key:
e="65537"

n="2483790199491205341506001624338547531741771200963322451" \
  "16318655098567854682220895878748602513720919196015584783557" \
  "704400541915850094004767776687012394493261448676783015273985771" \
  "1238030112386627501698642461625407366533907839206541565912321199" \
  "009791795944233570230631191423356738502486763195167267521973031" \
  "6838578210434343067511636079081818744400113533624136339709745782" \
  "32161853372590090308494113224155565481298018056338822080805188480" \
  "139150684063550507331062187412707210886548924698896783031493679037" \
  "3122088161029787856707927049345768779125257912445784686277424030038" \
  "539380288863347855630618237433032833865316901740219"


#Private key
d="152501997096795110757068525202189319208625862269501399381045003" \
  "01373684948285528219578200125958795897780598922907027278290745917" \
  "4083840545807194541888429655727807270271016523695687179904011971106" \
  "46024638603131783118232131092639581621182826911051011196270811088775" \
  "8622627957416117004996969971673524599345136221501081814180958260506967" \
  "05549363779862358358393233189560520163106785535319492545898745183439" \
  "10980478364023104227720426942196244946117979269924656213962726626606" \
  "77452212629548965644705371048342816305068001182195025882564173365857" \
  "07762540909960941277936950557159506459454566798472128560135656506235" \
  "741389170953"


#encrypted message
encoded="187216163520278606105320112446137004408231369834741341053563682" \
        "277774349916058822189964158715390402738262899525931062389534962" \
        "09104749822344117450601254708536373034264130933521987327974000" \
        "255146756518397668069770185737907343422454676477169144712992560" \
        "738066894543224559303296179944700852861503983647039123452966586" \
        "43024446530008588087574157621730825724439869400851215840977916" \
        "767440706251849931986529460039147463908090086303953826751056882" \
        "5732583473943114017472152320746478960753673137088195122814398113" \
        "5288648561417818449968250721180493107501204327582989947582671" \
        "70231934908068721013345590521202959891172540575563129"

无需使用pyOpenSSL或任何其他外部库即可对密文进行解码。

用公式m = cd[=29简单地逆向加密运算=] mod n 如下:

n="24837..."
d="15250..."
encoded="18721..."
plaintext = pow(int(encoded,10),int(d,10),int(n,10))
print hex(plaintext)[2:-1].decode('hex')

pow() 运算符执行 mod 平方幂运算来计算 (encoded**d) % n。在print语句中,将结果值转换为十六进制(去掉前两个字符0x和最后一个字符L),然后解码为十六进制字符串以检索原始字节.

由于消息是在没有使用任何填充的情况下编码的,因此不需要进一步的操作。