RSA algorithm JS encrypted Java decryption

Source: Internet
Author: User
Tags assert base64 decrypt decrypt with public key asymmetric encryption

There is such a requirement that the usernamepassword,password of the front-end login must be encrypted. But not to use MD5, because the background to detect the complexity of password, then in the premise of ensuring security password into the background, the answer is to use the RSA Asymmetric encryption algorithm to solve.

Java code

need to rely on Commons-codec package
Rsacoder.java

ImportOrg.apache.commons.codec.binary.Base64;ImportJavax.crypto.Cipher;Importjava.security.*;ImportJava.security.spec.PKCS8EncodedKeySpec;ImportJava.security.spec.X509EncodedKeySpec;ImportJava.util.HashMap;ImportJava.util.Map;/** * Created by Lake on 17-4-12. * * Public  class rsacoder {     Public Static FinalString Key_algorithm ="RSA"; Public Static FinalString Signature_algorithm ="Md5withrsa";Private Static FinalString Public_key ="Rsapublickey";Private Static FinalString Private_key ="Rsaprivatekey"; Public Static byte[]decryptBASE64(String key) {returnBase64.decodebase64 (key); } Public StaticStringencryptBASE64(byte[] bytes) {returnBase64.encodebase64string (bytes); }/** * Digitally sign information with private key * * @param Data encrypted * @param privatekey private key * @retu RN * @throws Exception * *     Public StaticString Sign(byte[] data, String Privatekey)throwsException {//Decrypt private key encoded by Base64        byte[] keybytes = decryptBASE64 (Privatekey);//Construct Pkcs8encodedkeyspec objectPkcs8encodedkeyspec Pkcs8keyspec =NewPkcs8encodedkeyspec (keybytes);//Key_algorithm The specified encryption algorithmKeyfactory keyfactory = keyfactory.getinstance (key_algorithm);//Take private Key ObjectPrivatekey Prikey = keyfactory.generateprivate (Pkcs8keyspec);//Generate digital signatures for information with private keySignature Signature = signature.getinstance (signature_algorithm);        Signature.initsign (Prikey); Signature.update (data);returnEncryptBASE64 (Signature.sign ()); }/** * Verify Digital signature * * @param Data encryption * @param publickey Public key * @param s IGN Digital Signature * @return Verify Success Returns TRUE Failure returns false * @throws Exception * /     Public Static Boolean Verify(byte[] Data, string publickey, string sign)throwsException {//Decrypt the public key encoded by Base64        byte[] keybytes = decryptBASE64 (PublicKey);//Construct X509encodedkeyspec objectX509encodedkeyspec KeySpec =NewX509encodedkeyspec (keybytes);//Key_algorithm The specified encryption algorithmKeyfactory keyfactory = keyfactory.getinstance (key_algorithm);//Take the Public key objectPublicKey PubKey = Keyfactory.generatepublic (KeySpec);        Signature Signature = signature.getinstance (signature_algorithm);        Signature.initverify (PubKey); Signature.update (data);//Verify that the signature is normal        returnSignature.verify (decryptBASE64 (sign)); } Public Static byte[]Decryptbyprivatekey(byte[] data, String key)throwsexception{//decryption of keys        byte[] keybytes = decryptBASE64 (key);//Get the private keyPkcs8encodedkeyspec Pkcs8keyspec =NewPkcs8encodedkeyspec (keybytes);        Keyfactory keyfactory = keyfactory.getinstance (key_algorithm); Key Privatekey = keyfactory.generateprivate (Pkcs8keyspec);//decryption of dataCipher Cipher = cipher.getinstance (Keyfactory.getalgorithm ()); Cipher.init (Cipher.decrypt_mode, Privatekey);returnCipher.dofinal (data); }/** * Decrypt <br> * Decrypt with private key * * @param data * @param key * @return * @throws Exception * *     Public Static byte[]Decryptbyprivatekey(string data, string key)throwsException {returnDecryptbyprivatekey (decryptBASE64 (data), key); }/** * Decrypt <br> * Decrypt with public key * * @param data * @param key * @return * @throws Exception * *     Public Static byte[]Decryptbypublickey(byte[] data, String key)throwsException {//decryption of keys        byte[] keybytes = decryptBASE64 (key);//Get public keyX509encodedkeyspec X509keyspec =NewX509encodedkeyspec (keybytes);        Keyfactory keyfactory = keyfactory.getinstance (key_algorithm); Key PublicKey = Keyfactory.generatepublic (X509keyspec);//decryption of dataCipher Cipher = cipher.getinstance (Keyfactory.getalgorithm ()); Cipher.init (Cipher.decrypt_mode, PublicKey);returnCipher.dofinal (data); }/** * Encrypt <br> * Encrypt with public key * * @param data * @param key * @return * @throws Exception * *     Public Static byte[]Encryptbypublickey(string data, string key)throwsException {//Decrypt the public key        byte[] keybytes = decryptBASE64 (key);//Get public keyX509encodedkeyspec X509keyspec =NewX509encodedkeyspec (keybytes);        Keyfactory keyfactory = keyfactory.getinstance (key_algorithm); Key PublicKey = Keyfactory.generatepublic (X509keyspec);//Encryption of dataCipher Cipher = cipher.getinstance (Keyfactory.getalgorithm ()); Cipher.init (Cipher.encrypt_mode, PublicKey);returnCipher.dofinal (Data.getbytes ()); }/** * Encrypt <br> * Encrypt with private key * * @param data * @param key * @return * @throws Exception * *     Public Static byte[]Encryptbyprivatekey(byte[] data, String key)throwsException {//decryption of keys        byte[] keybytes = decryptBASE64 (key);//Get the private keyPkcs8encodedkeyspec Pkcs8keyspec =NewPkcs8encodedkeyspec (keybytes);        Keyfactory keyfactory = keyfactory.getinstance (key_algorithm); Key Privatekey = keyfactory.generateprivate (Pkcs8keyspec);//Encryption of dataCipher Cipher = cipher.getinstance (Keyfactory.getalgorithm ()); Cipher.init (Cipher.encrypt_mode, Privatekey);returnCipher.dofinal (data); }/** * Get the private key * * @param keyMap * @return * @throws Exception */     Public StaticStringGetprivatekey(map<string, key> keyMap)throwsException {Key key = (key) keymap.get (Private_key);returnEncryptBASE64 (key.getencoded ()); }/** * Get public key * * @param keyMap * @return * @throws Exception */      Public StaticStringGetpublickey(map<string, key> keyMap)throwsException {Key key = Keymap.get (Public_key);returnEncryptBASE64 (key.getencoded ()); }/** * Initialize key * * @return * @throws Exception */     Public StaticMap<string, key>Initkey()throwsException {keypairgenerator Keypairgen = keypairgenerator. getinstance (Key_algorithm); Keypairgen.initialize (1024x768);        KeyPair KeyPair = Keypairgen.generatekeypair (); map<string, key> KeyMap =NewHashMap (2); Keymap.put (Public_key, Keypair.getpublic ());//Public keyKeymap.put (Private_key, Keypair.getprivate ());//private key        returnKeyMap; }}

Test class
Rsacodertest.java

ImportOrg.junit.Before;ImportOrg.junit.Test;ImportJava.security.Key;ImportJava.util.Map;Import StaticOrg.junit.Assert.assertEquals;Import StaticOrg.junit.Assert.assertTrue;/** * Created by Lake on 17-4-12. * * Public  class rsacodertest {    PrivateString PublicKey;PrivateString Privatekey;@Before     Public void setUp()throwsException {map<string, key> keyMap = Rsacoder.initkey ();        PublicKey = Rsacoder.getpublickey (KEYMAP);        Privatekey = Rsacoder.getprivatekey (KEYMAP); System.err.println ("Public key: \n\r"+ PublicKey); System.err.println ("Private key: \n\r"+ Privatekey); }@Test     Public void Test()throwsException {System.err.println ("Public key cryptography--private key decryption"); String Inputstr ="ABC";byte[] Encodeddata = Rsacoder.encryptbypublickey (Inputstr, PublicKey);byte[] Decodeddata = Rsacoder.decryptbyprivatekey (Encodeddata, Privatekey); String Outputstr =NewString (Decodeddata); System.err.println ("before encryption:"+ Inputstr +"\n\r"+"After decryption:"+ outputstr);    Assertequals (Inputstr, OUTPUTSTR); }@Test     Public void testsign()throwsException {System.err.println ("Private key encryption--public key decryption"); String Inputstr ="Sign";byte[] data = Inputstr.getbytes ();byte[] Encodeddata = Rsacoder.encryptbyprivatekey (data, Privatekey);byte[] Decodeddata = Rsacoder.decryptbypublickey (Encodeddata, PublicKey); String Outputstr =NewString (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 signatureString sign = rsacoder.sign (Encodeddata, Privatekey); System.err.println ("Signature:"+ sign);//Verify signature        BooleanStatus = Rsacoder.verify (Encodeddata, PublicKey, sign); System.err.println ("Status:"+ status);    Asserttrue (status); }}
Front-end Code

Dependent Jsencrypt Project

<script src="bin/jsencrypt.min.js"></script><script type="text/javascript">    var encrypt = new JSEncrypt();    encrypt.setPublicKey(‘java生成的公钥‘);    var encrypted = encrypt.encrypt(‘加密的字符串‘);</script>
Description

The front-end generates encrypted strings, which are uploaded to the encrypted background, and Java uses the private key to decrypt it.

RSA algorithm JS encrypted Java decryption

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.