如何签订RSA密钥和连接在Java中使用Base64 code通用的文字? [英] How to sign a generic text with RSA key and encode with Base64 in Java?

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

问题描述

我在bash下面code:

I have the following code in bash:

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

基本上,这code采用纯文本,使用私钥和连接codeS Base64编码使用它的标志

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

我怎么会做一个code正好与在Java中相同的功能?

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

推荐答案

您可以使用的 JDK安全API 。看看这方面的工作样品,希望它可以让你开始:

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));
  }

编辑:
上面的例子使用的内部Sun的EN codeR( sun.misc.BASE64En codeR )。最好是使用类似的> Base64的共享codeC 。

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 code通用的文字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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