Java SRA encryption and decryption

Source: Internet
Author: User
Package testrsa; import Java. io. bytearrayinputstream; import Java. io. bytearrayoutputstream; import Java. io. file; import Java. io. fileinputstream; import Java. io. fileoutputstream; import Java. io. inputstream; import Java. io. outputstream; import it. sauronsoftware. base64.base64; /*** <p> * base64 encoding and decoding toolkit * </P> * <p> * depending on the javabase64-1.3.1.jar * </P> ** @ author icewee * @ date 2012-5-19 *@ version 1.0 */Public CIA SS base64utils {/*** file read buffer size */Private Static final int cache_size = 1024; /*** <p> * decodes base64 strings into binary data * </P> ** @ Param base64 * @ return * @ throws exception */public static byte [] Decode (string base64) throws exception {return base64.decode (base64.getbytes ());} /*** <p> * binary data is encoded as a base64 string * </P> ** @ Param bytes * @ return * @ throws exception */public static string encode (byte [] bytes) Throws exception {return new string (base64.encode (bytes ));} /***** <p> * encode the file as a base64 string * </P> * <p> * use large files with caution, may cause memory overflow * </P> ** @ Param filepath file absolute path * @ return * @ throws exception */public static string encodefile (string filepath) throws exception {byte [] bytes = filetobyte (filepath); Return encode (bytes );} /*** <p> * convert a base64 string to a file * </P> ** @ Param filepath: the absolute path of the file * @ Param base64 encoded string * @ Throws exception */public static void decodetofile (string filepath, string base64) throws exception {byte [] bytes = decode (base64); bytearraytofile (bytes, filepath );} /*** <p> * convert the file to a binary array * </P> ** @ Param filepath * @ return * @ throws exception */public static byte [] filetobyte (string filepath) throws exception {byte [] DATA = new byte [0]; file = new file (filepath); If (file. ex Ists () {fileinputstream in = new fileinputstream (File); bytearrayoutputstream out = new bytearrayoutputstream (2048); byte [] cache = new byte [cache_size]; int nread = 0; while (nread = in. read (cache ))! =-1) {out. write (cache, 0, nread); out. flush ();} Out. close (); In. close (); Data = out. tobytearray ();} return data ;} /***** <p> * binary data Writing File * </P> ** @ Param bytes binary data * @ Param filepath file generation directory */public static void bytearraytofile (byte [] bytes, string filepath) throws exception {inputstream in = new bytearrayinputstream (bytes); file destfile = new file (filepath); If (! Destfile. getparentfile (). exists () {destfile. getparentfile (). mkdirs ();} destfile. createnewfile (); outputstream out = new fileoutputstream (destfile); byte [] cache = new byte [cache_size]; int nread = 0; while (nread = in. read (cache ))! =-1) {out. Write (cache, 0, nread); Out. Flush ();} Out. Close (); in. Close ();}}
-------------------------------------------------- Relentless split line ------------------------------------------------------------------------------------------
Package testrsa; import Java. util. map; public class rsatester {static string publickey; static string privatekey;/** plaintext */private final static string sourcestring = "I am a Chinese student, okay, what do you mean, you can do it to Chinese people, okay? Okay, you can do it. "; // test the Public Key Private Static string public_aa =" signature + tobv/y9n88myiqle5cqsdp9widaqab "; // test the Private Static string private_bb = "encrypt + 9bz3b + encrypt + ky6/encrypt + s7rcm/encrypt/decrypt + encrypt/x3lpdqz/jaokvdviior2c/notify/decrypt /authorization + 7l9fkavcye8opxauqmee3 + jlhzfas + Iy + authorization + eojmsil3kggqha + authorization + 6jfkwl3pspx07koi0unt5w = "; static {try {Map <string, Object> keymap = rsautils. genkeypair (); publickey = rsautils. getpublickey (keymap); privatekey = rsautils. getprivatekey (keymap); system. err. println ("Public Key:" + publickey); system. err. println ("Private Key:" + privatekey);} catch (exception e) {e. printstacktrace () ;}} public static void main (string [] ARGs) throws exception {test (); system. out. println (); system. out. println (); system. out. println (); testsign ();} static void test () throws exception {system. out. println ("pre-encryption text:" + sourcestring ); // encryption // @ # �� PJ �� p7i1 ��> O �� BJT/ha) J #, byte [] DATA = sourcestring. getbytes (); byte [] encodeddata = rsautils. encryptbypublickey (data, public_aa); system. out. println ("after the encrypted text:" + new string (encodeddata); // decrypt // test and decrypt byte [] decodeddata = rsautils. decryptbyprivatekey (encodeddata, private_bb); string target = new string (decodeddata); system. out. println ("decrypted text:" + target);} static void testsign () throws exception {system. out. println ("original text:" + sourcestring); byte [] DATA = sourcestring. getbytes (); byte [] encodeddata = rsautils. encryptbyprivatekey (data, private_bb); system. out. println ("encrypted:" + new string (encodeddata); byte [] decodeddata = rsautils. decryptbypublickey (encodeddata, public_aa); string target = new string (decodeddata); system. out. println ("decrypted:" + target); string Sign = rsautils. sign (encodeddata, private_bb); system. out. println ("Signature:" + sign); // test the change result ------------------------------------------ string strcode = new string (encodeddata); strcode + = "ddwerwef"; encodeddata = strcode. getbytes (); // test the change result ----------------------------------------------- Boolean status = rsautils. verify (encodeddata, public_aa, sign); system. out. println ("Verification Result:" + status );}}

// ------------------------------------------------ Relentless split line ------------------------------------------------------------------------------------------

Package testrsa; import Java. io. bytearrayoutputstream; 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. rsw.vatekey; 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;/*** <p> * RSA public key/private key/Signature toolkit * </P> * <p> * Ronald Li West (Ron [R] ivest), Adi salmore (Adi [s] Hamir) and Leonard adman (Leonard [a] dleman) * </P> * <p> * keys in string format are base64 encoded without special instructions. <br/> * asymmetric encryption is extremely slow, generally, a file uses symmetric encryption instead of encryption. <br/> * asymmetric encryption algorithms can be used to encrypt symmetric encryption keys, this ensures key security and data security. * </P> ** @ author icewee * @ date 2012-4-26 * @ version 1.0 */public class rsautils {/*** Encryption algorithm RSA */public static final string key_algorithm = "RSA "; /*** signature algorithm */public static final string signature_algorithm = "md5withrsa";/*** obtain the Public Key key */Private Static final string public_key = "rsapublickey "; /*** obtain the Private Key key */Private Static final string private_key = "rsw.vatekey";/*** maximum RSA encrypted plaintext size */Private Static final int max_encrypt_block = 117; /*** maximum ciphertext size for RSA decryption */Private Static final int max_decrypt_block = 128;/*** generate a key pair (Public Key and private key) * @ throws exception */public static Map <string, Object> genkeypair () throws exception {keypairgenerator keypairgen = keypairgenerator. getinstance (key_algorithm); keypairgen. initialize (1024); keypair = keypairgen. generatekeypair (); rsapublickey publickey = (rsapublickey) keypair. getpublic (); rsw.vatekey privatekey = (rsw.vatekey) keypair. getprivate (); Map <string, Object> keymap = new hashmap <string, Object> (2); keymap. put (public_key, publickey); keymap. put (private_key, privatekey); Return keymap;}/*** use the private key to generate a digital signature * @ Param data encrypted data * @ Param privatekey private key (base64 encoding) * @ throws exception */public static string sign (byte [] data, string privatekey) throws exception {byte [] keybytes = base64utils. decode (privatekey); pkcs8encodedkeyspec pkcs8keyspec = new pkcs8encodedkeyspec (keybytes); keyfactory = keyfactory. getinstance (key_algorithm); privatekey privatek = keyfactory. generateprivate (pkcs8keyspec); signature Signature = signature. getinstance (signature_algorithm); signature. initsign (privatek); signature. update (data); Return base64utils. encode (signature. sign ();}/*** verify the digital signature * @ Param data encrypted data * @ Param publickey Public Key (base64 encoding) * @ Param sign: * @ return * @ throws exception **/public static Boolean verify (byte [] data, string publickey, string sign) throws exception {byte [] keybytes = base64utils. decode (publickey); x509encodedkeyspec keyspec = new x509encodedkeyspec (keybytes); keyfactory = keyfactory. getinstance (key_algorithm); publickey publick = keyfactory. generatepublic (keyspec); signature Signature = signature. getinstance (signature_algorithm); signature. initverify (publick); signature. update (data); Return signature. verify (base64utils. decode (sign);}/*** Private Key decryption * @ Param encrypteddata encrypted data * @ Param privatekey private key (base64 encoding) * @ throws exception */public static byte [] decryptbyprivatekey (byte [] encrypteddata, string privatekey) throws exception {byte [] keybytes = base64utils. decode (privatekey); pkcs8encodedkeyspec pkcs8keyspec = new pkcs8encodedkeyspec (keybytes); keyfactory = keyfactory. getinstance (key_algorithm); Key privatek = keyfactory. generateprivate (pkcs8keyspec); cipher = cipher. getinstance (keyfactory. getalgorithm (); cipher. init (cipher. decrypt_mode, privatek); int inputlen = encrypteddata. length; bytearrayoutputstream out = new bytearrayoutputstream (); int offset = 0; byte [] cache; int I = 0; // segment decryption of data while (inputlen-Offset> 0) {If (inputlen-Offset> max_decrypt_block) {cache = cipher. dofinal (encrypteddata, offset, max_decrypt_block);} else {cache = cipher. dofinal (encrypteddata, offset, inputlen-offset);} Out. write (cache, 0, cache. length); I ++; offset = I * max_decrypt_block;} byte [] decrypteddata = out. tobytearray (); out. close (); Return decrypteddata;}/*** Public Key decryption * @ Param encrypteddata encrypted data * @ Param publickey Public Key (base64 encoding) * @ return * @ throws exception */public static byte [] decryptbypublickey (byte [] encrypteddata, string publickey) throws exception {byte [] keybytes = base64utils. decode (publickey); x509encodedkeyspec x509keyspec = new x509encodedkeyspec (keybytes); keyfactory = keyfactory. getinstance (key_algorithm); Key publick = keyfactory. generatepublic (x509keyspec); cipher = cipher. getinstance (keyfactory. getalgorithm (); cipher. init (cipher. decrypt_mode, publick); int inputlen = encrypteddata. length; bytearrayoutputstream out = new bytearrayoutputstream (); int offset = 0; byte [] cache; int I = 0; // segment decryption of data while (inputlen-Offset> 0) {If (inputlen-Offset> max_decrypt_block) {cache = cipher. dofinal (encrypteddata, offset, max_decrypt_block);} else {cache = cipher. dofinal (encrypteddata, offset, inputlen-offset);} Out. write (cache, 0, cache. length); I ++; offset = I * max_decrypt_block;} byte [] decrypteddata = out. tobytearray (); out. close (); Return decrypteddata;}/*** public key encryption * @ Param data source data * @ Param publickey Public Key (base64 encoding) * @ throws exception */public static byte [] encryptbypublickey (byte [] data, string publickey) throws exception {byte [] keybytes = base64utils. decode (publickey); x509encodedkeyspec x509keyspec = new x509encodedkeyspec (keybytes); keyfactory = keyfactory. getinstance (key_algorithm); Key publick = keyfactory. generatepublic (x509keyspec); // data encryption cipher = cipher. getinstance (keyfactory. getalgorithm (); cipher. init (cipher. encrypt_mode, publick); int inputlen = data. length; bytearrayoutputstream out = new bytearrayoutputstream (); int offset = 0; byte [] cache; int I = 0; // encrypt data in segments while (inputlen-Offset> 0) {If (inputlen-Offset> max_encrypt_block) {cache = cipher. dofinal (data, offset, max_encrypt_block);} else {cache = cipher. dofinal (data, offset, inputlen-offset);} Out. write (cache, 0, cache. length); I ++; offset = I * max_encrypt_block;} byte [] encrypteddata = out. tobytearray (); out. close (); Return encrypteddata ;} /***** <p> * private key encryption * </P> ** @ Param data source data * @ Param privatekey private key (base64 encoding) * @ return * @ throws exception */public static byte [] encryptbyprivatekey (byte [] data, string privatekey) throws exception {byte [] keybytes = base64utils. decode (privatekey); pkcs8encodedkeyspec pkcs8keyspec = new pkcs8encodedkeyspec (keybytes); keyfactory = keyfactory. getinstance (key_algorithm); Key privatek = keyfactory. generateprivate (pkcs8keyspec); cipher = cipher. getinstance (keyfactory. getalgorithm (); cipher. init (cipher. encrypt_mode, privatek); int inputlen = data. length; bytearrayoutputstream out = new bytearrayoutputstream (); int offset = 0; byte [] cache; int I = 0; // encrypt data in segments while (inputlen-Offset> 0) {If (inputlen-Offset> max_encrypt_block) {cache = cipher. dofinal (data, offset, max_encrypt_block);} else {cache = cipher. dofinal (data, offset, inputlen-offset);} Out. write (cache, 0, cache. length); I ++; offset = I * max_encrypt_block;} byte [] encrypteddata = out. tobytearray (); out. close (); Return encrypteddata;}/*** get private key * @ Param keymap key pair * @ return * @ throws exception */public static string getprivatekey (Map <string, object> keymap) throws exception {key = (key) keymap. get (private_key); Return base64utils. encode (key. getencoded ();}/*** get public key * @ Param keymap key pair * @ throws exception */public static string getpublickey (Map <string, Object> keymap) throws exception {key = (key) keymap. get (public_key); Return base64utils. encode (key. getencoded ());}}

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.