如何使用私钥对字符串进行签名 [英] How to sign string with private key
本文介绍了如何使用私钥对字符串进行签名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我已将私钥设为 byte []
SHA1withRSA 获取字符串的签名? >或字符串
?
How can I get the signature of a string using SHA1withRSA
if I already have the Private Key as byte[]
or String
?
推荐答案
我想你说的是你知道的密钥对然后想要签名/验证。
I guess what you say is you know the key pair before hand and want to sign/verify with that.
请参阅以下代码。
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.Signature;
import sun.misc.BASE64Encoder;
public class MainClass {
public static void main(String[] args) throws Exception {
KeyPair keyPair = getKeyPair();
byte[] data = "test".getBytes("UTF8");
Signature sig = Signature.getInstance("SHA1WithRSA");
sig.initSign(keyPair.getPrivate());
sig.update(data);
byte[] signatureBytes = sig.sign();
System.out.println("Signature:" + new BASE64Encoder().encode(signatureBytes));
sig.initVerify(keyPair.getPublic());
sig.update(data);
System.out.println(sig.verify(signatureBytes));
}
private static KeyPair getKeyPair() throws NoSuchAlgorithmException {
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(1024);
return kpg.genKeyPair();
}
}
在这里你需要将方法getKeyPair()更改为提供您已知的密钥对。您可以从Java密钥库[JKS]加载它。
Here you need to change the method getKeyPair() to supply your known key pair. You may load it from a java key store [JKS].
您不能将任意字节数组作为公钥或私钥。它们应该是相关的。
You can't just have an arbitrary byte array either as your public key or private key. They should be generated in relation.
这篇关于如何使用私钥对字符串进行签名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文