Java RSA Encryption decryption

Source: Internet
Author: User
Tags string back string format asymmetric encryption

The BASE64 is used in this tool class and requires a third-party class library: javabase64-1.3.1. Jar

Note:
RSA encryption plaintext maximum length of 117 bytes, decryption requires the maximum length of the ciphertext is 128 bytes, so in the process of encryption and decryption needs to be chunked.

RSA Encryption has a limit on the length of the plaintext if the encrypted data is thrown by the General Assembly as follows Exception:

Exception in thread ' main ' javax.crypto.IllegalBlockSizeException:Data must not being longer than 117 bytes at    com.sun.c RYPTO.PROVIDER.RSACIPHER.A (dashoa13*.)    At Com.sun.crypto.provider.RSACipher.engineDoFinal (dashoa13*.)    At Javax.crypto.Cipher.doFinal (dashoa13*.)



Rsautils.java


Package Security;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.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;/* * * <p> * RSA public/private key/Signature Toolkit * </p> * <p> * Ronald Leevist (Ron [r]ivest), Adi Samor (Adi [S]hamir) and Lennard Adman (Leonard [a]d Leman) * </p> * <p> * The key in string format is BASE64 encoded without special instructions <br/> * Because asymmetric encryption is extremely slow, the generic file does not use it for encryption but uses symmetric encryption <br /> * Asymmetric encryption algorithm can be used for symmetric encryption key encryption, so that the security of the key to ensure the security of data * </p> * * @author Icewee * @date 2012-4-26 * @version 1.0 */PUBL        IC class Rsautils {/** * cryptographic algorithm RSA */public static final String key_algorithm = "RSA"; /* * Signature Algorithm */public static final String signature_algorithm = "Md5withrsa";        /** * Gets the public key key */private static final String Public_key = "Rsapublickey";        /** * Gets the private key of key */private static final String Private_key = "Rsaprivatekey";        /** * RSA Maximum encrypted clear Text size */private static final int max_encrypt_block = 117;    /** * RSA Max decryption size */private static final int max_decrypt_block = 128; /** * <p> * Generate key pair (public and private) * </p> * * @return * @throws Exception * * IC map<string, object> Genkeypair () throws Exception {Keypairgenerator Keypairgen = Keypairgenerator.getinst        Ance (Key_algorithm);        Keypairgen.initialize (1024);        KeyPair KeyPair = Keypairgen.generatekeypair ();        Rsapublickey PublicKey = (rsapublickey) keypair.getpublic ();        Rsaprivatekey Privatekey = (rsaprivatekey) keypair.getprivate (); map<string, object> keyMap = new HashmaP<string, object> (2);        Keymap.put (Public_key, PublicKey);        Keymap.put (Private_key, Privatekey);    return KEYMAP; /** * <p> * Generate digital signatures for information with private key * </p> * * @param data encrypted * @param privatekey private key (BASE64 code) * * @return * @throws Exception */public static string sign (byte[] data, String Privatekey        ) throws Exception {byte[] keybytes = Base64utils.decode (Privatekey);        Pkcs8encodedkeyspec Pkcs8keyspec = new Pkcs8encodedkeyspec (keybytes);        Keyfactory 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 ());    }/** * <p> * Verify Digital signature * </p> * * @param data encrypted * @param publickey public key (BASE64 encoded) * @param sign Digital Signature * * @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 = 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)); }/** * <P> * Private key decryption * </p> * * @param encrypteddata Encrypted data * @param privatekey private key (BA SE64 code) * @return * @throws Exception */public static byte[] Decryptbyprivatekey (byte[] EncryptedData, STR       ing Privatekey) throws Exception {byte[] keybytes = Base64utils.decode (Privatekey); Pkcs8encodedkeyspec Pkcs8keyspec = new Pkcs8encodedkeyspec (keybytes);        Keyfactory keyfactory = keyfactory.getinstance (key_algorithm);        Key Privatek = keyfactory.generateprivate (Pkcs8keyspec);        Cipher 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;                Fragment 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; /** * <p> * Public Key decryption * </p> * * @param encrypteddata Encrypted data * @param publickey public key (BAS E64 code) * @return * @throws Exception */public static byte[] Decryptbypublickey (byte[] EncryptedData, Strin        G PublicKey) throws Exception {byte[] keybytes = Base64utils.decode (PublicKey);        X509encodedkeyspec X509keyspec = new X509encodedkeyspec (keybytes);        Keyfactory keyfactory = keyfactory.getinstance (key_algorithm);        Key Publick = Keyfactory.generatepublic (X509keyspec);        Cipher 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;                Fragment decryption of data while (Inputlen-offset > 0) {if (Inputlen-offset > Max_decrypt_block) { Aa!he = 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;     }/** * <p> * Public key Encryption * </p> * * @param data source * @param publickey Public key (BASE64 encoded)            * @return * @throws Exception */public static byte[] Encryptbypublickey (byte[] data, String PublicKey)        Throws Exception {byte[] keybytes = Base64utils.decode (PublicKey);        X509encodedkeyspec X509keyspec = new X509encodedkeyspec (keybytes);        Keyfactory keyfactory = keyfactory.getinstance (key_algorithm);        Key Publick = Keyfactory.generatepublic (X509keyspec); Encrypt the data Cipher 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;                Fragment encryption for data 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 * @param privatekey private key (BASE64 encoded)            * @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 = keyfactory.getinstance (key_algorithm);        Key Privatek = keyfactory.generateprivate (Pkcs8keyspec);        Cipher 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;                Fragment encryption for data 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> * Get private key * </p> * * @param keyMap Key pair * @return * @throws Exception */public static String Getprivatekey (map<string, object> keyMap) throws Exception {Key ke        y = (Key) keymap.get (Private_key);    Return Base64utils.encode (key.getencoded ());     }/** * <p> * Get public key * </p> * * @param keyMap Key pair * @return * @throws Exception  */public static String Getpublickey (map<string, object> keyMap) throws Exception {key key        = (Key) keymap.get (Public_key);    Return Base64utils.encode (key.getencoded ()); }}



Base64utils.java



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 Codec kit * </p> * <p> * Dependent Javabase64-1.3.1.jar * </p> * * @author Icewee * @date 2012-5-19 * @version 1.0 */public class Base64utils {/** * file read buffer size *        /private static final int cache_size = 1024; /** * <p> * BASE64 string decoded to binary data * </p> * * @param base64 * @return * @throws Except Ion */public static byte[] Decode (String base64) throws Exception {return Base64.decode (Base64.getbytes ())    ; }/** * <p> * binary data encoded as BASE64 String * </p> * * @param bytes * @return * @throw S Exception */public static string encode (byte[] bytes) throws Exception {return new string (Base64.encOde (bytes));      }/** * <p> * encode file as BASE64 String * </p> * <p> * Large file with caution, may cause memory overflow * </p> * * @param filePath file Absolute path * @return * @throws Exception */public static String Encodefile (Strin        G FilePath) throws Exception {byte[] bytes = Filetobyte (FilePath);    return encode (bytes); }/** * <p> * BASE64 string back to File * </p> * * @param filePath file Absolute path * @param base64         Encoded String * @throws Exception */public static void Decodetofile (String filePath, String base64) throws Exception {        byte[] bytes = decode (base64);    Bytearraytofile (bytes, filePath); }/** * <p> * file converted to binary array * </p> * * @param filePath file path * @return * @thro WS Exception */public static byte[] Filetobyte (String filePath) throws Exception {byte[] data = new Byte[0        ];        File File = new file (FilePath); if (File.exisTS ()) {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 Write 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 (); }        }



Rsatester.java



Import Java.util.map;public class Rsatester {static String publickey;    Static String Privatekey;            static {try {map<string, object> keyMap = Rsautils.genkeypair ();            PublicKey = Rsautils.getpublickey (KEYMAP);            Privatekey = Rsautils.getprivatekey (KEYMAP);            SYSTEM.ERR.PRINTLN ("Public key: \n\r" + publickey);        SYSTEM.ERR.PRINTLN ("Private key: \n\r" + privatekey);        } catch (Exception e) {e.printstacktrace ();        }} public static void Main (string[] args) throws Exception {test ();    Testsign ();        } static void Test () throws Exception {System.err.println ("Public key cryptography-private key decryption"); String Source = "This is a line without any meaning of the text, you see the end is not see, is not it?"        ";        System.out.println ("\ r pre-encryption text: \ r \ n" + source);        byte[] data = Source.getbytes ();        byte[] Encodeddata = Rsautils.encryptbypublickey (data, PublicKey);        SYSTEM.OUT.PRINTLN ("Encrypted text: \ r \ n" + new String (Encodeddata)); byte[] Decodeddata = RsauTils.decryptbyprivatekey (Encodeddata, Privatekey);        String target = new string (decodeddata);    SYSTEM.OUT.PRINTLN ("decrypted text: \ r \ n" + target);        } static void Testsign () throws Exception {System.err.println ("private key encryption--public key decryption");        String Source = "This is a line of meaningless text that tests RSA digital signatures";        System.out.println ("original text: \ r \ n" + source);        byte[] data = Source.getbytes ();        byte[] Encodeddata = Rsautils.encryptbyprivatekey (data, Privatekey);        SYSTEM.OUT.PRINTLN ("After encryption: \ r \ n" + new String (Encodeddata));        byte[] Decodeddata = Rsautils.decryptbypublickey (Encodeddata, PublicKey);        String target = new string (decodeddata);        System.out.println ("After decryption: \ r \ n" + target);        SYSTEM.ERR.PRINTLN ("Private key signature--public key verification signature");        String sign = rsautils.sign (Encodeddata, Privatekey);        System.err.println ("signature: \ r" + sign);        Boolean status = Rsautils.verify (Encodeddata, PublicKey, sign);    System.err.println ("Verification result: \ r" + status); }    }




Java RSA Encryption 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.