java写一个randomkey类用于生成一个128比特的sm4随机密钥存于String secretKey
时间: 2024-03-23 19:43:25 浏览: 53
好的,以下是一个Java实现的RandomKey类,可以用于生成128位的SM4随机密钥并存储到字符串中:
```java
import java.security.SecureRandom;
public class RandomKey {
private static final int KEY_LENGTH = 16; // 128 bits
private static final String HEX_CHARS = "0123456789ABCDEF";
public static String generate() {
SecureRandom random = new SecureRandom();
byte[] keyBytes = new byte[KEY_LENGTH];
random.nextBytes(keyBytes);
return bytesToHex(keyBytes);
}
private static String bytesToHex(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
sb.append(HEX_CHARS.charAt((b >> 4) & 0x0F));
sb.append(HEX_CHARS.charAt(b & 0x0F));
}
return sb.toString();
}
}
```
使用方法如下:
```java
String secretKey = RandomKey.generate();
System.out.println(secretKey);
```
运行结果类似于:
```
3F1C8A235B8D925EBF1C6C1D2E1145F5
```
阅读全文