Newer
Older
dxcgt / app / src / main / java / com / smartdot / cgt / util / RsaUtils.java
wangxitong on 6 Apr 2021 2 KB first commit
package com.smartdot.cgt.util;

import android.util.Base64;

import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

/**
 * Created by W530 on 2019/9/26.
 */


public class RsaUtils {
    //构建Cipher实例时所传入的的字符串,默认为"RSA/NONE/PKCS1Padding"
    private static String sTransform = "RSA/None/PKCS1Padding";
    //进行Base64转码时的flag设置,默认为Base64.DEFAULT
    private static int sBase64Mode = Base64.DEFAULT;

    //初始化方法,设置参数
    public static void init(String transform, int base64Mode){
        sTransform = transform;
        sBase64Mode = base64Mode;
    }


    private static byte[] processData(byte[] srcData, Key key, int mode){
        //用来保存处理结果
        byte[] resultBytes = null;
        try {
            //获取Cipher实例
            Cipher cipher = Cipher.getInstance(sTransform);
            //初始化Cipher,mode指定是加密还是解密,key为公钥或私钥
            cipher.init(mode,key);
            //处理数据
            resultBytes = cipher.doFinal(srcData);

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        }

        return resultBytes;
    }

    public static String encryptDataByPublicKey(byte[] srcData, PublicKey publicKey){

        byte[] resultBytes = processData(srcData,publicKey, Cipher.ENCRYPT_MODE);

        return Base64.encodeToString(resultBytes,sBase64Mode);

    }

    public static PublicKey keyStrToPublicKey(String publicKeyStr){
        PublicKey publicKey = null;
        byte[] keyBytes = Base64.decode(publicKeyStr,sBase64Mode);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        try {
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            publicKey = keyFactory.generatePublic(keySpec);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
        }
        return publicKey;
    }

}