How to sign a generic text with RSA key and encode

2019-02-20 00:17发布

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?

3条回答
The star\"
2楼-- · 2019-02-20 00:44

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.

查看更多
趁早两清
3楼-- · 2019-02-20 00:55

I copy the link @Aqua posted as a new answer, because I think it's FAR more useful than any of the answers given yet. Use THIS to read/write private/public keys from files: http://codeartisan.blogspot.ru/2009/05/public-key-cryptography-in-java.html

The link doesn't say anythig about signing and verifying, but signing is a lot easier. I used this code to sign:

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

    signature.update("text to sign".getBytes());
    signature.sign();

And to verify:

    Signature signature = Signature.getInstance("SHA256WithRSA");
    signature.initVerify(publicKey);
    signature.update("text to sign".getBytes);
    signature.verify(signatureMadeEarlier);
查看更多
Deceive 欺骗
4楼-- · 2019-02-20 00:56

Also, you can use not-yet-commons-ssl to obtain the private key from a file and encode using org.apache.commons.ssl.Base64. Using Max's example:

import java.security.Signature;
import org.apache.commons.ssl.Base64;
import org.apache.commons.ssl.PKCS8Key;

// [...]

PKCS8Key pkcs8 = new PKCS8Key(new FileInputStream("keyfile.pem"),
                              "changeit".toCharArray());

Signature sig = Signature.getInstance("MD5WithRSA");
sig.initSign(pkcs8.getPrivateKey());
sig.update(data);
byte[] signatureBytes = sig.sign();

System.out.println("Singature: " +
                   Base64.encodeBase64String(signatureBytes));
查看更多
登录 后发表回答