如何使用 RSA 密钥签署通用文本并在 Java 中使用 Base64 进行编码? [英] How to sign a generic text with RSA key and encode with Base64 in Java?

查看:37
本文介绍了如何使用 RSA 密钥签署通用文本并在 Java 中使用 Base64 进行编码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.

这篇关于如何使用 RSA 密钥签署通用文本并在 Java 中使用 Base64 进行编码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