Skip to content
RSAUtils.java 16.6 KiB
Newer Older
杨郁彬's avatar
杨郁彬 committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
package com.cesgroup.bdc.util;

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.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.Base64.Encoder;

/**
 * RSA加密解密工具类,适合对不大数据量加密、解密。
 * 
 * 一般使用公钥加密,私钥解密,但也可以使用私钥加密,公钥解密。
 * 
 * @author khaoth
 */
public class RSAUtils {

    /**
     * 一次数据加密处理的最大长度的值默认值。默认使用1024(128字节)长度的密钥,默认padding(填充数据)占用11个字节是设置的值(128-11=117)。
     */
    private static final int MAX_ENCRYPT_BLOCK = 117;

    /**
     * 一次数据解密处理的最大长度的值默认值。默认使用1024(128字节)长度密钥。
     */
    private static final int MAX_DECRYPT_BLOCK = 128;

    /**
     * 算法
     */
    private static final String ALGORITHM = "RSA";

    /**
     * 参数的编码。
     */
    private final static String CHARSET = "UTF-8";

    /**
     * RSA 生成的密钥对。
     * 
     * @author khaoth
     */
    public static class RSAKeyPair {

        /**
         * RSA公钥字符串,通过base64编码
         */
        private String publicKey;

        /**
         * RSA私钥字符串,通过base64编码
         */
        private String privateKey;

        /**
         * RSA公钥对象
         */
        private RSAPublicKey rsaPublicKey;

        /**
         * RSA私钥对象
         */
        private RSAPrivateKey rsaPrivateKey;

        /**
         * 构造函数,初始化
         * 
         * @param rsaPublicKey
         * @param rsaPrivateKey
         */
        RSAKeyPair(RSAPublicKey rsaPublicKey, RSAPrivateKey rsaPrivateKey) {

            Encoder base64Encoder = Base64.getEncoder();
            this.publicKey = base64Encoder.encodeToString(rsaPublicKey.getEncoded());
            this.privateKey = base64Encoder.encodeToString(rsaPrivateKey.getEncoded());
            this.rsaPublicKey = rsaPublicKey;
            this.rsaPrivateKey = rsaPrivateKey;
        }

        /**
         * 获取base64编码的RSA公钥字符串
         * 
         * @return
         */
        public String getPublicKey() {
            return publicKey;
        }

        /**
         * 获取base64编码的RSA私钥字符串
         * 
         * @return
         */
        public String getPrivateKey() {
            return privateKey;
        }

        /**
         * 获取RSA公钥对象
         * 
         * @return
         */
        public RSAPublicKey getRsaPublicKey() {
            return rsaPublicKey;
        }

        /**
         * 获取RSA私钥对象
         * 
         * @return
         */
        public RSAPrivateKey getRsaPrivateKey() {
            return rsaPrivateKey;
        }
    }

    /**
     * 随机生成密钥对
     *
     *            生成密钥,长度1024。
     * @throws NoSuchAlgorithmException
     */
    public static RSAKeyPair genKeyPair1024() throws NoSuchAlgorithmException {

        return RSAUtils.genKeyPair(1024);
    }

    /**
     * 随机生成密钥对
     *
     *            生成密钥,长度2048。
     * @throws NoSuchAlgorithmException
     */
    public static RSAKeyPair genKeyPair2048() throws NoSuchAlgorithmException {

        return RSAUtils.genKeyPair(2048);
    }

    /**
     * 随机生成密钥对
     * 
     * @param keySize
     *            生成密钥长度,一般为1024或2048。生成的密钥长度会与一次数据加密、解密处理的最大长度有关。
     * @throws NoSuchAlgorithmException
     */
    public static RSAKeyPair genKeyPair(int keySize) throws NoSuchAlgorithmException {

        // KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(ALGORITHM);
        keyPairGen.initialize(keySize, new SecureRandom());
        // 生成一个密钥对,保存在keyPair中
        KeyPair keyPair = keyPairGen.generateKeyPair();
        // 得到公钥
        RSAPublicKey rsaPublicKey = (RSAPublicKey)keyPair.getPublic();
        // 得到私钥
        RSAPrivateKey rsaPrivateKey = (RSAPrivateKey)keyPair.getPrivate();

        return new RSAKeyPair(rsaPublicKey, rsaPrivateKey);
    }

