首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

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

2012-10-20 
RSA使用X509EncodedKeySpec、PKCS8EncodedKeySpec生成公钥和私钥private static final String KEY_ALGORITH

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);}

热点排行