如何在Java中的字符串上应用MD5withRSA

时间:2019-02-07 05:27:22

标签: java cryptography certificate rsa md5

我是实用密码学的新手。 我正在使用第三部分API服务器,我应该对发送到API的所有内容(字符串参数的串联)进行签名。为此,他们根据我的公钥给了我证书。现在,我应该在字符串上应用MD5withRSA并在结果上应用Base64。这将是API服务器最终检查的sign参数。我不怎么用Java做到这一点。我将不胜感激。

1 个答案:

答案 0 :(得分:0)

我做到了。

import java.io.*;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;

public class Main {
    private final static String PRIVATE_KEY = "-----BEGIN PRIVATE KEY-----\n" +
            "??????????????????????????????????????\n" +
            "??????????????????????????????????????\n" +
            "??????????????????????????????????????\n" +
            "???????????????????????" +
            "-----END PRIVATE KEY-----";
    public static void main(String[] args) throws Exception {
        String concatedString = "agent:1af:topup:999756:10.00:08/02/2019 09:57:40";
        StringBuilder pkcs8Lines = new StringBuilder();
        BufferedReader rdr = new BufferedReader(new StringReader(PRIVATE_KEY));
        String line;
        while ((line = rdr.readLine()) != null) {
            pkcs8Lines.append(line);
        }
        String pkcs8Pem = pkcs8Lines.toString();
        pkcs8Pem = pkcs8Pem.replace("-----BEGIN PRIVATE KEY-----", "");
        pkcs8Pem = pkcs8Pem.replace("-----END PRIVATE KEY-----", "");
        pkcs8Pem = pkcs8Pem.replaceAll("\\s+","");

        byte [] pkcs8EncodedBytes = Base64.getDecoder().decode(pkcs8Pem);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pkcs8EncodedBytes);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        PrivateKey privKey = kf.generatePrivate(keySpec);
        Signature md5withrsa = Signature.getInstance("MD5withRSA");
        md5withrsa.initSign(privKey);

        md5withrsa.update(concatedString.getBytes());
        byte[] res = md5withrsa.sign();
        System.out.println(Base64.getEncoder().encodeToString(res));


    }
}