rsa decryption front and rear ends

1, the service-side encryption and decryption:

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;
public class RsaUtils {


    private static final String RSA_ALGORITHM = "RSA";
    private static final int MAX_DECRYPT_BLOCK = 128;
    private static  RSAPublicKey publicKey;
    private static  RSAPrivateKey privateKey;

    public static RsaUtils instance(){
        return new RsaUtils();
    }


    public void geneKeys() throws NoSuchAlgorithmException {
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(RSA_ALGORITHM, new BouncyCastleProvider());
            keyPairGenerator.initialize(1024);
            KeyPair keyPair = keyPairGenerator.generateKeyPair();
            privateKey = (RSAPrivateKey) keyPair.getPrivate();
            publicKey = (RSAPublicKey)keyPair.getPublic();
    }


    public String encodeByPrivateKey(String body) throws Exception {
        Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, privateKey);
        return Base64.getEncoder().encodeToString(cipher.doFinal(body.getBytes("utf-8")));
    }

    public String encodeByPublicKey(String body)  throws Exception {
        Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        return Base64.getEncoder().encodeToString(cipher.doFinal(body.getBytes("utf-8")));
    }


    public String decodeByPrivateKey(String body)   throws Exception {
        Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        return decryptByPrivateKey(body);
    }


    public String decodeByPublicKey(String body)    throws Exception {
        Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, publicKey);
        return new new decryptBase64 (encryptedStr);String (Cipher.doFinal (Base64.getDecoder () decode (body)).); 
    } 


    / ** 
     * private key to decrypt 
     * 
     * @param encryptedStr 
     * @return 
     * / 
    public   String decryptByPrivateKey (String encryptedStr) 
    { 
        the try 
        { 
            // for private key to decrypt 
            byte [] = privateKeyBytes privateKey.getEncoded ();
             // get private 
            PKCS8EncodedKeySpec with keySpec = new new PKCS8EncodedKeySpec with (privateKeyBytes);
             // get the data to be decrypted 
            byte [] data = 
            the KeyFactory FactoryKeyFactory.getInstance = ( "the RSA" ); 
            the PrivateKey privateKey = factory.generatePrivate (keySpec);
             // data decrypting 
            the Cipher cipher = Cipher.getInstance (factory.getAlgorithm ()); 
            cipher.init (Cipher.DECRYPT_MODE, privateKey); 
            // returns the UTF-8 encoding decryption information 
            int inputLen = data.length; 
            ByteArrayOutputStream OUT = new new ByteArrayOutputStream ();
             int OFFSET = 0 ;
             byte [] Cache;
             int I = 0 ;
             // to decrypt the data segments
            while (inputLen - offSet > 0)
            {
                if (inputLen - offSet > MAX_DECRYPT_BLOCK)
                {
                    cache = cipher.doFinal(data, offSet, MAX_DECRYPT_BLOCK);
                } else
                {
                    cache = cipher.doFinal(data, offSet, inputLen - offSet);
                }
                out.write(cache, 0, cache.length);
                i++;
                offSet = i * MAX_DECRYPT_BLOCK;
            }
            byte [] = decryptedData out.toByteArray (); 
            the out.close (); 
            return  new new String (decryptedData, "UTF-. 8" ); 
        } the catch (Exception E) 
        { 
            e.printStackTrace (); 
        } 
        return  null ; 
    } 

    / * * 
     * BASE64 decoding 
     * 
     * @param Key requires a Base64 string decoded 
     * @return byte array
      * / 
    public  static  byte [] decryptBase64 (string Key) 
    { 
        return Base64.getDecoder () decode (Key);. 
    }


     public static void main(String[] args) throws Exception {
        RsaUtils rsaUtils = new RsaUtils();
        rsaUtils.geneKeys();
        String encodes = rsaUtils.encodeByPrivateKey("123456");
        System.out.println("加密前:"+123456);
        System.out.println("公钥:"+Base64.getEncoder().encodeToString(RsaUtils.publicKey.getEncoded()));
        System.out.println("私钥:"+Base64.getEncoder().encodeToString(RsaUtils.privateKey.getEncoded()));
        System.out.println("私钥加密后:"+encodes);
        System.out.println ( "after public-key encryption:" + rsaUtils.encodeByPublicKey ( "123456" )); 
        System.out.println ( "public key and decryption:" + rsaUtils.decodeByPublicKey (Encodes)); 
    } 
}

