首页 > 编程语言 > 详细

数字签名算法--1.RSA算法代码

时间:2015-03-15 19:51:03      阅读:352      评论:0      收藏:0      [点我收藏+]
package Imooc;


import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.security.Signature;


import com.sun.org.apache.xerces.internal.impl.dv.util.HexBin;
//import com.sun.org.apache.bcel.internal.classfile.Signature;


public class ImoocRSA {


private static String src = "imooc security rsa";
public static void main(String[] args) {
jdkRSA();
}
public static void jdkRSA()
{
//1.初始化密钥

try {
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 :" + HexBin.encode(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();
}

}
}

数字签名算法--1.RSA算法代码

原文:http://blog.csdn.net/u013218720/article/details/44279443

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!