nonce = randSeq(16) timestamp = strconv.Itoa(int(time.Now().Unix())) text := []byte(timestamp) //需要加密的试timestamp //应该是把nonce当盐了 cfb := cipher.NewCFBEncrypter(c, []byte(nonce)) cfb.XORKeyStream(text, text) sign = hex.EncodeToString(text) 转换成java
时间: 2024-03-08 22:47:01 浏览: 157
node-nonce:用于表单和URL的Node.js nonce和CSRF工具
以下是 Java 代码实现:
```java
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class EncryptUtil {
// 需要加密的文本
private static String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
// 随机数
private static String nonce = getRandomString(16);
public static void main(String[] args) throws Exception {
String secretKey = "0123456789abcdef"; // 密钥,长度必须是16的倍数
String encryptedText = encrypt(timestamp.getBytes(StandardCharsets.UTF_8), nonce.getBytes(StandardCharsets.UTF_8), secretKey.getBytes(StandardCharsets.UTF_8));
System.out.println("加密后的文本:" + encryptedText);
}
private static String encrypt(byte[] text, byte[] nonce, byte[] secretKey) throws Exception {
// 初始化加密器
Cipher cipher = Cipher.getInstance("AES/CFB/NoPadding");
SecretKeySpec keySpec = new SecretKeySpec(secretKey, "AES");
IvParameterSpec ivSpec = new IvParameterSpec(nonce);
cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
// 加密文本
byte[] encrypted = cipher.doFinal(text);
byte[] combined = new byte[nonce.length + encrypted.length];
System.arraycopy(nonce, 0, combined, 0, nonce.length);
System.arraycopy(encrypted, 0, combined, nonce.length, encrypted.length);
// base64编码
return Base64.getEncoder().encodeToString(combined);
}
private static String getRandomString(int length) {
String base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
StringBuilder sb = new StringBuilder();
SecureRandom random = null;
try {
random = SecureRandom.getInstanceStrong();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
for (int i = 0; i < length; i++) {
int number = random.nextInt(base.length());
sb.append(base.charAt(number));
}
return sb.toString();
}
}
```
注意事项:
1. 请注意 Java 版本是否支持 AES/CFB/NoPadding 加密方式;
2. 请注意密钥的长度必须是 16 的倍数;
3. 请注意 base64 编码后的加密文本与 Python 代码输出的 sign 是相同的。
阅读全文