python sign and java verifySign ( SHA256withRSA)

1.下载openssl工具

2.通过openssl生成RSA私钥命令:

openssl genrsa -out private.pem 4096

3.通过openssl生成RSA公钥命令:

openssl rsa -in private.pem -outform PEM -pubout -out public.pem

4.将RSA私钥公钥一并放入当前文件夹keys

 

5.python 实现签名源代码文件sign.py

/* python sign */

// sign.py file content

#! /usr/bin/env python2.7
# encoding: utf-8

import sys
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5 as Signature_pkcs1_v1_5
from Crypto.Hash import SHA256
import base64

def main():
    filename = "./keys/private.pem"
    testdata = "Hello Python!"

    with open(filename) as f:
        key = f.read()
        prikey = RSA.importKey(key)
        signer = Signature_pkcs1_v1_5.new(prikey)

        digest = SHA256.new()
        digest.update(testdata)

        signature = signer.sign(digest)
    auth_signature = base64.b64encode(signature)    #signature base64
    print "auth_signature: ", auth_signature

    with open("sign.txt", "w") as wf:
        write_size = wf.write(auth_signature)

if __name__ == '__main__':
    sys.exit(main())

6.java实现签名验签源代码文件

/* java verifySign */

// verifySign.java file content

import java.security.KeyFactory;
import java.security.InvalidKeyException;
import java.security.Signature;
import java.security.SignatureException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.io.*;

public class verifySign {

    private static final int DEFAULTBUFFERSTREAM = 4096;  // buffer 4kb

    /**
     * 从文件中读取文本
     *
     * @param filename
     * @return String
     */
    public static String readFromFile(String filename) {
        String readString = null;
        BufferedInputStream bufferedInput = null;
        byte[] buffer = new byte[DEFAULTBUFFERSTREAM];

        try {
            //创建BufferedInputStream 对象
            bufferedInput = new BufferedInputStream(new FileInputStream(filename));

            int bytesRead = 0;

            //从文件中按字节读取内容,到文件尾部时read方法将返回-1
            while ((bytesRead = bufferedInput.read(buffer)) != -1) {

                //将读取的字节转为字符串对象
                readString = new String(buffer, 0, bytesRead);
            }

        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            //关闭 BufferedInputStream
            try {
                if (bufferedInput != null)
                    bufferedInput.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

        return readString;
    }

    //  函数rsaSign可以实现Java下的SHA256withRSA签名,保留用。

    public static String rsaSign(String content, String privateKey) throws SignatureException {
        try {
            privateKey = privateKey.replace("-----BEGIN PRIVATE KEY-----", "");
            privateKey = privateKey.replace("-----END PRIVATE KEY-----", "");
            privateKey = privateKey.replace("\r", "");
            privateKey = privateKey.replace("\n", "");

            PrivateKey priKey = getPrivateKeyFromPKCS8("RSA", privateKey);

            Signature signature = Signature.getInstance("SHA256WithRSA");

            signature.initSign(priKey);
            signature.update(content.getBytes("UTF-8"));
            byte[] signed = signature.sign();
            return new String(Base64.getEncoder().encodeToString(signed));
        } catch (Exception e) {
            throw new SignatureException("RSAcontent = " + content, e);
        }
    }
    public static PrivateKey getPrivateKeyFromPKCS8(String algorithm, String privateKey) throws Exception {
        KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
        byte[] encodedKey = privateKey.getBytes("UTF-8");
        encodedKey = Base64.getDecoder().decode(encodedKey);
        return keyFactory.generatePrivate(new PKCS8EncodedKeySpec(encodedKey));
    }

    public static boolean rsaVerify(String content, String sign, String publicKey) throws SignatureException {
        publicKey = publicKey.replace("-----BEGIN PUBLIC KEY-----", "");
        publicKey = publicKey.replace("-----END PUBLIC KEY-----", "");
        publicKey = publicKey.replace("\r", "");
        publicKey = publicKey.replace("\n", "");
        try {
            PublicKey pubKey = getPublicKeyFromX509("RSA", publicKey);

            Signature signature = Signature.getInstance("SHA256WithRSA");

            signature.initVerify(pubKey);
            signature.update(content.getBytes("UTF-8"));

            return signature.verify(Base64.getDecoder().decode(sign.getBytes("UTF-8")));
        } catch (Exception e) {
            throw new SignatureException("RSA verify signature [content = " + content + "; signature = " + sign + "] Error!", e);
        }
    }
    public static PublicKey getPublicKeyFromX509(String algorithm, String publicKey) throws NoSuchAlgorithmException {
        try {
            KeyFactory keyFactory = KeyFactory.getInstance(algorithm);

            byte[] encodedKey = publicKey.getBytes("UTF-8");

            encodedKey = Base64.getDecoder().decode(encodedKey);

            return keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
        } catch (InvalidKeySpecException | IOException ex) {
            ex.printStackTrace();
        }
        return null;
    }

    /**
     * get file size
     *
     * @param filename
     * @return file size
     */
    public static long getFileSize(String filename) {
        File file = new File(filename);
        if (!file.exists() || !file.isFile()) {
            System.out.println("file is not exist or it is not a file");
            return -1;
        }
        return file.length();
    }

    // 去除 \0 字符
    public static String filterCode(String string){
        if (string != null) {
            string = string.trim();
            byte[] zero = new byte[1];
            zero[0] = (byte) 0;
            String s = new String(zero);
            string = string.replace(s, "");
        }
        return string;
    }

    public static String readData(byte[] value) throws UnsupportedEncodingException {
        String result = new String(value,"UTF-8");
        return filterCode(result);
    }

    public static void main(String[] args) {
        try{
            /* 校验testdata */
            String testdata = "Hello Python!";

            /* 校验testdata signature */
            String signaturedata = readFromFile("sign.txt");
            System.out.println("test data signaturedata\n");
            System.out.println(signaturedata);
            System.out.println("\n");

            String pubkey = readFromFile("./keys/public.pem");

            boolean verifySignatureSuccess =false;
            verifySignatureSuccess = rsaVerify(testdata, signaturedata, pubkey);
            System.out.println("rsaVerify Result: " + verifySignatureSuccess);

            if (!verifySignatureSuccess)
                throw new Exception("testdata verify signature error!");
        }
        catch (Exception e){
            System.out.println(e);
        }

    }
}

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值