对于Java开发者而言,加解密和日期格式转换是日常开发中非常常见的需求。在这篇文章中,我为大家整理了Java中常用的加解密功能和日期格式转换工具类,并提供具体示例代码。这些功能和工具类可以帮助Java开发者快速、简便地进行加解密和日期格式转换操作。
1. Base64加解密
在Java中,我们可以使用Base64类进行字符串的加解密操作。Base64是一种常见的编码方式,可以将任意二进制数据转换成纯文本格式,以方便在网络传输中使用。具体实现代码如下:
import java.util.Base64;
public class Base64Util {
public static String encode(String str) {
byte[] bytes = str.getBytes();
return Base64.getEncoder().encodeToString(bytes);
}
public static String decode(String encodedStr) {
byte[] bytes = Base64.getDecoder().decode(encodedStr);
return new String(bytes);
}
public static byte[] encode(byte[] data) {
return Base64.getEncoder().encode(data);
}
public static byte[] decode(byte[] encodedData) {
return Base64.getDecoder().decode(encodedData);
}
}
2. MD5加解密
MD5是一种常用的加密算法,可以将任意数据转换成固定长度的哈希值,不可逆。在Java中,我们可以使用MessageDigest类进行MD5加密操作。具体实现代码如下:
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5Util {
public static String encrypt(String str)
throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(str.getBytes());
byte[] bytes = md.digest();
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
sb.append(Integer.toHexString((b & 0xff) + 0x100).substring(1));
}
return sb.toString();
}
}
3. AES加解密
AES是一种对称加密算法,可以在数据传输中保证数据的安全性。在Java中,我们可以使用Cipher类进行AES加解密操作。具体实现代码如下:
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
public class AESUtil {
public static final int KEY_SIZE = 128;
public static byte[] generateKey() throws NoSuchAlgorithmException {
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
SecureRandom random = new SecureRandom();
keyGenerator.init(KEY_SIZE, random);
SecretKey key = keyGenerator.generateKey();
return key.getEncoded();
}
public static byte[] encrypt(byte[] data, byte[] key)
throws Exception {
SecretKey secretKey = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encrypt = cipher.doFinal(data);
return encrypt;
}
public static byte[] decrypt(byte[] data, byte[] key)
throws Exception {
SecretKey secretKey = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decrypt = cipher.doFinal(data);
return decrypt;
}
public static void main(String[] args) throws Exception {
String data = "Hello, world!";
byte[] key = generateKey();
byte[] encrypt = encrypt(data.getBytes(StandardCharsets.UTF_8), key);
byte[] decrypt = decrypt(encrypt, key);
System.out.println("明文: " + data);
System.out.println("加密后: " + Base64Util.encode(encrypt));
System.out.println("解密后: " + new String(decrypt, StandardCharsets.UTF_8));
}
}
4. 日期格式转换工具类
在Java中,我们可以使用SimpleDateFormat类进行日期格式转换操作。下面给出一个日期格式转换的工具类,支持转换成String类型和Byte类型:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateUtil {
public static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
public static String formatDate(Date date, String format) {
if (date == null) {
return null;
}
SimpleDateFormat formatter = new SimpleDateFormat(format);
return formatter.format(date);
}
public static String formatDateTime(Date date) {
return formatDate(date, DATE_TIME_FORMAT);
}
public static Date parse(String str, String format)
throws ParseException {
if (str == null || str.isEmpty()) {
return null;
}
SimpleDateFormat formatter = new SimpleDateFormat(format);
return formatter.parse(str);
}
public static Date parseDateTime(String str) throws ParseException {
return parse(str, DATE_TIME_FORMAT);
}
public static byte[] toBytes(Date date) {
return Long.toString(date.getTime()).getBytes();
}
public static Date toDate(byte[] bytes) {
return new Date(Long.parseLong(new String(bytes)));
}
public static void main(String[] args) throws Exception {
Date now = new Date();
String strDateTime = formatDateTime(now);
System.out.println("Date转String:" + strDateTime);
byte[] bytesDateTime = toBytes(now);
System.out.println("Date转Byte:" + Base64Util.encode(bytesDateTime));
Date dateTime = parseDateTime(strDateTime);
System.out.println("String转Date:" + formatDateTime(dateTime));
Date dateBytes = toDate(Base64Util.decode(bytesDateTime));
System.out.println("Byte转Date:" + formatDateTime(dateBytes));
}
}
在 Java 中日期格式,如果使用了非常规的格式或者没有指定正确的格式,可能会出现19位的问题。这通常是由于在日期格式中使用了错误的字符或者格式化字符串长度不正确导致的。
Java 中日期格式化通常使用 SimpleDateFormat 类来实现,可以通过传递指定的格式化字符串来将日期格式化成指定格式。例如,以下代码将日期格式化为 “yyyy-MM-dd” 格式:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = sdf.format(new Date());
然而,如果在格式化字符串中使用了错误的字符或者不正确的格式化字符串长度,就会出现19位问题(即超出了日期时间的表示范围)。例如,以下代码使用了错误的格式化字符串将日期格式化:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSSSSSSSS");
String formattedDate = sdf.format(new Date());
在这个例子中,格式化字符串中的 SSSSSSSSS 表示毫秒部分,但是这个字符串长度超出了日期时间的表示范围,导致格式化后的日期字符串长度变成了19位。