最近有篇计算机网络的论文,准备写一下数字签名这个知识点。没有我想象的那么简单。。。
RSA这个算法在学数论的时候学习了,不过并不是用来学习加密的,而是学习了里面的中国剩余定理和费马小定理,跨越千年的算法这一篇文章讲的很不错,建议大家看一下:
我写的这个代码只是调用了java jdk里面的方法,并没有去实现这个加密算法。有需要的可以看一下。
代码:
package Signature;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
public class RSA {
private static String src = "CYK";
public static void main(String[] args) {
// TODO Auto-generated method stub
jdkRSA();
}
public static void jdkRSA() {
try {
//1.初始化秘钥
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(512);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
//用作验证 公钥
RSAPublicKey rsaPublicKey = (RSAPublicKey)keyPair.getPublic();
//用作签名 私钥
RSAPrivateKey rsaPrivateKey = (RSAPrivateKey)keyPair.getPrivate();
//2.执行签名
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(rsaPrivateKey.getEncoded());
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
//签名对象
Signature signature = Signature.getInstance("MD5withRSA");
//签名对象的初始化方法
signature.initSign(privateKey);
signature.update(src.getBytes());
byte[] result = signature.sign();
System.out.println("jdk rsa sign:" + result);
//3.验证签名
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(rsaPublicKey.getEncoded());
keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
signature = Signature.getInstance("MD5withRSA");
signature.initVerify(publicKey);
signature.update(src.getBytes());
boolean bool = signature.verify(result);
System.out.println("jdk rsa verify:" + bool);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}