JAVA Asymmetric Encryption algorithm RSA

Source: Internet
Author: User
Tags decrypt hmac md5 encryption asymmetric encryption

Asymmetric encryption algorithm RSA process: A case of both sides of A and B
1. Initialize key building key pair, generate public key, save private key to Keymap
Keypairgenerator---> KeyPair-rsapublickey, Rsaprivatekey
2, party a use private key encryption, after encryption in the private key to the encryption data signature, and then sent to party B
Rsacoder.encryptbyprivatekey (data, Privatekey);
Rsacoder.sign (Encodeddata, Privatekey);
3, the party B verifies the signed encrypted data through the public key, if the authentication is correct, decrypts the encrypted data through the public key
Rsacoder.verify (Encodeddata, PublicKey, sign);
Rsacoder.decryptbypublickey (Encodeddata, PublicKey);
4. Party B is sent to party A through public key encryption
Rsacoder.encryptbypublickey (Decodeddata, PublicKey);
5, the party to decrypt the data through the private key
Rsacoder.decryptprivatekey (Encodeddata, Privatekey);
The flowchart is as follows:

The Java code is implemented as follows:

Package Com.bank.utils;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;public Abstract class Coder {public static final string Key_sha = "SHA";p ublic 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";/** * BASE6 4 decryption * @param key * @return * @throws Exception */public static byte[] decryptBASE64 (String key) throws Exception{return (New Base64decoder ()). Decodebuffer (key);} /** * BASE64 Encryption * @param key * @return * @throws Exception */public static String encryptBASE64 (byte[] key) throws Excepti On{return (New Base64encoder ()). Encodebuffer (key);} /** * MD5 Encryption * @param data * @return * @throws Exception */public static byte[] 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 byte[] 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 Exc Eption{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, S Tring key) throws Exception{secretkey Secretkey = new Secretkeyspec (decryptBASE64 (key), KEY_MAC); Mac Mac = Mac.getinstance (Secretkey.getalgorithm ()); Mac.init (Secretkey); return mac.dofinal (data);}}

Package Com.bank.utils;import Java.security.key;import Java.security.keyfactory;import Java.security.KeyPair; Import Java.security.keypairgenerator;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.pkcs8encodedkeyspec;import Java.security.spec.x509encodedkeyspec;import Java.util.hashmap;import Java.util.map;import Javax.crypto.Cipher; Public abstract class Rsacoder extends Coder{public static final string key_algorithm = "RSA";p ublic static final string S Ignature_algorithm = "Md5withrsa";p rivate static final String public_key = "Rsapublickey";p rivate static final string PRIV Ate_key = "Rsaprivatekey";/** * Digitally sign information with private key * @param data encrypted * @param privatekey private key * @return * @throws Exception */pub Lic static string sign (byte[] data, String privatekey) throws Exception {//Decrypt the private key base64 encoded by byte[] keybytes = decryptBASE64 (P Rivatekey); PKCS8Encodedkeyspec Pkcs8encodedkeyspec = new Pkcs8encodedkeyspec (keybytes); Keyfactory keyfactory = keyfactory.getinstance (key_algorithm);//Take private Key object Privatekey PKey = Keyfactory.generateprivate ( PKCS8ENCODEDKEYSPEC);//Generate a digital signature with the private key signature signature = Signature.getinstance (signature_algorithm); Signature.initsign (PKey); signature.update (data); return encryptBASE64 (Signature.sign ());} /** * Verify Digital signature * @param data encryption * @param publickey Public key * @param sign Digital signature * @return * @throws Exception */public Static Boo Lean verify (byte[] data, string publickey, String sign) throws exception{//decrypt the public key base64 encoded byte[] Keybytes = decryptBASE64 ( PublicKey); X509encodedkeyspec KeySpec = new X509encodedkeyspec (keybytes); Keyfactory keyfactory = keyfactory.getinstance (key_algorithm);//Take public key object PublicKey PKey = Keyfactory.generatepublic ( KEYSPEC); Signature Signature = signature.getinstance (signature_algorithm); signature.initverify (PKey); Signature.update (data );//Verify that the signature is normal return signature.verify (decryptBASE64 (sign));} /** * decryption * decryption with private key * @pAram Data Encryption * @param key * @return * @throws Exception */public static byte[] Decryptprivatekey (byte[] data, String key ) throws exception{byte[] Keybytes = decryptBASE64 (key);//Get private key pkcs8encodedkeyspec Encodedkeyspec = new Pkcs8encodedkeyspec (keybytes); Keyfactory factory = keyfactory.getinstance (Key_algorithm); Key PKey = factory.generateprivate (ENCODEDKEYSPEC);//decryption of data cipher cipher = Cipher.getinstance (Factory.getalgorithm ()) ; Cipher.init (Cipher.decrypt_mode, PKey); return cipher.dofinal (data);} /** * Decrypted with public key * @param data * @param key * @return * @throws Exception */public static byte[] Decryptbypublickey (byte[] Dat A, String key) throws exception{//decryption byte[] keybytes = decryptBASE64 (key);//Get public key x509encodedkeyspec KeySpec = new X509encod Edkeyspec (keybytes); Keyfactory keyfactory = keyfactory.getinstance (key_algorithm); Key PKey = Keyfactory.generatepublic (KEYSPEC);//decryption of data cipher cipher = Cipher.getinstance (Keyfactory.getalgorithm ()); Cipher.init (Cipher.decrypt_mode, PKey); return cipher.dofinal (data);} /** * Encrypted with public key * @param data * @param key * @return * @throws Exception */public static byte[] Encryptbypublickey (byte[] Dat A, String key) throws exception{byte[] Keybytes = decryptBASE64 (key); X509encodedkeyspec KeySpec = new X509encodedkeyspec (keybytes); Keyfactory keyfactory = keyfactory.getinstance (key_algorithm); Key PKey = Keyfactory.generatepublic (KeySpec); Cipher Cipher = cipher.getinstance (Keyfactory.getalgorithm ()); Cipher.init (Cipher.encrypt_mode, PKey); return Cipher.dofinal (data);} /** * Encrypted with private key * @param data * @param key * @return * @throws Exception */public static byte[] Encryptbyprivatekey (byte[] Dat A, String key) throws exception{byte[] Keybytes = decryptBASE64 (key); Pkcs8encodedkeyspec KeySpec = new Pkcs8encodedkeyspec (keybytes); Keyfactory keyfactory = keyfactory.getinstance (key_algorithm); Key Privatekey = keyfactory.generateprivate (KeySpec); Cipher Cipher = cipher.getinstance (Keyfactory.getalgorithm ()); Cipher.init (Cipher.encrypt_mode, Privatekey); return Cipher.dofinal (DATa);} /** * Get the private key * @param keyMap * @return * @throws Exception */public static String Getprivatekey (map<string, object> K Eymap) throws Exception{key Key = (key) keymap.get (Private_key); return encryptBASE64 (key.getencoded ());} /** * Get Public key * @param keyMap * @return * @throws Exception */public static String Getpublickey (map<string, object> ke YMAP) throws Exception{key Key = (key) keymap.get (Public_key); return encryptBASE64 (key.getencoded ());} /** * Initialize key * @return * @throws Exception */public static map<string, object> Initkey () throws Exception{keypairgene Rator keypairgenerator = keypairgenerator.getinstance (key_algorithm); keypairgenerator.initialize (1024); KeyPair KeyPair = Keypairgenerator.generatekeypair ();//Public key Rsapublickey PublicKey = (rsapublickey) keypair.getpublic () ;//private key Rsaprivatekey Privatekey = (rsaprivatekey) keypair.getprivate (); map<string, object> keyMap = new hashmap<string, object> (2); Keymap.put (Private_key, Privatekey); Keymap.put (Public_key, PubliCkey); return keyMap;}} 

Package Com.bank.test;import Java.util.map;import org.junit.assert;import org.junit.before;import org.junit.Test; Import Com.bank.utils.rsacoder;public class Rsacodertest {private string publickey;private string privatekey;/* * Asymmetric encryption algorithm RSA process: Take the two sides as an example * 1, initialize key building key pair, generate public key, private key saved to Keymap * keypairgenerator--->keypair-->rsapublickey, rsaprivat EKey * 2, party A uses the private key encryption, after encryption in the private key to encrypt the data to sign data, and then sent to party B * Rsacoder.encryptbyprivatekey (data, Privatekey); * Rsacoder.sign (Encodeddata, Privatekey); * 3, the party B verifies the signed encrypted data through the public key, if the authentication is correct, the encrypted data is decrypted by the public key * Rsacoder.verify (Encodeddata, PublicKey, sign); * Rsacoder.decryptbypublickey (Encodeddata, PublicKey); * * 4, Party B in the public key encryption sent to party A * Rsacoder.encryptbypublickey (Decodeddata, PublicKey); * 5, the party to decrypt the data by private key * Rsacoder.decryptprivatekey (Encodeddata, Privatekey); */@Beforepublic void SetUp () throws Exception {map<string, object> keyMap = Rsacoder.initkey ();p Ublickey = Rsacoder . Getpublickey (KEYMAP);p Rivatekey = Rsacoder.getprivatekey (KEYMAP); SYSTEM.OUT.PRINTLN ("Public key: \ n" + PUBlickey); SYSTEM.OUT.PRINTLN ("private key: \ n" + Privatekey);} @Testpublic void Test () throws exception{string inputstr = "abc"; byte[] data = Inputstr.getbytes ();//The resulting byte array is not the same each time. Second step private key encryption byte[] Encodeddata = Rsacoder.encryptbyprivatekey (data, privatekey);//private key for data signing string sign = Rsacoder.sign ( Encodeddata, Privatekey);//Third Step public key authentication Digital Signature Boolean flag = Rsacoder.verify (Encodeddata, PublicKey, sign); System.out.println ("flag:" + flag);//Decrypt data with public key byte[] Decodeddata = Rsacoder.decryptbypublickey (Encodeddata, PublicKey ); SYSTEM.OUT.PRINTLN ("Data:" + data + "Encrypt": "+ Encodeddata +" Decrypt data: "+ decodeddata); System.out.println ("Pre-encryption data-:" + new String (data) + "decrypted" + new string (Decodeddata));//Fourth step using public key to encrypt data Encodeddata = RSA Coder.encryptbypublickey (Decodeddata, PublicKey);//The fifth step uses the private key to decrypt the data Decodeddata = Rsacoder.decryptprivatekey ( Encodeddata, Privatekey); SYSTEM.OUT.PRINTLN ("Data:" + data + "Encrypt": "+ Encodeddata +" Decrypt data: "+ decodeddata); System.out.println ("Pre-encryption Data:" + INPUTSTR + "decrypted data:" + new String (decoDeddata));} @Testpublic void Test1 () throws Exception{system.out.println ("private key encryption-----Public key decryption"); String INPUTSTR = "abc"; byte[] data = Inputstr.getbytes (); SYSTEM.OUT.PRINTLN ("Data:" + data); byte[] Encodeddata = Rsacoder.encryptbyprivatekey (data, Privatekey); byte[] Decodeddata = Rsacoder.decryptbypublickey (Encodeddata, PublicKey); String outputstr = new string (decodeddata); System.out.println ("Before encryption:" + inputstr + "\ n decrypted:" + outputstr); Assert.assertequals (Inputstr, OUTPUTSTR); SYSTEM.OUT.PRINTLN ("Private key signature---Public key authentication signature");//generate signature String sign = Rsacoder.sign (Encodeddata, Privatekey); System.out.println ("signature: \ r" + sign);//Verify signature Boolean flag = Rsacoder.verify (Encodeddata, PublicKey, sign); System.out.println ("Status: \ r" + flag); Assert.asserttrue (flag);}}

  

JAVA Asymmetric Encryption algorithm RSA

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.