/** 指定key的大小 */ private static int KEYSIZE = 1024; // 字符集 private final static String CHARACTER_SET = "UTF-8"; // rsa 加密方式 public static final String RSA_ALGORITHM = "RSA/ECB/PKCS1Padding"; /** * * 描述:RSA 生成公鑰、私鑰對 * * @return * @throws Exception * @author yangyongchuan 2016年11月8日 上午10:16:56 * @version 1.0 */ public static Map<String, String> generateKeyPair() throws Exception { /** RSA算法要求有一個可信任的隨機數源 */ SecureRandom sr = new SecureRandom(); /** 爲RSA算法建立一個KeyPairGenerator對象 */ KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); /** 利用上面的隨機數據源初始化這個KeyPairGenerator對象 */ kpg.initialize(KEYSIZE, sr); /** 生成密匙對 */ KeyPair kp = kpg.generateKeyPair(); /** 獲得公鑰 */ Key publicKey = kp.getPublic(); byte[] publicKeyBytes = publicKey.getEncoded(); String pub = new String(Base64.encodeBase64(publicKeyBytes), CHARACTER_SET); /** 獲得私鑰 */ Key privateKey = kp.getPrivate(); byte[] privateKeyBytes = privateKey.getEncoded(); String pri = new String(Base64.encodeBase64(privateKeyBytes), CHARACTER_SET); Map<String, String> map = new HashMap<String, String>(); map.put("publicKey", pub); map.put("privateKey", pri); RSAPublicKey rsp = (RSAPublicKey) kp.getPublic(); BigInteger bint = rsp.getModulus(); byte[] b = bint.toByteArray(); byte[] deBase64Value = Base64.encodeBase64(b); String retValue = new String(deBase64Value); map.put("modulus", retValue); return map; }
RSA 生成公鑰私鑰對。在map中獲取"publicKey","privateKey"。java