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. Initializing the key
try {
Keypairgenerator keypairgenerator = keypairgenerator. getinstance ("RSA");
Keypairgenerator.initialize (512);
KeyPair KeyPair = Keypairgenerator.generatekeypair ();
Rsapublickey Rsapublickey = (rsapublickey) keypair.getpublic ();
Rsaprivatekey Rsaprivatekey = (rsaprivatekey) keypair.getprivate ();
2. Execute signature
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. Verifying the signature
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 ();
}
}
}
Digital Signature Algorithm--1. RSA Algorithm Code