RSA encryption and decryption algorithms, data transmission, front and back data exchange

1, RSA encryption and decryption algorithm ideas.

      java background randomly generated public key, private key. Stored in the session, informed the front desk js obtain the public key. Encrypted by jsencrypt.min.js. Transfer back to back, back through the private key to decrypt.

2, RSA common abnormal decomposition.

    Question one

Cannot find any provider supporting RSA

This issue, belong to JDK version bug problem, I 1.8.0_171 experience this problem can be solved after replacing the 1.8.0_211.

Question two

DER input, Integer tag error

This problem is mainly a public key, the private key to the mix to, decryption, using the public key to decrypt, ha ha break through discovery.

Question three

Decryption error

This problem occurs mainly mass participation front page to the back, a "+" symbol is replaced by "" spaces cause can not be decrypted.

 

3. The code section.

Refers to the address: https: //blog.csdn.net/qq_36827957/article/details/81563973 

<script language=javascript>
var publicKey = '<%=session.getAttribute("publicKey")%>';
$(document).ready(function() {
    $('#doSearch').click(function(e) {
        var  phoneNo= $("#phoneNo").val();
        var encrypt = new JSEncrypt();
        encrypt.setPublicKey(publicKey);
        phoneNo = encrypt.encrypt(phoneNo);
        alert(phoneNo);
document.frm.submit(); }); });
</script>

 Into the session part

    @RequestMapping(value = "/index")
    public String login(Model model, HttpSession session,HttpServletRequest request) {
        Map<String, String> rsaMap = new  HashMap<String, String>();
        rsaMap = RsaUtil.createRSAKeys();
        String publicKey = rsaMap.get("publicKey");
        String privateKey = rsaMap.get("privateKey");
        session.setAttribute("publicKey", publicKey);
        session.setAttribute("niceKey", privateKey);
        return "index";
    }

 

 Analysis section

    @RequestMapping(value = "/search", method = RequestMethod.POST)
    public String search(@ModelAttribute String phoneNo, HttpServletRequest request,
            HttpSession session, Model model) {
                if (phoneNo==null || "".equals(phoneNo)) {
                    model.addAttribute("returnUrl", "fail");
                    return "fail";
                }
                //RSA解密
                phoneNo = phoneNo.replace(" ", "+");
                phoneNo = RsaUtil.decode(phoneNo, session.getAttribute("niceKey").toString());
                System.out.println ("PhoneNo:" + PhoneNo); 
                
                { 
                    // service code 
                }
         return "Success" ; 
    }

 

 

 

 RSA Tools section

package com.thinksep.utils;

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.SecureRandom;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
 
import javax.crypto.Cipher;
 
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.tomcat.util.codec.binary.Base64;
 
/**
* @author 
* @createDate 
*/
public class RsaUtil {
    protected static final Log log = LogFactory.getLog(RsaUtil.class);
    private static String KEY_RSA_TYPE = "RSA";
    private static int KEY_SIZE = 1024;//JDK方式RSA加密最大只有1024位
    private static int= KEY_SIZE ENCODE_PART_SIZE / 8 ;
     public  static  Final String PUBLIC_KEY_NAME = "public" ;
     public  static  Final String PRIVATE_KEY_NAME = "Private" ; 
 
    / ** 
     * Create a public secret key 
     * @return 
     * / 
    public  static the Map <String, String> createRSAKeys ( ) { 
        the Map <String, String> = keyPairMap new new the HashMap <> (); // stored inside Base64 encryption bit public and private keys of 
        the try { 
            the KeyPairGenerator KeyPairGenerator = KeyPairGenerator.getInstance (KEY_RSA_TYPE);
            keyPairGenerator.initialize (KEY_SIZE, new new a SecureRandom ()); 
            KeyPair KeyPair = keyPairGenerator.generateKeyPair (); 
 
            // obtains the public key secret key 
            String publicKeyValue = Base64.encodeBase64String (keyPair.getPublic () the getEncoded ().); 
            String privateKeyValue = the Base64 .encodeBase64String (keyPair.getPrivate () the getEncoded ().); 
 
            // stored public keys, for later retrieval 
            keyPairMap.put (PUBLIC_KEY_NAME, publicKeyValue); 
            keyPairMap.put (PRIVATE_KEY_NAME, privateKeyValue); 
        } the catch (NoSuchAlgorithmException E) { 
            log.error ( "current JDK version did not find the RSA encryption algorithm!" ); 
            e.printStackTrace (); 
        }
        return keyPairMap; 
    } 
 
