del[util]: remove util module

This commit is contained in:
godotg committed 2023-09-02 21:11:50 +08:00
1 parent 353d40d5fe
commit e4bcd22bc7
17 files changed
+13 -253

No files matched your search

-5
View File
@@ -56,11 +56,6 @@
</properties>
<dependencies>
<dependency>
<groupId>com.zfoo</groupId>
<artifactId>util</artifactId>
<version>${zfoo.version}</version>
</dependency>
<dependency>
<groupId>com.zfoo</groupId>
<artifactId>event</artifactId>
@@ -16,7 +16,6 @@ import com.zfoo.protocol.collection.ArrayUtils;
import com.zfoo.protocol.util.AssertionUtils;
import com.zfoo.protocol.util.IOUtils;
import com.zfoo.protocol.util.StringUtils;
import com.zfoo.util.EnumUtils;
import org.springframework.lang.Nullable;
import java.io.IOException;
@@ -290,7 +289,11 @@ public class NetUtils {
public static Set<NetworkInterface> getAllNetworkInterface() {
try {
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
return EnumUtils.enumerationToSet(networkInterfaces);
var set = new HashSet<NetworkInterface>();
while (networkInterfaces.hasMoreElements()) {
set.add(networkInterfaces.nextElement());
}
return set;
} catch (SocketException e) {
return Collections.emptySet();
}
@@ -0,0 +1,125 @@
/*
* Copyright (C) 2020 The zfoo Authors
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and limitations under the License.
*/
package com.zfoo.net.util.security;
import com.zfoo.protocol.util.StringUtils;
import io.netty.util.concurrent.FastThreadLocal;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
/**
* AES加密和解密
* <p>
* 默认AES/ECB/PKCS5Padding
*
* @author godotg
* @version 3.0
*/
public abstract class AesUtils {
private static final Key KEY;
private static final String KEY_STR = "=jE[`B],YO24Vt+Akh&}D7@s9l1uLKP)";
/**
* 密钥算法
*/
private static final String ALGORITHM = "AES";
/**
* 加解密算法/工作模式/填充方式
*/
private static final String ALGORITHM_STR = "AES/ECB/PKCS5Padding";
static {
try {
KEY = new SecretKeySpec(KEY_STR.getBytes(StringUtils.DEFAULT_CHARSET_NAME), ALGORITHM);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private static final FastThreadLocal<Cipher> LOCAL_ENCRYPT_CIPHER = new FastThreadLocal<Cipher>() {
@Override
protected Cipher initialValue() throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException {
var cipher = Cipher.getInstance(ALGORITHM_STR);
cipher.init(Cipher.ENCRYPT_MODE, KEY);
return cipher;
}
};
private static final FastThreadLocal<Cipher> LOCAL_DECRYPT_CIPHER = new FastThreadLocal<Cipher>() {
@Override
protected Cipher initialValue() throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException {
var cipher = Cipher.getInstance(ALGORITHM_STR);
cipher.init(Cipher.DECRYPT_MODE, KEY);
return cipher;
}
};
/**
* 对str进行AES加密
*
* @param str 需要加密的字符串
* @return AES加密后的字符串
*/
public static String getEncryptString(String str) {
try {
var base64Encoder = Base64.getEncoder();
var strBytes = StringUtils.bytes(str);
var encryptStrBytes = encrypt(strBytes);
return base64Encoder.encodeToString(encryptStrBytes);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static byte[] encrypt(byte[] bytes) {
try {
return LOCAL_ENCRYPT_CIPHER.get().doFinal(bytes);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 对str进行AES解密
*
* @param str 需要解密的字符串
* @return AES解密后的字符串
*/
public static String getDecryptString(String str) {
try {
var base64Decoder = Base64.getDecoder();
var strBytes = base64Decoder.decode(str);
var decryptStrBytes = decrypt(strBytes);
return StringUtils.bytesToString(decryptStrBytes);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static byte[] decrypt(byte[] bytes) {
try {
return LOCAL_DECRYPT_CIPHER.get().doFinal(bytes);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
@@ -0,0 +1,87 @@
/*
* Copyright (C) 2020 The zfoo Authors
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and limitations under the License.
*/
package com.zfoo.net.util.security;
import com.zfoo.protocol.util.StringUtils;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* MD5的全称是Message-Digest Algorithm 5,在90年代初由MIT的计算机科学实验室和RSA Data Security Inc发明,经MD2、MD3和MD4发展而来。
* <p>
* MD5将任意长度的“字节串”变换成一个128bit的大整数,并且它是一个不可逆的字符串变换算法。
* <p>
* 换句话说就是,即使你看到源程序和算法描述,也无法将一个MD5的值变换回原始的字符串。
* <p>
* 从数学原理上说,是因为原始的字符串有无穷多个,这有点象不存在反函数的数学函数。
* <p>
* MD5的典型应用是对一段Message(字节串)产生fingerprint(指纹),以防止被“篡改”。
* <p>
* 举个例子,你将一段话写在一个叫 readme.txt文件中,并对这个readme.txt产生一个MD5的值并记录在案,然后你可以传播这个文件给别人,
* 别人如果修改了文件中的任何内容,你对这个文件重新计算MD5时就会发现。如果再有一个第三方的认证机构,用MD5还可以防止文件作者的“抵赖”,
* 这就是所谓的数字签名应用。MD5还广泛用于加密和解密技术上,在很多操作系统中,用户的密码是以MD5值(或类似的其它算法)的方式保存的,
* 用户Login的时候,系统是把用户输入的密码计算成MD5值,然后再去和系统中保存的MD5值进行比较,而系统并不“知道”用户的密码是什么。
*
* @author godotg
* @version 3.0
*/
public abstract class MD5Utils {
private static final String MD5_ALGORITHM = "MD5";
/**
* 16进制字符
*/
private static final char[] HEX_CHARS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
public static String strToMD5(String str) {
if (StringUtils.isBlank(str)) {
throw new NullPointerException();
}
return bytesToMD5(StringUtils.bytes(str));
}
// MD5将任意长度的“字节串”变换成一个128bit的大整数
public static String bytesToMD5(byte[] bytes) {
try {
var messageDigest = MessageDigest.getInstance(MD5_ALGORITHM);
// inputByteArray是输入字符串转换得到的字节数组
messageDigest.update(bytes);
// 转换并返回结果,也是字节数组,包含16个元素
// 字符数组转换成字符串返回,MD5将任意长度的字节数组变换成一个16个字节,128bit的大整数
return byteArrayToHex(messageDigest.digest());
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("MD加密出现未知异常", e);
}
}
//下面这个函数用于将字节数组换成成16进制的字符串
private static String byteArrayToHex(byte[] bytes) {
// new一个字符数组,这个就是用来组成结果字符串的(解释一下:一个byte是八位二进制,也就是2位十六进制字符(2的8次方等于16的2次方))
var resultCharArray = new char[bytes.length * 2];
// 遍历字节数组,通过位运算(位运算效率高),转换成字符放到字符数组中去
var index = 0;
for (var b : bytes) {
resultCharArray[index++] = HEX_CHARS[b >>> 4 & 0xf];
resultCharArray[index++] = HEX_CHARS[b & 0xf];
}
// 字符数组组合成字符串返回
return new String(resultCharArray);
}
}
@@ -0,0 +1,71 @@
/*
* Copyright (C) 2020 The zfoo Authors
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and limitations under the License.
*/
package com.zfoo.net.util.security;
import com.zfoo.protocol.util.IOUtils;
import java.io.ByteArrayOutputStream;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;
/**
* @author godotg
* @version 3.0
*/
public abstract class ZipUtils {
private static final int BUFFER_SIZE = IOUtils.ONE_BYTE;
// compression level (0-9),只能是0-9
private static final int COMPRESS_LEVEL = 5;
public static byte[] zip(byte[] bytes) {
// deflate [dɪ'fleɪt] v.抽出空气; 缩小
Deflater deflater = new Deflater(COMPRESS_LEVEL);
deflater.setInput(bytes);
deflater.finish();
ByteArrayOutputStream baos = new ByteArrayOutputStream(BUFFER_SIZE);
byte[] buffer = new byte[BUFFER_SIZE];
while (!deflater.finished()) {
int count = deflater.deflate(buffer);
baos.write(buffer, 0, count);
}
deflater.end();
IOUtils.closeIO(baos);
return baos.toByteArray();
}
public static byte[] unZip(byte[] bytes) {
Inflater inflater = new Inflater();
inflater.setInput(bytes);
ByteArrayOutputStream baos = new ByteArrayOutputStream(BUFFER_SIZE);
try {
byte[] buffer = new byte[BUFFER_SIZE];
while (!inflater.finished()) {
int count = inflater.inflate(buffer);
baos.write(buffer, 0, count);
}
} catch (DataFormatException e) {
throw new RuntimeException(e);
} finally {
IOUtils.closeIO(baos);
}
return baos.toByteArray();
}
}
@@ -0,0 +1,33 @@
/*
* Copyright (C) 2020 The zfoo Authors
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and limitations under the License.
*/
package com.zfoo.net.util.security;
import org.junit.Assert;
import org.junit.Test;
/**
* @author godotg
* @version 3.0
*/
public class AesUtilsTest {
@Test
public void test() {
for (int i = 0; i < 10; i++) {
var passWord = "hello world";
var encodePassWorld = AesUtils.getEncryptString(passWord);
Assert.assertEquals(passWord, AesUtils.getDecryptString(encodePassWorld));
}
}
}
@@ -0,0 +1,31 @@
/*
* Copyright (C) 2020 The zfoo Authors
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and limitations under the License.
*/
package com.zfoo.net.util.security;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.util.DigestUtils;
/**
* @author godotg
* @version 3.0
*/
public class MD5UtilsTest {
@Test
public void md5Test() {
var str = "qwerasdfzxcv1234;:'";
Assert.assertEquals(MD5Utils.bytesToMD5(str.getBytes()).toLowerCase(), DigestUtils.md5DigestAsHex(str.getBytes()));
}
}
@@ -0,0 +1,47 @@
/*
* Copyright (C) 2020 The zfoo Authors
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and limitations under the License.
*/
package com.zfoo.net.util.security;
import org.junit.Assert;
import org.junit.Test;
/**
* @author godotg
* @version 3.0
*/
public class ZipTest {
// Zip算法压缩测试
@Test
public void test() {
String str = "ZIP,是一个文件的压缩的算法,原名Deflate(真空),发明者为菲利普·卡兹(Phil Katz))," +
"他于1989年1月公布了该格式的资料。ZIP通常使用后缀名“.zip”,它的MIME格式为 application/zip 。" +
"目前,ZIP格式属于几种主流的压缩格式之一,其竞争者包括RAR格式以及开放源码的7-Zip格式。" +
"从性能上比较,RAR格式较ZIP格式压缩率较高,但是它的压缩时间远远高于Zip。" +
"而7-Zip(7z)由于提供了免费的压缩工具而逐渐在更多的领域得到应用。";
byte[] bytes = str.getBytes();
// 压缩前数组长度
Assert.assertEquals(bytes.length, 555);
bytes = ZipUtils.zip(bytes);
// 压缩后数组长度
Assert.assertEquals(bytes.length, 438);
bytes = ZipUtils.unZip(bytes);
Assert.assertEquals(new String(bytes), str);
}
}