`
caniggia1986
  • 浏览: 149361 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

RSA使用X509EncodedKeySpec、PKCS8EncodedKeySpec生成公钥和私钥

阅读更多
	private static final String KEY_ALGORITHM = "RSA";  
	private static final String PUBLIC_KEY ="publicKey";
	private static final String PRIVATE_KEY ="privateKey"; 
        public static void main(String[] args) throws Exception{
		Map<String,String> keyMap = genKey();
		RSAPublicKey publicKey = getPublicKey(keyMap.get(PUBLIC_KEY));
		RSAPrivateKey privateKey = getPrivateKey(keyMap.get(PRIVATE_KEY));
		String info ="明文123456";
		//加密
		byte[] bytes = encrypt(info.getBytes("utf-8"),publicKey);
		//解密
		bytes = decrypt(bytes, privateKey);
		System.out.println(new String(bytes,"utf-8"));
		 
	}
	
	public static Map<String,String> genKey() throws NoSuchAlgorithmException{
		Map<String,String> keyMap = new HashMap<String,String>();
		KeyPairGenerator keygen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
		SecureRandom random = new SecureRandom();
		// random.setSeed(keyInfo.getBytes());
		// 初始加密,512位已被破解,用1024位,最好用2048位
		keygen.initialize(1024, random);
		// 取得密钥对
		KeyPair kp = keygen.generateKeyPair();
		RSAPrivateKey privateKey = (RSAPrivateKey)kp.getPrivate();
 		String privateKeyString = Base64.encode(privateKey.getEncoded());
		RSAPublicKey publicKey = (RSAPublicKey)kp.getPublic(); 
		String publicKeyString = Base64.encode(publicKey.getEncoded());
		keyMap.put(PUBLIC_KEY, publicKeyString);
		keyMap.put(PRIVATE_KEY, privateKeyString);
		return keyMap;
	}
	
	public static RSAPublicKey getPublicKey(String publicKey) throws Exception{
		byte[] keyBytes = LBase64.decode(publicKey);
		X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
		return (RSAPublicKey) keyFactory.generatePublic(spec);
	}
	
	public static RSAPrivateKey getPrivateKey(String privateKey) throws Exception{
		byte[] keyBytes = LBase64.decode(privateKey);
		PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
		return (RSAPrivateKey) keyFactory.generatePrivate(spec);
	}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics