All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.kaizen4j.common.encrypt.RSA Maven / Gradle / Ivy

There is a newer version: 1.3.8.RELEASE
Show newest version
package org.kaizen4j.common.encrypt;

import com.google.common.base.Throwables;
import org.apache.commons.codec.binary.Base64;

import java.nio.charset.StandardCharsets;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * RSA 加密算法类
 */
public final class RSA {

    private static final String ALGORITHM = "RSA";

    private static final int KEY_SIZE = 1024;

    private String publicKey;

    private String privateKey;

    /**
     * RSA 构造函数
     *
     * @param seed 种子
     *
     * @throws NoSuchAlgorithmException
     */
    public RSA(String seed) {
        try {
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM);
            SecureRandom secureRandom = new SecureRandom();
            secureRandom.setSeed(seed.getBytes(StandardCharsets.UTF_8));

            keyPairGenerator.initialize(KEY_SIZE, secureRandom);
            KeyPair keyPair = keyPairGenerator.genKeyPair();

            this.publicKey = Base64.encodeBase64String(keyPair.getPublic().getEncoded());
            this.privateKey = Base64.encodeBase64String(keyPair.getPrivate().getEncoded());
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

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

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

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy