Python 实现RSA SHA-1签名

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/dutsoft/article/details/78029492

今天对接业务接口,传递的参数需要用RSA签名,三方只给了java的RSA签名Demo;但我们这边后端采用python开发,因此需要用Python来实现RSA签名。

Java版Demo

import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;

public class Sign {
    public static String sign(String content, String privateKey) {
        try {
            PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64
                    .decode(privateKey));
            KeyFactory keyf = KeyFactory.getInstance("RSA");
            PrivateKey priKey = keyf.generatePrivate(priPKCS8);

            java.security.Signature signature = java.security.Signature
                    .getInstance("SHA1WithRSA");//签名算法SHA1WithRSA

            signature.initSign(priKey);
            signature.update(content.getBytes("UTF-8"));

            byte[] signed = signature.sign();

            return Base64.encode(signed);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}

Python相关RSA加密库: rsa, Crypto, M2Crypto;下面分别调研了使用rsa和Crypto实现RSA签名(代码中,pem就是RSA签名需要的私钥)。

利用rsa库

import base64
import rsa

def sign(self, data):
    pri_key = rsa.PrivateKey.load_pkcs1(self.pem)
    signature = rsa.sign(str(data), priv_key=pri_key, hash='SHA-1')
    return base64.b64encode(signature)

利用Crypto库

import base64
from Crypto.Signature import PKCS1_v1_5
from Crypto.PublicKey import RSA
from Crypto.Hash import SHA


def sign(self, data):
    private_key = RSA.importKey(self.pem)
    cipher = PKCS1_v1_5.new(private_key)
    h = SHA.new(data)
    signature = cipher.sign(h)
    return base64.b64encode(signature)

相关内容

openssl生成PKCS#1格式

openssl genrsa -out rsa_private_key.pem 1024
openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem

openssl生成PKCS#8格式

openssl pkcs8 -topk8 -inform PEM -in rsa_private_key.pem -outform PEM -nocrypt

python方式生成PKCS#1格式

import rsa

(pubkey, privkey) = rsa.newkeys(1024)
privkey.save_pkcs1('PEM')
pubkey.save_pkcs1('PEM')
展开阅读全文

没有更多推荐了,返回首页