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 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 genKey() throws NoSuchAlgorithmException{  
    Map keyMap = new HashMap();  
    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);  
}

你可能感兴趣的:(RSA使用X509EncodedKeySpec、PKCS8EncodedKeySpec生成公钥和私钥)