如何在Java中发送和接收DSA公共/私人签名消息
我找不到任何关于如何在Java中交换公钥/私钥签名消息的好(完整)文档 我还没有找到关于使用DSA生成公钥和私钥、对字节[]签名并进行验证所需的最低步骤的简明文档如何在Java中发送和接收DSA公共/私人签名消息,java,public-key-encryption,encryption-asymmetric,dsa,Java,Public Key Encryption,Encryption Asymmetric,Dsa,我找不到任何关于如何在Java中交换公钥/私钥签名消息的好(完整)文档 我还没有找到关于使用DSA生成公钥和私钥、对字节[]签名并进行验证所需的最低步骤的简明文档 来自Oracle的太分散,需要跨多个JVM运行。我已成功使用私钥对字节数组进行签名,并使用公钥对其进行验证 例如 byte[] data = "hello.".getBytes(); /* Test generating and verifying a DSA signature */ try {
来自Oracle的太分散,需要跨多个JVM运行。我已成功使用私钥对字节数组进行签名,并使用公钥对其进行验证 例如
byte[] data = "hello.".getBytes();
/* Test generating and verifying a DSA signature */
try {
/* generate a key pair */
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA");
keyGen.initialize(1024, new SecureRandom());
KeyPair pair = keyGen.generateKeyPair();
/* create a Signature object to use
* for signing and verifying */
Signature dsa = Signature.getInstance("SHA/DSA");
/* initialize the Signature object for signing */
PrivateKey priv = pair.getPrivate();
dsa.initSign(priv);
/* Update and sign the data */
dsa.update(data);
/* Now that all the data to be signed
* has been read in, sign it */
byte[] sig = dsa.sign();
/* Verify the signature */
/* Initialize the Signature object for verification */
PublicKey pub = pair.getPublic();
dsa.initVerify(pub);
/* Update and verify the data */
dsa.update(data);
boolean verifies = dsa.verify(sig);
Assert.assertTrue(verifies);
} catch (Exception e) {
System.err.println("Caught exception " + e.toString());
}
在这个版本中,我将公钥序列化为一个字节数组,然后从该字节数组创建一个公钥
byte[] data = "hello.".getBytes();
/* Test generating and verifying a DSA signature */
try {
/* generate a key pair */
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA");
keyGen.initialize(1024, new SecureRandom());
KeyPair pair = keyGen.generateKeyPair();
/* create a Signature object to use
* for signing and verifying */
Signature dsa = Signature.getInstance("SHA/DSA");
/* initialize the Signature object for signing */
PrivateKey priv = pair.getPrivate();
dsa.initSign(priv);
/* Update and sign the data */
dsa.update(data);
/* Now that all the data to be signed
* has been read in, sign it */
byte[] sig = dsa.sign();
/* Verify the signature */
/* Initialize the Signature object for verification */
PublicKey pub = pair.getPublic();
/* Encode the public key into a byte array */
byte[] encoded = pub.getEncoded();
/* Get the public key from the encoded byte array */
PublicKey fromEncoded = KeyFactory.getInstance("DSA", "SUN").generatePublic(new X509EncodedKeySpec(encoded));
dsa.initVerify(fromEncoded);
/* Update and verify the data */
dsa.update(data);
boolean verifies = dsa.verify(sig);
Assert.assertTrue(verifies);
} catch (Exception e) {
System.err.println("Caught exception " + e.toString());
}