Java Cryptographic RSA Example

Source: Internet
Author: User
Tags base64 decrypt
 
Import java.security.InvalidKeyException;
Import Java.security.KeyFactory;
Import Java.security.KeyPair;
Import Java.security.KeyPairGenerator;
Import java.security.NoSuchAlgorithmException;
Import Java.security.PrivateKey;
Import Java.security.PublicKey;
Import Java.security.interfaces.RSAPrivateKey;
Import Java.security.interfaces.RSAPublicKey;
Import Java.security.spec.PKCS8EncodedKeySpec;
 
Import Java.security.spec.X509EncodedKeySpec;
Import javax.crypto.BadPaddingException;
Import Javax.crypto.Cipher;
Import javax.crypto.IllegalBlockSizeException;
 
Import javax.crypto.NoSuchPaddingException;
Import Sun.misc.BASE64Decoder;
Import Sun.misc.BASE64Encoder; 
public class Encryprsa {public static final String key_algorithm = "RSA"; /** * BASE64 decryption * @param key * @return * @throws Exception/public static byte[] decryptBASE64 (String key) thr  
oWS Exception {return (new Base64decoder ()). Decodebuffer (key); /** * BASE64 Encryption * @param key * @return * @throWS Exception */public static String encryptBASE64 (byte[] key) throws Exception {return (new Base64encoder ()). En  
Codebuffer (key); /** * Encryption * @param publickey * @param srcbytes * @return * @throws Nosuchalgor Ithmexception * @throws nosuchpaddingexception * @throws invalidkeyexception * @throws Illegalblocksizee Xception * @throws badpaddingexception * * protected byte[] Encrypt (rsapublickey publickey,byte[] Srcbyte s) throws NoSuchAlgorithmException, Nosuchpaddingexception, InvalidKeyException, Illegalblocksizeexception, badpaddingexception{if (publickey!=null) {//cipher is responsible for completing the encryption or decryption work, based on RSA Cipher Cipher =  
            Cipher.getinstance ("RSA");  
            Initializes the cipher object according to the public key Cipher.init (Cipher.encrypt_mode, PublicKey);  
            byte[] resultbytes = cipher.dofinal (srcbytes);  
        return resultbytes;  
    return null;  
 }     
    /** * Decryption * @param privatekey * @param srcbytes * @return * @throws Nosuchalgorith Mexception * @throws nosuchpaddingexception * @throws invalidkeyexception * @throws illegalblocksizeexce ption * @throws badpaddingexception * * protected byte[] Decrypt (rsaprivatekey privatekey,byte[] Srcbytes ) throws NoSuchAlgorithmException, Nosuchpaddingexception, InvalidKeyException, Illegalblocksizeexception,  badpaddingexception{if (privatekey!=null) {//cipher is responsible for completing the encryption or decryption work, based on RSA Cipher Cipher =  
            Cipher.getinstance ("RSA");  
            Initializes the cipher object according to the public key Cipher.init (Cipher.decrypt_mode, Privatekey);  
            byte[] resultbytes = cipher.dofinal (srcbytes);  
        return resultbytes;  
    return null; /** * @param args * @throws nosuchalgorithmexception * @throws badpaddingexception * @th Rows IllegalblocksizeexCeption * @throws nosuchpaddingexception * @throws invalidkeyexception/public static void Ma In (string[] args) throws NoSuchAlgorithmException, InvalidKeyException, Nosuchpaddingexception,  
        Illegalblocksizeexception, Badpaddingexception, exception{encryprsa RSA = new Encryprsa ();  
        String msg = "Public and private key";  
        Keypairgenerator class is used to generate public and private key pairs, based on the RSA algorithm to generate objects Keypairgenerator Keypairgen = keypairgenerator.getinstance ("RSA");  
        Initializes a key pair generator with a key size of 1024-bit keypairgen.initialize (1024);  
        Generates a key pair, stored in KeyPair KeyPair KeyPair = Keypairgen.generatekeypair ();               
        Get the private key rsaprivatekey Oraprivatekey = (rsaprivatekey) keypair.getprivate ();  
          
        
        
        Get public key Rsapublickey Orapublickey = (rsapublickey) keypair.getpublic ();
        Byte[] Publickeybyte =orapublickey.getencoded ();
        String publickeystring = encryptBASE64 (publickeybyte); SYstem.out.println (publickeystring);
        Byte[] Privatekeybyte =oraprivatekey.getencoded ();
        String privatekeystring = encryptBASE64 (privatekeybyte);
        
        System.out.println (privatekeystring);  
        Keyfactory keyfactory = keyfactory.getinstance (key_algorithm);  
        Pkcs8encodedkeyspec Privatekcs8keyspec = new Pkcs8encodedkeyspec (decryptBASE64 (privatekeystring));
        
 
        
        Privatekey privatekey= keyfactory.generateprivate (PRIVATEKCS8KEYSPEC); 
        X509encodedkeyspec Publicpkcs8keyspec = new X509encodedkeyspec (decryptBASE64 (publickeystring));
        
        
        
        PublicKey PublicKey = Keyfactory.generatepublic (Publicpkcs8keyspec);  
        Encrypt byte[with public key] Srcbytes = Msg.getbytes ();  
        
        byte[] Resultbytes = Rsa.encrypt ((rsapublickey) PublicKey, srcbytes);
        
        String base64msg= encryptBASE64 (resultbytes);
          
        byte[] base64msgd = decryptBASE64 (base64msg);Decrypt byte[with the private key] Decbytes = Rsa.decrypt ((rsaprivatekey) Privatekey, BASE64MSGD);  
        System.out.println ("Clear text is:" + msg);  
        SYSTEM.OUT.PRINTLN ("Double encryption is:" +base64msg);  
    System.out.println ("After decryption:" + new String (decbytes));  
 

 }  
}

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.