    / ** 
     * public key cryptography 
     * Description: 
     * 1 byte = 8 bits; 
     * The maximum length of the encrypted private key 1024, the maximum length of the encryption 128-11 = 117 bytes, regardless of how long the data, encryption are out length of 128 bytes. 
     * @Param sourceStr 
     * @param publicKeyBase64Str 
     * @return 
     * / 
    public  static String encode (sourceStr String, String publicKeyBase64Str) {
         byte [] = publicBytes Base64.decodeBase64 (publicKeyBase64Str);
         // public key encryption 
        X509EncodedKeySpec X509EncodedKeySpec = new new X509EncodedKeySpec (publicBytes) ; 
        List<byte[]> alreadyEncodeListData = new LinkedList<>();
 
        int maxEncodeSize = ENCODE_PART_SIZE - 11;
        String encodeBase64Result = null;
        try {
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_RSA_TYPE);
            PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
            Cipher cipher = Cipher.getInstance(KEY_RSA_TYPE);
            cipher.init(Cipher.ENCRYPT_MODE,publicKey);
            byte[] sourceBytes = sourceStr.getBytes("utf-8");
            int sourceLen = sourceBytes.length;
            for(int i=0;i<sourceLen;i+=maxEncodeSize){
                int curPosition = sourceLen - i;
                int tempLen = curPosition;
                if(curPosition > maxEncodeSize){
                    tempLen = maxEncodeSize;
                }
                byte[] tempBytes = new byte[tempLen];//待加密分段数据
                System.arraycopy(sourceBytes,i,tempBytes,0,tempLen);
                byte[] tempAlreadyEncodeData = cipher.doFinal(tempBytes);
                alreadyEncodeListData.add(tempAlreadyEncodeData);
            }
            int partLen = alreadyEncodeListData.size();//加密次数
 
            int allEncodeLen = partLen * ENCODE_PART_SIZE;
            byte[] encodeData = new byte[allEncodeLen];//存放所有RSA分段加密数据
            for (int i = 0; i < partLen; i++) {
                byte[] tempByteList = alreadyEncodeListData.get(i);
                System.arraycopy(tempByteList,0,encodeData,i*ENCODE_PART_SIZE,ENCODE_PART_SIZE);
            }
            encodeBase64Result = Base64.encodeBase64String(encodeData);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return encodeBase64Result;
    }
 
    /**
     * 私钥解密
     * @param sourceBase64RSA
     * @param privateKeyBase64Str
     */
    public static String decode(String sourceBase64RSA,String privateKeyBase64Str){
        byte[] privateBytes = Base64.decodeBase64(privateKeyBase64Str);
        byte[] encodeSource = Base64.decodeBase64(sourceBase64RSA);
        int encodePartLen = encodeSource.length/ENCODE_PART_SIZE;
        List<byte[]> decodeListData = new LinkedList<>();//所有解密数据
        String decodeStrResult = null;
        //私钥解密
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateBytes);
        try {
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_RSA_TYPE);
            PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
            Cipher cipher = Cipher.getInstance(KEY_RSA_TYPE);
            cipher.init(Cipher.DECRYPT_MODE,privateKey);
            int allDecodeByteLen = 0;//初始化所有被解密数据长度
            for (int i = 0; i < encodePartLen; i++) {
                byte[] tempEncodedData = new byte[ENCODE_PART_SIZE];
                System.arraycopy(encodeSource,i*ENCODE_PART_SIZE,tempEncodedData,0,ENCODE_PART_SIZE);
                byte[] decodePartData = cipher.doFinal(tempEncodedData);
                decodeListData.add(decodePartData);
                allDecodeByteLen += decodePartData.length;
            }
            byte [] decodeResultBytes = new byte[allDecodeByteLen];
            for (int i = 0,curPosition = 0; i < encodePartLen; i++) {
                byte[] tempSorceBytes = decodeListData.get(i);
                int tempSourceBytesLen = tempSorceBytes.length;
                System.arraycopy(tempSorceBytes,0,decodeResultBytes,curPosition,tempSourceBytesLen);
                curPosition += tempSourceBytesLen;
            }
            decodeStrResult = new String(decodeResultBytes,"UTF-8");
        }catch (Exception e){
            e.printStackTrace();
        }
        return decodeStrResult;
    }
}

 

 

Guess you like

Origin www.cnblogs.com/thinksep/p/10987920.html