創建RSA共私鑰

import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.codec.binary.Base64;
import org.junit.Test;

import lombok.extern.slf4j.Slf4j;

/**
 * 創建RSA公私鑰
 * 
 * @author wangcaiyan[[email protected]]
 *
 */
@Slf4j
public class CreateRsaKey {

    // 非對稱加密密鑰算法
    public static final String KEY_ALGORITHM = "RSA";
    // 公鑰
    private static final String PUBLIC_KEY = "RSAPublicKey";
    // 私鑰
    private static final String PRIVATE_KEY = "RSAPrivateKey";

    /**
     * RSA密鑰長度默認1024位,密鑰長度必須是64的倍數,範圍在512~65536之間
     */
    private static final int KEY_SIZE = 2048;

    @Test
    public void test() throws NoSuchAlgorithmException {
        initKeys();
    }
    
    public void initKeys() throws NoSuchAlgorithmException {
        // 初始化密鑰對
        Map<String, Object> keyMap =  initKey();
        String pubKey = getPublicKey(keyMap);
        log.info("公鑰:[{}]", pubKey);
        String pivKey = getPrivateKey(keyMap);
        log.info("私鑰:[{}]", pivKey);
    }

    /**
     * 初始化密鑰
     * 
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static Map<String, Object> initKey() throws NoSuchAlgorithmException {
        // 實例化密鑰對生成器
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
        // 初始化密鑰對生成器
        keyPairGen.initialize(KEY_SIZE);
        // 生成密鑰對
        KeyPair keyPair = keyPairGen.generateKeyPair();
        // 公鑰
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        log.info("公鑰:[{}]", publicKey);
        // 私鑰
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        log.info("私鑰:[{}]", privateKey);
        // 封裝私鑰
        Map<String, Object> keyMap = new HashMap<>();
        keyMap.put("publicKey", publicKey);
        keyMap.put("privateKey", privateKey);
        return keyMap;
    }
    
    /**
     * 取得公鑰
     * @param keyMap
     * @return
     */
    public static String getPublicKey(Map<String, Object> keyMap) {
        Key key = (Key) keyMap.get("publicKey");
        return Base64.encodeBase64String(key.getEncoded());
    }
    
    /**
     * 取得私鑰
     * @param keyMap
     * @return
     */
    public static String getPrivateKey(Map<String, Object> keyMap) {
        Key key = (Key) keyMap.get("privateKey");
        return Base64.encodeBase64String(key.getEncoded());
    }

}
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章