RsaHelper.java 16 KB
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 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
package com.yanzuoguang.util.helper;

import com.yanzuoguang.util.YzgError;
import com.yanzuoguang.util.log.Log;
import org.springframework.util.Base64Utils;

import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * RSA
 * # 知识点
 * 1. 从一个固定长度的字节数组转换为另外一个固定长度的字节数组。如117的加密对应128的解密
 * 2. RSA分为公钥+私钥
 * 3. 可以用公钥加密+私钥解密 或者 私钥加密+公钥解密
 * 4. 因为加密只有字节,所以需要转换为base64
 * <p>
 * # 流程
 * 1. 生成公钥私钥
 * 2. 将公钥转换为字节,然后转换为base64字符串
 * 3. 将私钥转换为字节,然后转换为base64字符串
 * 4. 将来源字符串转换为字节,并按照固定加密长度截断,依次用公钥字符串生成的公钥进行加密。将加密后的字节转换为base64字符串。
 * 5. 将需要解密的字符串转换为字节,按照固定解密长度阶段,依次用私钥字符串生成的私钥进行解密。
 *
 * @author 颜佐光
 */
public final class RsaHelper {

    private static final String ALGORITHM_RSA = "RSA";

    private static final String ALGORITHM_SIGN = "MD5withRSA";

    private static final int KEYPAIR_LEN = 1024;
    /**
     * RSA最大加密明文大小
     */
    private static final int MAX_ENCRYPT_BLOCK = 117;

    /**
     * RSA最大解密密文大小
     */
    private static final int MAX_DECRYPT_BLOCK = 128;

    private RsaHelper() {
        super();
    }

    private interface HandleBytes {
        byte[] handle(byte[] from, int offset, int len) throws Exception;
    }

    private static byte[] handle(byte[] froms, int size, HandleBytes handle) throws Exception {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int inputLen = froms.length;
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段加密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > size) {
                cache = handle.handle(froms, offSet, size);
            } else {
                cache = handle.handle(froms, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * size;
        }
        byte[] to = out.toByteArray();
        out.close();
        return to;
    }

