本文主要是介绍数字签字RSA,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
package 数字签字;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.Signature;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;import org.apache.commons.codec.binary.Hex;public class RSA {
private static String src="imooc";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 pkcs8=new PKCS8EncodedKeySpec(rsaPrivateKey.getEncoded());KeyFactory keyFactory=KeyFactory.getInstance("RSA");PrivateKey privateKey=keyFactory.generatePrivate(pkcs8);Signature signature=Signature.getInstance("MD5withRSA");//初始化signaturesignature.initSign(privateKey);signature.update(src.getBytes());byte[]result=signature.sign();System.out.println("jdk RSA:"+Hex.encodeHexString(result));//验证签名X509EncodedKeySpec x509EncodedKeySpec=new X509EncodedKeySpec(rsaPublicKey.getEncoded());KeyFactory keyFactory2=KeyFactory.getInstance("RSA");PublicKey publicKey=keyFactory2.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 blocke.printStackTrace();}}}
这篇关于数字签字RSA的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!