加密方案:rsa使用公钥对字符串加密和私钥解密

package com.duoduozb.constants;

import java.io.ByteArrayOutputStream;

import java.security.Key;

import java.security.KeyFactory;

import java.security.PublicKey;

import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;

/**

* @author Created by deli

* @date 2018/9/21 08:14

* @description rsa加密工具

*/

public class RsaEncryptUtil {

    /** */

/**

* 加密算法RSA

*/

    public static final String KEY_ALGORITHM = "RSA";// RSA/NONE/NoPadding,RSA/NONE/PKCS1Padding

    /**

* String to hold name of the encryption padding.

*/

    public static final String PADDING = "RSA/NONE/PKCS1Padding";// RSA/NONE/NoPadding

    /**

* String to hold name of the security provider.

*/

    public static final String PROVIDER = "BC";

    /** */

/**

* 签名算法

*/

    public static final String SIGNATURE_ALGORITHM = "MD5withRSA";

    /** */

/**

* 获取公钥的key

*/

    private static final String PUBLIC_KEY = "RSAPublicKey";

    /** */

/**

* 获取私钥的key

*/

    private static final String PRIVATE_KEY = "RSAPrivateKey";

    /** */

/**

* RSA最大加密明文大小

*/

    private static final int MAX_ENCRYPT_BLOCK = 117;

    /** */

/**

* RSA最大解密密文大小

*/

    private static final int MAX_DECRYPT_BLOCK = 128;

    /*

* 公钥加密

*/

    public static String encryptByPublicKey(String str) throws Exception {

        Cipher cipher = Cipher.getInstance(PADDING, PROVIDER);

        // 获得公钥

        Key publicKey = getPublicKey();

        // 用公钥加密

        cipher.init(Cipher.ENCRYPT_MODE, publicKey);

        // 读数据源

        byte[] data = str.getBytes("UTF-8");

        int inputLen = data.length;

        ByteArrayOutputStream out = new ByteArrayOutputStream();

        int offSet = 0;

        byte[] cache;

        int i = 0;

        // 对数据分段加密

        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 Base64Util.encode(encryptedData);

    }

    /*

* 公钥解密

*/

    public static String decryptByPublicKey(String str) throws Exception {

        Cipher cipher = Cipher.getInstance(PADDING, PROVIDER);

        // 获得公钥

        Key publicKey = getPublicKey();

        // 用公钥解密

        cipher.init(Cipher.DECRYPT_MODE, publicKey);

        // 读数据源

        byte[] encryptedData = Base64Util.decode(str);

        int inputLen = encryptedData.length;

        ByteArrayOutputStream out = new ByteArrayOutputStream();

        int offSet = 0;

        byte[] cache;

        int i = 0;

        // 对数据分段解密

        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 new String(decryptedData, "UTF-8");

    }

    /**

* 读取公钥

*

    * @return

    * @throws Exception

    * @comment

    */

    private static Key getPublicKey() throws Exception {

        String key = GlobalConstants.ras_public_key;

        byte[] keyBytes;

        keyBytes = Base64Util.decode(key);

        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);

        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);

        PublicKey publicKey = keyFactory.generatePublic(keySpec);

        return publicKey;

    }

}

package com.duoduozb.constants;

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;

/**

* @author Created by deli

* @date 2018/9/21 08:17

* @description rsa 工具类

*/

public class Base64Util {

    /** */

/**

* 文件读取缓冲区大小

*/

    private static final int CACHE_SIZE = 1024;

    /** */

/**

    *

    * BASE64字符串解码为二进制数据

    *

    *

    * @param base64

    * @return

    * @throws Exception

    */

    public static byte[] decode(String base64) throws Exception {

        return Base64.decode(base64.getBytes());

    }

    /** */

/**

    *

    * 二进制数据编码为BASE64字符串

    *

    *

    * @param bytes

    * @return

    * @throws Exception

    */

    public static String encode(byte[] bytes) throws Exception {

        return new String(Base64.encode(bytes));

    }

    /** */

/**

    *

    * 将文件编码为BASE64字符串

    *

    *

    * 大文件慎用,可能会导致内存溢出

    *

    *

    * @param filePath

    *            文件绝对路径

    * @return

    * @throws Exception

    */

    public static String encodeFile(String filePath) throws Exception {

        byte[] bytes = fileToByte(filePath);

        return encode(bytes);

    }

    /** */

/**

    *

    * BASE64字符串转回文件

    *

    *

    * @param filePath

    *            文件绝对路径

    * @param base64

    *            编码字符串

    * @throws Exception

    */

    public static void decodeToFile(String filePath, String base64)

            throws Exception {

        byte[] bytes = decode(base64);

        byteArrayToFile(bytes, filePath);

    }

    /** */

/**

    *

    * 文件转换为二进制数组

    *

    *

    * @param filePath

    *            文件路径

    * @return

    * @throws 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;

    }

    /** */

/**

    *

    * 二进制数据写文件

    *

    *

    * @param bytes

    *            二进制数据

    * @param filePath

    *            文件生成目录

*/

    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();

    }

}

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,847评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,208评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,587评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,942评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,332评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,587评论 1 218
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,853评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,568评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,273评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,542评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,033评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,373评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,031评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,073评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,830评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,628评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,537评论 2 269

推荐阅读更多精彩内容

  • Base64.java public final class Base64 { static private ...
    BUG弄潮儿阅读 741评论 0 0
  • 概述 之前一直对加密相关的算法知之甚少,只知道类似DES、RSA等加密算法能对数据传输进行加密,且各种加密算法各有...
    Henryzhu阅读 2,931评论 0 14
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,100评论 18 139
  • 福到了 老词啦 总觉得这个对联很经典 学写隶书 感觉楷书不见长进 米芾的影子也木看出来 特写一下 横批也要有滴 写...
    何处落风送暗香阅读 424评论 0 5
  • 退去了激情,他发现他不爱你了,他要求分手。 你难过,哭泣着答应,事后的每一天,你会伤感,会睹物思人,会一个人无厘头...
    几何月阅读 296评论 0 1