    /**
     * 生成密钥对
     */
    public static void generatorKeyPair() {
        try {
            RsaInfo rsaInfo = generatorRsa();
            Log.info(RsaHelper.class, "生成的公钥:%s\n生成的私钥:%s", rsaInfo.getPublicKey(), rsaInfo.getPrivateKey());
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    /**
     * 生成密钥对
     *
     * @return 返回值
     */
    public static RsaInfo generatorRsa() {
        try {
            KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(ALGORITHM_RSA);
            keyPairGen.initialize(KEYPAIR_LEN);
            KeyPair keyPair = keyPairGen.generateKeyPair();
            RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
            RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();

            return new RsaInfo(rsaPublicKey, rsaPrivateKey);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    /**
     * 获取公钥
     *
     * @return 公钥
     */
    public static PublicKey getPublicKey(String publicKey) {
        try {
            X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(decodeBase64(publicKey));
            KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM_RSA);
            return keyFactory.generatePublic(publicKeySpec);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    /**
     * 获取私钥
     *
     * @return 私钥
     */
    public static PrivateKey getPrivateKey(String privateKey) {
        try {
            PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(decodeBase64(privateKey));
            KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM_RSA);
            return keyFactory.generatePrivate(privateKeySpec);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    /**
     * 公钥加密,需要用私钥解密
     *
     * @param source       源代码
     * @param publicKeyStr 公钥base64字符串
     * @return 返回值
     */
    public static String encryptionByPublicKey(String source, String publicKeyStr) {
        PublicKey publicKey = getPublicKey(publicKeyStr);
        return encryptionByPublicKey(source, publicKey);
    }

    /**
     * 公钥加密,需要用私钥解密
     *
     * @param source    源代码
     * @param publicKey 公钥
     * @return 返回值
     */
    public static String encryptionByPublicKey(String source, PublicKey publicKey) {
        try {
            Cipher cipher = Cipher.getInstance(publicKey.getAlgorithm());
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);

            byte[] bytes = source.getBytes(StandardCharsets.UTF_8);
            byte[] to = handle(bytes, MAX_ENCRYPT_BLOCK, cipher::doFinal);
            return encodeBase64(to);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    /**
     * 公钥解密,解密私钥加密的字符串
     *
     * @param target       私钥加密的值
     * @param publicKeyStr 公钥
     * @return 返回值
     */
    public static String decryptionByPublicKey(String target, String publicKeyStr) {
        PublicKey publicKey = getPublicKey(publicKeyStr);
        return decryptionByPublicKey(target, publicKey);
    }

    /**
     * 公钥解密,解密私钥加密的字符串
     *
     * @param target    私钥加密的值
     * @param publicKey 公钥
     * @return 返回值
     */
    public static String decryptionByPublicKey(String target, PublicKey publicKey) {
        try {
            byte[] bytes = decodeBase64(target);

            Cipher cipher = Cipher.getInstance(publicKey.getAlgorithm());
            cipher.init(Cipher.DECRYPT_MODE, publicKey);

            byte[] to = handle(bytes, MAX_DECRYPT_BLOCK, cipher::doFinal);
            return new String(to, StandardCharsets.UTF_8);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    /**
     * 公钥验证签名
     *
     * @param target       私钥加密的值
     * @param sign         签名
     * @param publicKeyStr 公钥
     * @return 返回值
     */
    public static boolean verifyByPublicKey(String target, String sign, String publicKeyStr) {
        PublicKey publicKey = getPublicKey(publicKeyStr);
        return verifyByPublicKey(target, sign, publicKey);
    }

    /**
     * 公钥验证签名
     *
     * @param target    私钥加密的值
     * @param sign      签名
     * @param publicKey 公钥
     * @return 返回值
     */
    public static boolean verifyByPublicKey(String target, String sign, PublicKey publicKey) {
        try {
            Signature signature = Signature.getInstance(ALGORITHM_SIGN);
            signature.initVerify(publicKey);
            signature.update(target.getBytes(StandardCharsets.UTF_8));
            return signature.verify(decodeBase64(sign));
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    /**
     * 私钥加密,要用公钥解密
     *
     * @param source        原字符串
     * @param privateKeyStr 私钥base64字符串
     * @return 返回值
     */
    public static String encryptionByPrivateKey(String source, String privateKeyStr) {
        PrivateKey privateKey = getPrivateKey(privateKeyStr);
        return encryptionByPrivateKey(source, privateKey);
    }

    /**
     * 私钥加密,要用公钥解密
     *
     * @param source     原字符串
     * @param privateKey 私钥
     * @return 返回值
     */
    public static String encryptionByPrivateKey(String source, PrivateKey privateKey) {
        try {
            byte[] bytes = source.getBytes(StandardCharsets.UTF_8);

            Cipher cipher = Cipher.getInstance(privateKey.getAlgorithm());
            cipher.init(Cipher.ENCRYPT_MODE, privateKey);

            byte[] to = handle(bytes, MAX_ENCRYPT_BLOCK, cipher::doFinal);

            return encodeBase64(to);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    /**
     * 私钥解密,解密公钥加密后的字符串
     *
     * @param target        加密字符
     * @param privateKeyStr base64位的私钥
     * @return 返回值
     */
    public static String decryptionByPrivateKey(String target, String privateKeyStr) {
        PrivateKey privateKey = getPrivateKey(privateKeyStr);
        return decryptionByPrivateKey(target, privateKey);
    }

    /**
     * 私钥解密,解密公钥加密后的字符串
     *
     * @param target     加密字符
     * @param privateKey 私钥
     * @return 返回值
     */
    public static String decryptionByPrivateKey(String target, PrivateKey privateKey) {
        try {
            byte[] bytes = decodeBase64(target);
            Cipher cipher = Cipher.getInstance(privateKey.getAlgorithm());
            cipher.init(Cipher.DECRYPT_MODE, privateKey);

            byte[] to = handle(bytes, MAX_DECRYPT_BLOCK, cipher::doFinal);

            return new String(to, StandardCharsets.UTF_8);
        } catch (Exception ex) {
            throw YzgError.getRuntimeException(ex, "056", ex.getMessage());
        }
    }

    /**
     * 私钥签名
     *
     * @param target        原字符
     * @param privateKeyStr 私钥
     * @return 签名值
     */
    public static String signByPrivateKey(String target, String privateKeyStr) {
        PrivateKey privateKey = getPrivateKey(privateKeyStr);
        return signByPrivateKey(target, privateKey);
    }

    /**
     * 私钥签名
     *
     * @param target     原字符串
     * @param privateKey 私钥
     * @return 签名值
     */
    public static String signByPrivateKey(String target, PrivateKey privateKey) {
        try {
            Signature signature = Signature.getInstance(ALGORITHM_SIGN);
            signature.initSign(privateKey);
            signature.update(target.getBytes(StandardCharsets.UTF_8));
            return encodeBase64(signature.sign());
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    /**
     * base64编码
     *
     * @param source 原字符
     * @return 编码
     */
    public static String encodeBase64(byte[] source) {
        try {
            byte[] to = Base64Utils.encode(source);
            return new String(to, StandardCharsets.UTF_8);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    /**
     * Base64解码
     *
     * @param target 原字符
     * @return 解码
     */
    public static byte[] decodeBase64(String target) {
        try {
            byte[] from = target.getBytes(StandardCharsets.UTF_8);
            return Base64Utils.decode(from);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    /**
     * 解密信息
     *
     * @param rsaJsonPwd 加密后的json字符串
     * @param publicKey  公钥
     * @param timeout    超时时间
     * @return 返回值
     */
    public static String decodeRsaValueInfo(String rsaJsonPwd, PublicKey publicKey, long timeout) {
        String rsaJson = decryptionByPublicKey(rsaJsonPwd, publicKey);
        return checkTimeout(timeout, rsaJson);
    }

    /**
     * 解密信息
     *
     * @param rsaJsonPwd 加密后的json字符串
     * @param privateKey 私钥
     * @param timeout    超时时间
     * @return 返回值
     */
    public static String decodeRsaValueInfo(String rsaJsonPwd, PrivateKey privateKey, long timeout) {
        String rsaJson = decryptionByPrivateKey(rsaJsonPwd, privateKey);
        return checkTimeout(timeout, rsaJson);
    }

    private static String checkTimeout(long timeout, String rsaJson) {
        RsaValueInfo rsaValueInfo = JsonHelper.deserialize(rsaJson, RsaValueInfo.class);
        long splitTime = System.currentTimeMillis() / 1000 - rsaValueInfo.getT();
        if (splitTime > timeout && timeout > 0) {
            throw YzgError.getRuntimeException("999");
        }
        return rsaValueInfo.getV();
    }

    /**
     * 解密信息
     *
     * @param value     私钥
     * @param publicKey 公钥
     * @return 返回值
     */
    public static String encodeRsaValueInfo(String value, PublicKey publicKey) {
        RsaValueInfo info = new RsaValueInfo(value);
        String json = JsonHelper.serialize(info);
        return encryptionByPublicKey(json, publicKey);
    }

    /**
     * 解密信息
     *
     * @param value      私钥
     * @param privateKey 私钥
     * @return 返回值
     */
    public static String encodeRsaValueInfo(String value, PrivateKey privateKey) {
        RsaValueInfo info = new RsaValueInfo(value);
        String json = JsonHelper.serialize(info);
        return encryptionByPrivateKey(json, privateKey);

    }

    /**
     * RSA加密值信息
     */
    public static class RsaValueInfo {
        /**
         * 加密值
         */
        private String v;
        /**
         * Linux时间错(秒)
         */
        private long t = System.currentTimeMillis() / 1000;

        public RsaValueInfo(String v) {
            this.v = v;
        }

        public RsaValueInfo(String v, long t) {
            this.v = v;
            this.t = t;
        }

        public String getV() {
            return v;
        }

        public void setV(String v) {
            this.v = v;
        }

        public long getT() {
            return t;
        }

        public void setT(long t) {
            this.t = t;
        }
    }

    /**
     * RSA公钥信息
     */
    public static class RsaInfo {
        /**
         * 公钥
         */
        private PublicKey publicKeyFrom;
        /**
         * 私钥
         */
        private PrivateKey privateKeyFrom;
        /**
         * 公钥
         */
        private String publicKey;
        /**
         * 私钥
         */
        private String privateKey;

        public RsaInfo() {
        }

        public RsaInfo(PublicKey publicKeyFrom, PrivateKey privateKeyFrom) {
            this.publicKeyFrom = publicKeyFrom;
            this.privateKeyFrom = privateKeyFrom;
            this.initToWithFrom();
        }

        public RsaInfo(String publicKey, String privateKey) {
            this.publicKey = publicKey;
            this.privateKey = privateKey;
            this.initFromWithTo();
        }

        public void initToWithFrom() {
            this.publicKey = encodeBase64(this.publicKeyFrom.getEncoded());
            this.privateKey = encodeBase64(this.privateKeyFrom.getEncoded());
        }

        public void initFromWithTo() {
            this.publicKeyFrom = RsaHelper.getPublicKey(this.publicKey);
            this.privateKeyFrom = RsaHelper.getPrivateKey(this.privateKey);
        }

        public PublicKey getPublicKeyFrom() {
            return publicKeyFrom;
        }

        public void setPublicKeyFrom(PublicKey publicKeyFrom) {
            this.publicKeyFrom = publicKeyFrom;
        }

        public PrivateKey getPrivateKeyFrom() {
            return privateKeyFrom;
        }

        public void setPrivateKeyFrom(PrivateKey privateKeyFrom) {
            this.privateKeyFrom = privateKeyFrom;
        }

        public String getPublicKey() {
            return publicKey;
        }

        public void setPublicKey(String publicKey) {
            this.publicKey = publicKey;
        }

        public String getPrivateKey() {
            return privateKey;
        }

        public void setPrivateKey(String privateKey) {
            this.privateKey = privateKey;
        }
    }
}