Before encryption: 123456
public: MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCgSZEMYSVYc / xAka4rLGtADBqKrZ2tzxLv9PpH4DgGqngfZbJDLEK1alGffXGwgg48mAryHtaCYt9d9xsIHqyYomQq5kASzaBSfOMrieCd5aGQSBot9v8yFcvHnUtnJ7IggXoBEfDLEn5tXHxJgQf6ra6tW / i89vTeuodHMvPBaQIDAQAB
Private: MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAKBJkQxhJVhz / ECRrissa0AMGoqtna3PEu / 0 + kfgOAaqeB9lskMsQrVqUZ99cbCCDjyYCvIe1oJi3133GwgerJiiZCrmQBLNoFJ84yuJ4J3loZBIGi32 / zIVy8edS2cnsiCBegER8MsSfm1cfEmBB / qtrq1b + Lz29N66h0cy88FpAgMBAAECgYAV / lItSS0nKG8N6w9jdCpZNO / 1ZGI05at7CnnHIACABacK49jkd6 / FlcuSX1OYvRe3 / 8LMuyeC548vpQbsA815wl2IMQVBtG58i / jjWzhUh4VTgYVubloKBf7GLCxX39DFF5E9oOQa9cMOwwxDkSvU9DVeRvQGlcx8v0I / Lnub6wJBANnksVTY3smY7Ud1Xv2A4DIRHMWy / p9LyuTtVBjsvP7tKf3wUrGqkeVVEkkThpaZ + 2GRg59KDp1 + 4Mewid33JP8CQQC8UcvL + lWhm + Zw7eHW5fm + uldjHksl3jysNoqMoAa4D09pCekS3NpIE + Pcw4sI2c16FLG0wnN7ds1RZWGLSBGXAkEAx2axHgulvmnz4yw3NNjm0wq0APxwZckPsXa7OmAUCVtyzVBL7QlCoNO8eyGiTlo2IbDv + irkux7sh / I4COhucwJBAIAKIUVz1GsIA7s + kjG5tX + PVMEopLF / k8MHZlZMq6TTjAt / 2H + ht6wQEfpU3aBL7iAWF + kt2LTWRq0UAClh + 8sCQQC25D7x / UWopLVUFqJUJxDfs5iMIVKR / Gs8wNvsGt6Ke7cikgPue + aqhArb3XZIHF1BslWC6 / Ddwr2ZrtoueJ0F
After the private key: K / 5aACTTKj1OZmOSUmbavA1NXczkCgRfedUUj + PRlZTblBL9jvo7W1HzRDJDdPIsm1Br7XPFSWbekYVLMCboxr6ygyEa5NtFu7ku7pNvs7TkROVOS7JqDXWDUGSLINqgXl1D39 + ZWBCKnwZadkipPfd9ZHkEJfkJc23cMhz2C2c =
after public-key encryption: k4QlyVJzti0EhSgpDz5K2bXt8RtfNrEGn7RwsGCjGk9WVzWrJoW5xP8wBJomVLeIeGK1mHEex4nYCxt4lW49f3HX85ZApAFQH31CBYSHwxpEfxoeNZF5SA65rNSeFdvMrOWdMWGoRxZzgF2GtqdSUC13PMNkGKhgMEGvVQOnNKE =
public key and decryption: 123456

 

2, the front end encryption rsa:

<html>
  <head>
        <script type="text/javascript" src="aes.js"></script> 
        
        <script src="https://cdn.bootcss.com/jsencrypt/3.0.0-rc.1/jsencrypt.js"></script>
  </head>
  <body>
  
  
  <script type="text/javascript">
      
             
             var aesFun = {
                options:{
                    originalStr:"123456",
                    aesKey:"1234567891234567"
                },
                encrypt:function(word){
                    var key = CryptoJS.enc.Utf8.parse(this.options.aesKey);
                    var srcs = CryptoJS.enc.Utf8.parse(word);
                    var encrypted = CryptoJS.AES.encrypt(srcs, key, {mode:CryptoJS.mode.ECB,padding: CryptoJS.pad.Pkcs7});
                    return encrypted.toString();
                
                },
                decrypt:function(word){
                    var Key = CryptoJS.enc.Utf8.parse ( the this .options.aesKey);
                     var the decrypt = CryptoJS.AES.decrypt (Word, Key, {MODE: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7});
                     return CryptoJS.enc.Utf8.stringify (the decrypt) .toString (); 
                } 
                
             } 
             
             var Options = aesFun.options; 
             
            var encryptstr = aesFun.encrypt (options.originalStr); 
            
            // console.info ( "before encryption:" + options .originalStr) 
            // console.info ( "encryption keys and decryption keys:" + options.aesKey) 
            // console.info ( "encrypted:" + encryptstr)
             //console.info("解密后:"+aesFun.decrypt(encryptstr)); 
            
            
            var encrypt = new JSEncrypt();
            var encryptstr = "123456";
            var pubKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDyWmqsl0DMtWrRS6VFF4dfbNx0aOqsrT3Yq61ZZVu8h3OnGTMUjCkYothw794C0FpSYCJpWBGl7Ip6dXkohQU9TgadHWZ4wuLPJIyVhm39gAK9KoMNtEoGQ6vjXAxOE6QAS8lTZvVZMa9c2cboGEKvgyIilpHtbuAO42dNZH2+qQIDAQAB";
            encrypt.setPublicKey(pubKey);
            
            var data = encrypt.encrypt(encryptstr);
            console.info("加密前:" + Encryptstr) 
            console.info ( " Public Key: " + pubkey) 
            console.info ( " after public-key encryption: " + Data); 
            
  </ Script > 
  </ body > 
</ HTML >

index.html: 49 before encryption: 123456
index.html: 50 public: MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDyWmqsl0DMtWrRS6VFF4dfbNx0aOqsrT3Yq61ZZVu8h3OnGTMUjCkYothw794C0FpSYCJpWBGl7Ip6dXkohQU9TgadHWZ4wuLPJIyVhm39gAK9KoMNtEoGQ6vjXAxOE6QAS8lTZvVZMa9c2cboGEKvgyIilpHtbuAO42dNZH2 + qQIDAQAB
index.html: 51 is the public-key encryption: g27aG60 / xFupUpBwfCJKhiuNBkn69X + TV5fO5qRpLgnnC0E0gMumJepwBtZR3h + q6vcUK + xqjNXSYG9mz7Lz7c8H + / CLxuga76vL8hpbewbkynelveb + jywHQFemIoMl1HI6JOe5hh5 / p / 1Ecio5iPfnYlmr9M9nli2OsItIN00 =

Guess you like

Origin www.cnblogs.com/heyf/p/11206217.html