    /**
     * 使用密钥加密数据。
     * 
     * 返回的密文做base64编码处理。
     * 
     * 适用密钥小于等于为128字节,padding(填充数据)占用11个字节。
     * 
     * @param text
     *            原文。
     * @param publicKey
     *            使用公钥加密,经过base64编码。
     * @return
     * @throws Exception
     */
    public static String encrypt(String text, String publicKey) throws Exception {

        return Base64.getEncoder()
            .encodeToString(crypto(null, text, getRSAPublicKey(publicKey), Cipher.ENCRYPT_MODE, MAX_ENCRYPT_BLOCK));
    }

    /**
     * 使用密钥解密数据。
     *
     * 适用密钥小于等于128字节。
     *
     * @param ciphertext
     *            密文。密文为base64编码的值。
     * @param privateKey
     *            使用私钥解密,经过base64编码。
     * @return
     * @throws Exception
     */
    public static String decrypt(String ciphertext, String privateKey) throws Exception {

        return new String(
                crypto(null, ciphertext, getRSAPrivateKey(privateKey), Cipher.DECRYPT_MODE, MAX_DECRYPT_BLOCK), CHARSET);
    }

    /**
     * 使用密钥加密数据。
     * 
     * 返回的密文做base64编码处理。
     * 
     * @param text
     *            原文。
     * @param publicKey
     *            使用公钥加密,经过base64编码。
     * @param maxSize
     *            一次数据加密处理的最大长度。加密时最大长度不能超过密钥的字节数减去padding(填充数据)占用的字节数
     * @return
     * @throws Exception
     */
    public static String encrypt(String text, String publicKey, int maxSize) throws Exception {

        return Base64.getEncoder()
            .encodeToString(crypto(null, text, getRSAPublicKey(publicKey), Cipher.ENCRYPT_MODE, maxSize));
    }

    /**
     * 使用密钥解密数据。
     *
     * @param ciphertext
     *            密文。密文为base64编码的值。
     * @param privateKey
     *            使用私钥解密,经过base64编码。
     * @param maxSize
     *            一次数据解密处理的最大长度。解密时最大长度不能超过密钥的字节数
     * @return
     * @throws Exception
     */
    public static String decrypt(String ciphertext, String privateKey, int maxSize) throws Exception {

        return new String(crypto(null, ciphertext, getRSAPrivateKey(privateKey), Cipher.DECRYPT_MODE, maxSize),
            CHARSET);
    }

    /**
     * 使用密钥加密数据。
     * 
     * 返回的密文做base64编码处理。
     * 
     * @param cipher
     *            加密解、密处理对象。
     * @param text
     *            原文。
     * @param publicKey
     *            使用公钥加密,经过base64编码。
     * @param maxSize
     *            一次数据加密处理的最大长度。加密时最大长度不能超过密钥的字节数减去padding(填充数据)占用的字节数
     * @return
     * @throws Exception
     */
    public static String encrypt(Cipher cipher, String text, String publicKey, int maxSize) throws Exception {

        return Base64.getEncoder()
            .encodeToString(crypto(cipher, text, getRSAPublicKey(publicKey), Cipher.ENCRYPT_MODE, maxSize));
    }

