JAVA 加密方法
1. RSA非对称加密
生成密钥对代码:
//生成秘钥对 public static KeyPair getKeyPair() throws NoSuchAlgorithmException { KeyPairGenerator keyPairGenerator= KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(1024); return keyPairGenerator.generateKeyPair(); } //获取公钥字符串 public static String getPublicKeyString(PublicKey key){ return new String(Base64.getEncoder().encode(key.getEncoded())); } //获取私钥字符串 public static String getPrivateKeyString(PrivateKey key){ return new String(Base64.getEncoder().encode(key.getEncoded())); }
公钥加密
//公钥加密 public static String encrypt(String content,String publicKeyString)throws Exception{ PublicKey publicKey = getPublicKey(publicKeyString); byte[] contentByte = content.getBytes(); byte[] result = encrypt(contentByte,publicKey); return Base64.getEncoder().encodeToString(result); } private static byte[] encrypt(byte[] content, PublicKey publicKey) throws Exception{ Cipher cipher=Cipher.getInstance("RSA");//java默认"RSA"="RSA/ECB/PKCS1Padding" cipher.init(Cipher.ENCRYPT_MODE, publicKey); return cipher.doFinal(content); }
私钥解密
//解密 private static byte[] decrypt(byte[] content, PrivateKey privateKey) throws Exception{ Cipher cipher=Cipher.getInstance("RSA"); cipher.init(Cipher.DECRYPT_MODE, privateKey); return cipher.doFinal(content); } //将base64编码后的私钥字符串转成PrivateKey实例 private static PrivateKey getPrivateKey(String privateKey) throws Exception{ byte[ ] keyBytes= Base64.getDecoder().decode(privateKey.getBytes()); PKCS8EncodedKeySpec keySpec=new PKCS8EncodedKeySpec(keyBytes); KeyFactory keyFactory=KeyFactory.getInstance("RSA"); return keyFactory.generatePrivate(keySpec); }
2. MD5加密
Md5PasswordEncoder encoder = new Md5PasswordEncoder(); String result = encoder.encodePassword(“str”,null).toUpperCase(); result = encoder.encodePassword(result.substring(1,11),null).toUpperCase();