How to sign a generic text with RSA key and encode with Base64 in Java?

拈花ヽ惹草 提交于 2019-12-01 10:43:50

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.

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

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!