package com.yjm.test509; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.security.InvalidKeyException; import java.security.Key; import java.security.KeyFactory; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.PrivateKey; import java.security.Signature; import java.security.SignatureException; import java.security.UnrecoverableKeyException; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; 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 javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; public class Test { public static void main(String[] args) { // test(); // test1(); // test2(); // test3(); // test4(); test5(); } private static void test5() { try { // RSA 密钥对 用私钥签名用公钥验签 KeyPairGenerator keyPairGenerator = KeyPairGenerator .getInstance("RSA"); keyPairGenerator.initialize(1024); KeyPair keyPair = keyPairGenerator.generateKeyPair(); // 获得公钥私钥 RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic(); RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate(); //获得签名算法 Signature signature = Signature.getInstance("MD5withRSA"); //对数据进行签名 signature.initSign(rsaPrivateKey); signature.update("test".getBytes()); byte[] b=signature.sign(); System.out.println("签名之后的串"+new String(b)); //对传输的数据进行验签 signature.initVerify(rsaPublicKey); signature.update("test".getBytes()); boolean boolea = signature.verify(b); //输出验签结果 System.out.println("验签结果: "+boolea); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (SignatureException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } }
输出结果
签名之后的串s[GQ-rmUD" Iid
c^# 2gi9n&qJFfHhTY<+g
8l#Bz11v_(L
验签结果: true