Before building the Java code implementation, we need to complete the production of the certificate.
1. Generate the Keystroe file
Execute the following command at the command line:
Keytool-genkey-validity 36000-alias jlxrsa-keyalg rsa-keystore d:\jlxrsz.keystore
which
-genkey indicates that the key is generated
-validity Specify the certificate validity period, this is 36000 days
-alias Specifies the alias, this is www.zlex.org
-keyalg Specifies the algorithm, here is the RSA
-keystore Specify the storage location, this is d:\zlex.keystore
Here I use the password for 123456
2. Generate a self-signed certificate
Light has KeyStore file is not enough, also need certificate file, certificate is directly provided to the outside public key credentials.
To export a certificate:
Keytool-export-keystore D:\jlxrsa.keystore-alias Jlxrsa-file D:\JLXRSA.CER-RFC
which
-export specified as an export operation
-keystore specifying keystore files
-alias specifying an alias in the export KeyStore file
-file pointing to the export path
-rfc output in text format, i.e. output in BASE64 encoding
The code here is 123456 .
Ok, get ready to finish, start Java implementation!
Package Cert;import Java.security.MessageDigest; Import Javax.crypto.KeyGenerator; Import Javax.crypto.Mac; Import Javax.crypto.SecretKey; Import Javax.crypto.spec.secretkeyspec;import Sun.misc.BASE64Decoder; Import Sun.misc.BASE64Encoder; /** * Basic Cryptographic components * * @author * @version 1.0 * @since 1.0 * * Public abstract class Coder {public static final STR ing Key_sha = "SHA"; public static final String key_md5 = "MD5"; /** * Mac algorithm can choose the following algorithms * * <pre> * HmacMD5 * HmacSHA1 * HmacSHA256 * HmacSHA384 * HMACSHA512 * </pre> * * public static final String Key_mac = "HmacMD5"; /** * BASE64 Decryption * * @param key * @return * @throws Exception */public static byte[] de CryptBASE64 (String key) throws Exception {return (new Base64decoder ()). Decodebuffer (key); }/** * BASE64 encryption * * @param key * @return * @throws exception */public static String encryptBASE64 (byte[] key) throws Exception {return (new Base64encoder ()). Enc Odebuffer (key); }/** * MD5 encryption * * @param data * @return * @throws Exception */public static by Te[] EncryptMD5 (byte[] data) throws Exception {messagedigest MD5 = messagedigest.getinstance (KEY_MD5); Md5.update (data); return Md5.digest (); }/** * SHA encryption * * @param data * @return * @throws Exception */public static by Te[] Encryptsha (byte[] data) throws Exception {MessageDigest sha = messagedigest.getinstance (Key_sha); Sha.update (data); return Sha.digest (); }/** * Initialize HMAC key * * @return * @throws Exception */public static String Initmackey () throws Exception {Keygenerator keygenerator = keygenerator.getinstance (KEY_MAC); Secretkey secretkey = KeYgenerator.generatekey (); Return encryptBASE64 (secretkey.getencoded ()); }/** * HMAC encryption * * @param data * @param key * @return * @throws Exception */ public static byte[] Encrypthmac (byte[] data, String key) throws Exception {Secretkey Secretkey = new Secre Tkeyspec (decryptBASE64 (key), KEY_MAC); Mac Mac = Mac.getinstance (Secretkey.getalgorithm ()); Mac.init (Secretkey); return mac.dofinal (data); } }
Package Cert;import Java.io.fileinputstream;import Java.security.keystore;import java.security.privatekey;import Java.security.publickey;import Java.security.signature;import Java.security.cert.certificate;import Java.security.cert.certificatefactory;import Java.security.cert.x509certificate;import Java.util.Date;import javax.crypto.cipher;/** * Certificate Component * * @author * @version 1.0 * @since 1.0 */public abstract class Certificatecoder extends Coder {/** * java KeyStore (Java key store,jks) Key_store */public static final String Key_store = "JKS";p ublic static final Strin G X509 = "n";/** * obtains private key from KeyStore * * @param keystorepath * @param alias * @param password * @return * @throws Excepti On */private static Privatekey Getprivatekey (String keystorepath, string alias,string password) throws Exception {Keystor E ks = getkeystore (keystorepath, password); Privatekey key = (Privatekey) ks.getkey (alias, Password.tochararray ()); return key;} /** * obtained public key by certificate * * @param certificatepath * @return * @tHrows Exception */private static PublicKey Getpublickey (String certificatepath) throws Exception {Certificate Certificate = getcertificate (Certificatepath); PublicKey key = Certificate.getpublickey (); return key;} /** * Get Certificate * * @param certificatepath * @return * @throws Exception */private static Certificate getcertificate ( String Certificatepath) throws Exception {certificatefactory certificatefactory = certificatefactory.getinstance (X509 ); FileInputStream in = new FileInputStream (Certificatepath); Certificate Certificate = Certificatefactory.generatecertificate (in); In.close (); return Certificate;} /** * Get certificate * * @param keystorepath * @param alias * @param password * @return * @throws Exception */private Stat IC Certificate getcertificate (String keystorepath,string Alias, string password) throws Exception {KeyStore KS = Getkeysto Re (keystorepath, password); Certificate Certificate = ks.getcertificate (alias); return Certificate;} /** * Get keystore * * @param keystorepath * @param Password * @return * @throws Exception */private static KeyStore Getkeystore (string keystorepath, string password) throws Exception {FileInputStream is = new FileInputStream (Keystorepath); KeyStore ks = keystore.getinstance (Key_store); Ks.load (is, Password.tochararray ()); Is.close (); return KS;} /** * Private Key Encryption * * @param data * @param keystorepath * @param alias * @param password * @return * @throws Exception */public Static byte[] Encryptbyprivatekey (byte[] data, string keystorepath,string Alias, string password) throws Exception {//Get private Key Privatekey Privatekey = Getprivatekey (Keystorepath, alias, password);//Data encryption cipher cipher = Cipher.getinstance ( Privatekey.getalgorithm ()); Cipher.init (Cipher.encrypt_mode, Privatekey); return cipher.dofinal (data);} /** * Private Key decryption * * @param data * @param keystorepath * @param alias * @param password * @return * @throws Exception */public Static byte[] Decryptbyprivatekey (byte[] data, string keystorepath,string Alias, string password) throws Exception {//Get private Key PrivaTekey Privatekey = Getprivatekey (Keystorepath, alias, password);//Data encryption cipher cipher = Cipher.getinstance ( Privatekey.getalgorithm ()); Cipher.init (Cipher.decrypt_mode, Privatekey); return cipher.dofinal (data);} /** * Public Key Encryption * * @param data * @param certificatepath * @return * @throws Exception */public static byte[] Encryptbypublick EY (byte[] data, String Certificatepath) throws Exception {//Get public key PublicKey PublicKey = Getpublickey (Certificatepath);// Data encryption Cipher cipher = Cipher.getinstance (Publickey.getalgorithm ()); Cipher.init (Cipher.encrypt_mode, PublicKey); return cipher.dofinal (data);} /** * Public Key decryption * * @param data * @param certificatepath * @return * @throws Exception */public static byte[] Decryptbypublick EY (byte[] data, String Certificatepath) throws Exception {//Get public key PublicKey PublicKey = Getpublickey (Certificatepath);// Data encryption Cipher cipher = Cipher.getinstance (Publickey.getalgorithm ()); Cipher.init (Cipher.decrypt_mode, PublicKey); return cipher.dofinal (data);} /** * Verify Certificate * * @paramCertificatepath * @return */public static Boolean verifycertificate (String certificatepath) {return verifycertificate ( New Date (), Certificatepath);} /** * Verify that the certificate is expired or invalid * * @param date * @param certificatepath * @return */public static Boolean verifycertificate (D Ate date, String Certificatepath) {Boolean status = true;try {//Get certificate Certificate Certificate = getcertificate (certificatep ATH);//Verify that the certificate is expired or invalid status = Verifycertificate (date, certificate);} catch (Exception e) {status = FALSE;} return status;} /** * Verify that the certificate is expired or invalid * * @param date * @param certificate * @return */private static Boolean verifycertificate (date date, Ce Rtificate certificate) {Boolean status = true;try {x509certificate x509certificate = (x509certificate) certificate; X509certificate.checkvalidity (date);} catch (Exception e) {status = FALSE;} return status;} /** * Signature * * @param keystorepath * @param alias * @param password * * @return * @throws Exception */public static String Sign (byte[) sign, String Keystorepath,String alias,string password) throws Exception {//Get certificate X509Certificate x509certificate = (x509certificate) GetCertificate (Keystorepath, alias, password);//Get private key KeyStore KS = Getkeystore (keystorepath, password);// Get the private key privatekey Privatekey = (privatekey) Ks.getkey (Alias,password.tochararray ());//build signature Signature Signature = Signature.getinstance (X509certificate.getsigalgname ()); Signature.initsign (Privatekey); signature.update (sign); Return encryptBASE64 (Signature.sign ());} /** * Verify Signature * * @param data * @param sign * @param certificatepath * @return * @throws Exception */public Static Boolean V Erify (byte[] data, String sign,string Certificatepath) throws Exception {//Get certificate X509Certificate x509certificate = (x509ce rtificate) getcertificate (Certificatepath);//Get public key PublicKey PublicKey = X509certificate.getpublickey ();// Build Signature Signature Signature = Signature.getinstance (X509certificate.getsigalgname ()); signature.initverify (PublicKey); Signature.update (data); return signature.verify (decryptBASE64 (sign));} /** * Verify Certificate * * @param keystorepath * @param alias * @param password * @return */public static Boolean Verifycert Ificate (date date, string keystorepath,string Alias, string password) {Boolean status = true;try {Certificate Certificate = GetCertificate (Keystorepath, alias,password); status = Verifycertificate (date, certificate);} catch (Exception e) {status = FALSE;} return status;} /** * Verify Certificate * * @param keystorepath * @param alias * @param password * @return */public static Boolean Verifycert Ificate (String keystorepath, string alias,string password) {return verifycertificate (new Date (), Keystorepath, alias, password);}}
Package Cert;import static Org.junit.assert.*;import org.junit.Test; /** * * @author * @version 1.0 * @since 1.0 */public class Certificatecodertest {private String password = " 123456 "; Private String alias = "Jlxrsa"; Private String Certificatepath = "D:/jlx.cer"; Private String Keystorepath = "D:/jlx.keystore"; @Test public void Test () throws Exception {System.err.println ("Key cryptography-private key decryption"); String inputstr = "Ceritifcate"; byte[] data = Inputstr.getbytes (); Byte[] Encrypt = certificatecoder.encryptbypublickey (data, Certificatepath); Byte[] Decrypt = Certificatecoder.decryptbyprivatekey (encrypt, Keystorepath, alias, password); String outputstr = new string (decrypt); System.err.println ("Before encryption:" + Inputstr + "\n\r" + "after decryption:" + outputstr); Verify data consistency assertarrayequals (data, decrypt); Verify that the certificate is valid Asserttrue (certifIcatecoder.verifycertificate (Certificatepath)); } @Test public void Testsign () throws Exception {System.err.println ("private key encryption-key decryption"); String inputstr = "sign"; byte[] data = Inputstr.getbytes (); byte[] Encodeddata = Certificatecoder.encryptbyprivatekey (data, Keystorepath, alias, password); byte[] Decodeddata = Certificatecoder.decryptbypublickey (Encodeddata, Certificatepath); String outputstr = new string (decodeddata); System.err.println ("Before encryption:" + Inputstr + "\n\r" + "after decryption:" + outputstr); Assertequals (Inputstr, OUTPUTSTR); SYSTEM.ERR.PRINTLN ("Private key signature--public key verification signature"); Generate signature String sign = certificatecoder.sign (Encodeddata, Keystorepath, alias, password); System.err.println ("signature: \ r" + sign); Verify that the signature is Boolean status = Certificatecoder.verify (Encodeddata, sign, certificatepath); System.err.println ("Status: \ r" + status); Asserttrue (status); } }
Java Digital certificate