    /**
     * 使用密钥解密数据。
     * 
     * @param cipher
     *            加密解、密处理对象。
     *
     * @param ciphertext
     *            密文。密文为base64编码的值。
     * @param privateKey
     *            使用私钥解密,经过base64编码。
     * @param maxSize
     *            一次数据解密处理的最大长度。解密时最大长度不能超过密钥的字节数
     * @return
     * @throws Exception
     */
    public static String decrypt(Cipher cipher, String ciphertext, String privateKey, int maxSize) throws Exception {

        return new String(crypto(cipher, ciphertext, getRSAPrivateKey(privateKey), Cipher.DECRYPT_MODE, maxSize),
            CHARSET);
    }

    /**
     * 使用密钥加密数据。
     * 
     * 返回的密文做base64编码处理。
     * 
     * 适用密钥小于等于为128字节,padding(填充数据)占用11个字节。
     * 
     * @param text
     *            原文。
     * @param key
     *            密钥,一般使用公钥加密。
     * @return
     * @throws Exception
     */
    public static String encrypt(String text, Key key) {

        return Base64.getEncoder().encodeToString(crypto(null, text, key, Cipher.ENCRYPT_MODE, MAX_ENCRYPT_BLOCK));
    }

    /**
     * 使用密钥解密数据。
     * 
     * 适用密钥小于等于128字节。
     *
     * @param ciphertext
     *            密文。密文为base64编码的值。
     * @param key
     *            密钥。一般使用私钥解密。
     * @return
     * @throws Exception
     */
    public static String decrypt(String ciphertext, Key key) throws Exception {

        return new String(crypto(null, ciphertext, key, Cipher.DECRYPT_MODE, MAX_DECRYPT_BLOCK), CHARSET);
    }

    /**
     * 使用密钥加密数据。
     * 
     * 返回的密文做base64编码处理。
     * 
     * @param text
     *            原文。
     * @param key
     *            密钥,一般使用公钥加密。
     * @param maxSize
     *            一次数据加密处理的最大长度。加密时最大长度不能超过密钥的字节数减去padding(填充数据)占用的字节数
     * @return
     * @throws Exception
     */
    public static String encrypt(String text, Key key, int maxSize) {

        return Base64.getEncoder().encodeToString(crypto(null, text, key, Cipher.ENCRYPT_MODE, maxSize));
    }

    /**
     * 使用密钥解密数据。
     *
     * @param ciphertext
     *            密文。密文为base64编码的值。
     * @param key
     *            密钥。一般使用私钥解密。
     * @param maxSize
     *            一次数据解密处理的最大长度。解密时最大长度不能超过密钥的字节数
     * @return
     * @throws Exception
     */
    public static String decrypt(String ciphertext, Key key, int maxSize) throws Exception {

        return new String(crypto(null, ciphertext, key, Cipher.DECRYPT_MODE, maxSize), CHARSET);
    }

    /**
     * 使用密钥加密数据。
     * 
     * 返回的密文做base64编码处理。
     * 
     * @param cipher
     *            加密解、密处理对象。
     * @param text
     *            原文。
     * @param key
     *            密钥,一般使用公钥加密。
     * @param maxSize
     *            一次数据加密处理的最大长度。加密时最大长度不能超过密钥的字节数减去padding(填充数据)占用的字节数
     * @return
     * @throws Exception
     */
    public static String encrypt(Cipher cipher, String text, Key key, int maxSize) {

        return Base64.getEncoder().encodeToString(crypto(cipher, text, key, Cipher.ENCRYPT_MODE, maxSize));
    }

    /**
     * 使用密钥解密数据。
     * 
     * @param cipher
     *            加密解、密处理对象。
     *
     * @param ciphertext
     *            密文。密文为base64编码的值。
     * @param key
     *            密钥。一般使用私钥解密。
     * @param maxSize
     *            一次数据解密处理的最大长度。解密时最大长度不能超过密钥的字节数
     * @return
     * @throws Exception
     */
    public static String decrypt(Cipher cipher, String ciphertext, Key key, int maxSize) throws Exception {

        return new String(crypto(cipher, ciphertext, key, Cipher.DECRYPT_MODE, maxSize), CHARSET);
    }

