非对称加密拥有两个密钥:公开密钥(publickey)和私有密钥(privatekey)。通常使用公钥加密,只有使用对应的私钥才能够解密。
非对称加密主要算法有:RSA、Elgamal、背包算法、Rabin、D-H、ECC(椭圆曲线加密算法)等
非对称加密执行的步骤顺序:
1、先获取KeyPair对象;
2、获取字符串的公钥/私钥;
3、将字符串的公钥/私钥转换成为公钥/私钥类对象;
4、使用类对象的公钥进行数据加密;
5、使用类对象的私钥进行解密。
RSA算法
目前最常用的非对称加密算法就是RSA算法,是Rivest, Shamir, 和Adleman于1978年发明,他们那时都是在MIT。
/** * 获取秘钥KeyPair * @return * @throws Exception */ public static KeyPair getKeyPair() throws Exception { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(512); KeyPair keyPair = keyPairGenerator.generateKeyPair(); return keyPair; } /** * RSA 获取String公钥 * @param keyPair * @return */ public static String getPublicKey(KeyPair keyPair) { PublicKey publicKey = keyPair.getPublic(); byte[] bytes = publicKey.getEncoded(); return byte2base64(bytes); } /** * RSA 获取String私钥 * @param keyPair * @return */ public static String getPrivateKey(KeyPair keyPair) { PrivateKey privateKey = keyPair.getPrivate(); byte[] bytes = privateKey.getEncoded(); return byte2base64(bytes); } /** * RSA 将字符串转换成为PublicKey公钥 * @param pubSt * @return * @throws Exception */ public static PublicKey string2PublicKey (String pubSt) throws Exception{ byte[] keyBytes = base642byte(pubSt); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); PublicKey publicKey = keyFactory.generatePublic(keySpec); return publicKey; } /** * RSA 将字符串转换成为PrivateKey公钥 * @param priStr * @return * @throws Exception */ public static PrivateKey string2PrivateKey(String priStr) throws Exception { byte[] keyBytes = base642byte(priStr); PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); PrivateKey privateKey = keyFactory.generatePrivate(keySpec); return privateKey; } /** * RSA 数据加密 * @param con * @param publicKey * @return * @throws Exception */ public static byte[] publicEncrypt(byte[] con,PublicKey publicKey) throws Exception { Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, publicKey); byte[] bytes = cipher.doFinal(con); return bytes; } /** * RSA 数据解密 * @param con * @param privateKey * @return * @throws Exception */ public static byte[] privateDecrypt(byte[] con,PrivateKey privateKey) throws Exception { Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.DECRYPT_MODE, privateKey); byte[] bytes = cipher.doFinal(con); return bytes; } /** * base64 編碼 * @param base64 * @return * @throws IOException */ private static byte[] base642byte(String base64) throws IOException { BASE64Decoder bs = new BASE64Decoder(); return bs.decodeBuffer(base64); } /** * base64 解码 * @param bytes * @return */ private static String byte2base64(byte[] bytes) { BASE64Encoder bse = new BASE64Encoder(); return bse.encode(bytes); } /**将字节数组转化为字符串显示 */ private static String byte2String(byte[] bytes) throws Exception{ return new String(bytes,"utf-8"); }
时间: 2024-12-27 15:51:02