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[wang_cy1@suixingpay.com]
*
*/
@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());
}
}