1 2 3 4 5 6 7 8 9 | 版权申明:本文为博主窗户(Colin Cai)原创,欢迎转帖。如要转贴,必须注明原文网址 http://www.cnblogs.com/Colin-Cai/p/8013009.html 作者:窗户 QQ:6679072 E-mail:6679072@qq.com |
使用RSA公钥解密,用openssl命令就是openssl rsautl -verify -in cipher_text -inkey public.pem -pubin -out clear_text,但其python网上还真没有找到有博文去写,只有hash的rsa解签名。
这里使用rsa库,如果没有可以到官方网址https://pypi.python.org/pypi/rsa/3.1.4下载。
想了想原理,然后到rsa库的python代码里找了找,从verify的代码里提取了出来,又试验了试验,一切OK了。
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | #! /usr/bin/env python # -*- coding: utf-8 -*- import sys #rsa from rsa import PublicKey, common, transform, core def f(cipher, PUBLIC_KEY): public_key = PublicKey.load_pkcs1(PUBLIC_KEY) encrypted = transform.bytes2int(cipher) decrypted = core.decrypt_int(encrypted, public_key.e, public_key.n) text = transform.int2bytes(decrypted) if len (text) > 0 and text[ 0 ] = = '\x01' : pos = text.find( '\x00' ) if pos > 0 : return text[pos + 1 :] else : return None fn = sys.stdin.readline()[: - 1 ] public_key = sys.stdin.readline()[: - 1 ] x = f( open (fn).read(), open (public_key).read()) print x |
用shell验证如下:
1 2 3 4 5 6 7 8 9 10 11 | $ openssl genrsa -out pri2048.pem 2048 Generating RSA private key, 2048 bit long modulus ..+++ ..............................................+++ e is 65537 (0x10001) $ openssl rsa - in pri2048.pem -out pub2048.pem -RSAPublicKey_out writing RSA key $ echo -n 'Just a test' >1.txt $ openssl rsautl -sign - in 1.txt -inkey pri2048.pem -out 1.bin $ { echo 1.bin; echo pub2048.pem; } | . /test_rsa .py Just a test |
一切OK,注意,公钥pem从私钥里析出必须用-RSAPublicKey_out,这样pem文件的第一行和最后一行为以下,这样rsa.PublicKey.load_pkcs1才会认识。
-----BEGIN RSA PUBLIC KEY-----
-----END RSA PUBLIC KEY-----
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析