如何使用 RSA 密钥签署通用文本并在 Java 中使用 Base64 进行编码?

2022-01-21 00:00:00 encryption sign base64 rsa java

I have the following code in bash:

signed_request = $(printf "PLAIN TEXT REQUEST" | 
openssl rsautl -sign -inkey "keyfile.pem" | openssl enc -base64 | _chomp )

Basically, this code takes a plain text, signs it with a private key and encodes using Base64

How could I do a code with exactly the same functionality in Java?

解决方案

You can use JDK security API. Take a look at this working sample, hope it can get you started:

  public static void main(String[] args) throws Exception {
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    kpg.initialize(1024);
    KeyPair keyPair = kpg.genKeyPair();

    byte[] data = "test".getBytes("UTF8");

    Signature sig = Signature.getInstance("MD5WithRSA");
    sig.initSign(keyPair.getPrivate());
    sig.update(data);
    byte[] signatureBytes = sig.sign();
    System.out.println("Singature:" + new BASE64Encoder().encode(signatureBytes));

    sig.initVerify(keyPair.getPublic());
    sig.update(data);

    System.out.println(sig.verify(signatureBytes));
  }

EDIT: The example above uses internal Sun's encoder (sun.misc.BASE64Encoder). It is best to use something like Base64 from Commons Codec.

相关文章