1.MD5加密
md5多用于用户密码加密或者签名使用,因md5不可逆,可用于身份验证。
MessageDigest md5=MessageDigest.getInstance("MD5"); Base64Encoder base64 = new Base64Encoder(); str = base64.encode(md5.digest(str.getBytes(CommonConstants.ENCODE_CHARSET_DEFAULT)));
固定长度的加密:
MessageDigest md5 = MessageDigest.getInstance("MD5"); byte[] digest = md5.digest(encode); string sign = Hex.encodeHexString(digest);
2. SHA256
MessageDigest md5 = MessageDigest.getInstance("SHA256"); byte[] digest = md5.digest(encode); string sign = Hex.encodeHexString(digest);
2.AES 对称加密
aes 用于确保文件传送的安全,对内容加密传递,由接收方进行解密。
key值要求必须是16位或32位的byte[]长度,不然无法加解密。高版本支持32位。
key生成参考:
KeyGenerator key = KeyGenerator.getInstance("AES");
key.init(128, new SecureRandom("test123".getBytes(StandardCharsets.UTF_8)));
String key1 =Hex.encodeHexString(key.generateKey().getEncoded());
// use AES对称加密算法对数据进行加密,加密后的数据转换为16进制 Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getBytes(), "AES")); byte[] bytes = cipher.doFinal(str.getBytes(StandardCharsets.UTF_8)); return Hex.encodeHexString(bytes);
3. HMAC-SHA256
private static String hmac(String sk, String stringToSign) { try { SecretKeySpec signingKey = new SecretKeySpec(sk.getBytes(StandardCharsets.UTF_8), HMAC_SHA256); Mac mac = Mac.getInstance(HMAC_SHA256); mac.init(signingKey); byte[] rawHmac = mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8)); return Hex.encodeHexString(rawHmac); } catch (Exception e) { throw new RuntimeException(e); } }