    /**
     * 使用密钥解密数据。
     * 
     * @param cipher
     *            加密解、密处理对象。
     * @param text
     *            需加密、解密的文本。
     * @param key
     *            密钥。
     * @param mode
     *            初始化模式(加密、解密),传入Cipher.ENCRYPT_MODE或Cipher.DECRYPT_MODE的值
     * @param maxSize
     *            最大处理能力(需要根据实际情况进行调整)。
     * @return
     */
    private static byte[] crypto(Cipher cipher, String text, Key key, int mode, int maxSize) {

        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            // 获取指定算法Cipher对象
            cipher = cipher == null ? Cipher.getInstance(ALGORITHM) : cipher;

            // 初始化模式(加密、解密)和密钥
            cipher.init(mode, key);

            byte[] data = null;

            // 判断是加密还是解密,做不同操作
            if (mode == Cipher.DECRYPT_MODE) {
                data = Base64.getDecoder().decode(text);
            } else if (mode == Cipher.ENCRYPT_MODE) {
                data = text.getBytes(CHARSET);
            }

            segCrypto(cipher, baos, data, maxSize);
            return baos.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 分段加密解密数据。
     * 
     * 由于加密/解密处理byte数据时,不同环境下最大处理长度不同,故需要设置参数maxSize,分段处理。
     *
     * @param cipher
     *            Cipher对象。
     * @param baos
     *            输出流
     * @param data
     *            要处理的byte数组。
     * @param maxSize
     *            一次数据加密、解密处理的最大长度的值。
     * @return
     * @throws Exception
     */
    private static void segCrypto(Cipher cipher, ByteArrayOutputStream baos, byte[] data, int maxSize)
        throws Exception {

        // 总数据长度
        int total = data.length;
        // 偏移量
        int offset = 0;
        // 缓冲区
        byte[] buffer;
        // 如果数据没有处理完, 就一直继续
        while (total - offset > 0) {
            // 如果剩余的数据 >= 最大处理能力, 就按照最大处理能力来加密数据
            if (total - offset >= maxSize) {
                // 加密数据
                buffer = cipher.doFinal(data, offset, maxSize);
                // 偏移量向右侧偏移最大数据能力个
                offset += maxSize;
            } else {
                // 如果剩余的数据 < 最大处理能力, 就按照剩余的个数来加密数据
                buffer = cipher.doFinal(data, offset, total - offset);
                // 偏移量设置为总数据长度, 这样可以跳出循环
                offset = total;
            }
            // 向输出流写入数据
            baos.write(buffer);
        }
    }

    /**
     * 字符串的公钥转为RSAPublicKey对象。
     * 
     * @param publicKey
     *            经过base64编码的RSA公钥。
     * @return
     * @throws Exception
     */
    public static RSAPublicKey getRSAPublicKey(String publicKey) throws Exception {

        // 通过X509编码的Key指令获得公钥对象
        KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(publicKey));
        RSAPublicKey key = (RSAPublicKey)keyFactory.generatePublic(x509KeySpec);
        return key;
    }

    /**
     * 字符串的私钥转为RSAPrivateKey对象。
     * 
     * @param privateKey
     *            经过base64编码的RSA私钥。
     * @return
     * @throws Exception
     */
    public static RSAPrivateKey getRSAPrivateKey(String privateKey) throws Exception {
        // 通过PKCS#8编码的Key指令获得私钥对象
        KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKey));
        RSAPrivateKey key = (RSAPrivateKey)keyFactory.generatePrivate(pkcs8KeySpec);
        return key;
    }
    public static void main(String[] args) {
        try {
            RSAKeyPair  rsaKeyPair= RSAUtils.genKeyPair1024();
            String private_key = rsaKeyPair.getPrivateKey();
            String public_key = rsaKeyPair.getPublicKey();
            System.out.println("private_key==》"+private_key);
            System.out.println("public_key==》"+public_key);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }

}