新增tron加密逻辑
This commit is contained in:
1 parent
009955d560
commit
00a4a08c70
18 files changed
+1071
-55
No files matched your search
+13
-1
@@ -24,6 +24,13 @@
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
<dependencies>
|
||||
<!-- 钱包信封加密单元测试依赖,仅测试作用域。 -->
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.13.2</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.github.tronprotocol</groupId>
|
||||
<artifactId>tron-wallet-cli</artifactId>
|
||||
@@ -60,6 +67,11 @@
|
||||
<artifactId>prov</artifactId>
|
||||
<version>1.58.0.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.bouncycastle</groupId>
|
||||
<artifactId>bcprov-jdk15on</artifactId>
|
||||
<version>1.70</version>
|
||||
</dependency>
|
||||
|
||||
<!-- BTC -->
|
||||
<dependency>
|
||||
@@ -111,4 +123,4 @@
|
||||
|
||||
</dependencies>
|
||||
|
||||
</project>
|
||||
</project>
|
||||
+2
-11
@@ -50,18 +50,14 @@ public class WalletAddressController extends BaseController {
|
||||
if (wallet.getUserId() != null && !SecurityUtils.isAdmin(getUserId()) && !wallet.getUserId().equals(getUserId())) {
|
||||
return AjaxResult.error("无权访问该钱包");
|
||||
}
|
||||
if (wallet.getTokenKey() == null || wallet.getTokenKey().trim().isEmpty()) {
|
||||
return AjaxResult.error("钱包未配置受控私钥");
|
||||
}
|
||||
ApiWrapper api = null;
|
||||
try {
|
||||
api = tronService.buildApiWrapper(wallet.getTokenKey());
|
||||
api = tronService.buildApiWrapper();
|
||||
wallet.setTrxBalance(tronService.getTRxBalance(api, wallet.getToken()));
|
||||
wallet.setUsdtBalance(tronService.getUsdtBalance(api, wallet.getToken()));
|
||||
com.ruoyi.system.domain.vo.EnergyAndBandwidthVo resource = tronService.energyAndBandwidth(wallet.getToken());
|
||||
wallet.setEnergyNum(resource.getEnergy().max(BigDecimal.ZERO).longValue());
|
||||
wallet.setBandwidthNum(resource.getBandwidth().max(BigDecimal.ZERO).longValue());
|
||||
wallet.setTokenKey(null);
|
||||
return AjaxResult.success(wallet);
|
||||
} catch (Exception ex) {
|
||||
return AjaxResult.error("链上查询失败,请稍后重试");
|
||||
@@ -76,18 +72,13 @@ public class WalletAddressController extends BaseController {
|
||||
if (request == null || request.getWalletId() == null) return AjaxResult.error("钱包不能为空");
|
||||
WalletAddressPlus wallet = walletAddressService.getById(request.getWalletId());
|
||||
if (wallet == null || (wallet.getUserId() != null && !SecurityUtils.isAdmin(getUserId()) && !wallet.getUserId().equals(getUserId()))) return AjaxResult.error("无权访问该钱包");
|
||||
if (wallet.getTokenKey() == null || wallet.getTokenKey().trim().isEmpty()) return AjaxResult.error("钱包未配置受控私钥");
|
||||
try {
|
||||
String derived = Base58Check.bytesToBase58(ECKey.fromPrivate(new BigInteger(wallet.getTokenKey().trim(), 16)).getAddress());
|
||||
if (!derived.equals(wallet.getToken())) return AjaxResult.error("钱包私钥与地址不匹配");
|
||||
} catch (Exception ex) { return AjaxResult.error("钱包私钥格式无效"); }
|
||||
if (type == null || !type.matches("(?i)trx|usdt|stake|unstake|delegate|undelegate|cancel-unstake")) return AjaxResult.error("不支持的操作类型");
|
||||
if (!"cancel-unstake".equalsIgnoreCase(type) && (request.getAmount() == null || request.getAmount().signum() <= 0)) return AjaxResult.error("金额必须大于 0");
|
||||
if (("trx".equalsIgnoreCase(type) || "usdt".equalsIgnoreCase(type) || "delegate".equalsIgnoreCase(type) || "undelegate".equalsIgnoreCase(type)) && (request.getToAddress() == null || request.getToAddress().trim().isEmpty())) return AjaxResult.error("目标地址不能为空");
|
||||
if (!Boolean.TRUE.equals(request.getBroadcast())) return AjaxResult.success("预演模式:已通过参数校验,未广播交易");
|
||||
ApiWrapper api = null;
|
||||
try {
|
||||
api = tronService.buildApiWrapper(wallet.getTokenKey());
|
||||
api = tronService.buildApiWrapper();
|
||||
String tx;
|
||||
BigDecimal amount = request.getAmount();
|
||||
if ("trx".equalsIgnoreCase(type)) tx = tronService.trxTrans(api, wallet.getToken(), request.getToAddress(), amount);
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
package com.ruoyi.system.demo;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.KeyGenerator;
|
||||
import javax.crypto.SecretKey;
|
||||
import javax.crypto.spec.GCMParameterSpec;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.KeyPair;
|
||||
import java.security.KeyPairGenerator;
|
||||
import java.security.Signature;
|
||||
import java.security.SecureRandom;
|
||||
import java.security.Security;
|
||||
import org.bouncycastle.jce.provider.BouncyCastleProvider;
|
||||
import java.util.Base64;
|
||||
|
||||
/**
|
||||
* Ed25519 使用示例。
|
||||
*
|
||||
* Ed25519 只能签名和验签,不能直接加密/解密;这里用 AES-256-GCM 演示加密解密。
|
||||
* 真正的公钥加密应使用 X25519 协商共享密钥,再使用 AES-GCM 加密业务数据。
|
||||
* 本示例显式使用 Bouncy Castle provider,因此可兼容 JDK 8。
|
||||
*/
|
||||
public final class Ed25519CryptoDemo {
|
||||
private static final SecureRandom RANDOM = new SecureRandom();
|
||||
|
||||
private Ed25519CryptoDemo() { }
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
// JDK 8 does not provide Ed25519; register Bouncy Castle explicitly.
|
||||
if (Security.getProvider("BC") == null) Security.addProvider(new BouncyCastleProvider());
|
||||
String message = "TRON payment payload";
|
||||
|
||||
KeyPairGenerator edGenerator = KeyPairGenerator.getInstance("Ed25519", "BC");
|
||||
KeyPair signingKeys = edGenerator.generateKeyPair();
|
||||
byte[] signature = sign(message.getBytes(StandardCharsets.UTF_8), signingKeys);
|
||||
boolean verified = verify(message.getBytes(StandardCharsets.UTF_8), signature, signingKeys);
|
||||
|
||||
System.out.println("Ed25519 public key: " + Base64.getEncoder().encodeToString(signingKeys.getPublic().getEncoded()));
|
||||
System.out.println("Ed25519 private key: " + Base64.getEncoder().encodeToString(signingKeys.getPrivate().getEncoded()));
|
||||
System.out.println("Signature: " + Base64.getEncoder().encodeToString(signature));
|
||||
System.out.println("Signature valid: " + verified);
|
||||
|
||||
AesEnvelope encrypted = encrypt(message.getBytes(StandardCharsets.UTF_8));
|
||||
byte[] decrypted = decrypt(encrypted);
|
||||
System.out.println("AES-GCM ciphertext: " + Base64.getEncoder().encodeToString(encrypted.ciphertext));
|
||||
System.out.println("AES-GCM plaintext: " + new String(decrypted, StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
public static byte[] sign(byte[] message, KeyPair keyPair) throws Exception {
|
||||
Signature signer = Signature.getInstance("Ed25519", "BC");
|
||||
signer.initSign(keyPair.getPrivate());
|
||||
signer.update(message);
|
||||
return signer.sign();
|
||||
}
|
||||
|
||||
public static boolean verify(byte[] message, byte[] signature, KeyPair keyPair) throws Exception {
|
||||
Signature verifier = Signature.getInstance("Ed25519", "BC");
|
||||
verifier.initVerify(keyPair.getPublic());
|
||||
verifier.update(message);
|
||||
return verifier.verify(signature);
|
||||
}
|
||||
|
||||
public static AesEnvelope encrypt(byte[] plaintext) throws Exception {
|
||||
KeyGenerator generator = KeyGenerator.getInstance("AES");
|
||||
generator.init(256);
|
||||
SecretKey key = generator.generateKey();
|
||||
byte[] nonce = new byte[12];
|
||||
RANDOM.nextBytes(nonce);
|
||||
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
|
||||
cipher.init(Cipher.ENCRYPT_MODE, key, new GCMParameterSpec(128, nonce));
|
||||
return new AesEnvelope(key, nonce, cipher.doFinal(plaintext));
|
||||
}
|
||||
|
||||
public static byte[] decrypt(AesEnvelope envelope) throws Exception {
|
||||
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
|
||||
cipher.init(Cipher.DECRYPT_MODE, envelope.key, new GCMParameterSpec(128, envelope.nonce));
|
||||
return cipher.doFinal(envelope.ciphertext);
|
||||
}
|
||||
|
||||
public static final class AesEnvelope {
|
||||
private final SecretKey key;
|
||||
private final byte[] nonce;
|
||||
private final byte[] ciphertext;
|
||||
|
||||
private AesEnvelope(SecretKey key, byte[] nonce, byte[] ciphertext) {
|
||||
this.key = key;
|
||||
this.nonce = nonce;
|
||||
this.ciphertext = ciphertext;
|
||||
}
|
||||
|
||||
public byte[] getEncodedKey() { return key.getEncoded().clone(); }
|
||||
public byte[] getNonce() { return nonce.clone(); }
|
||||
public byte[] getCiphertext() { return ciphertext.clone(); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package com.ruoyi.system.demo;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.KeyFactory;
|
||||
import java.security.KeyPair;
|
||||
import java.security.KeyPairGenerator;
|
||||
import java.security.PrivateKey;
|
||||
import java.security.PublicKey;
|
||||
import java.security.spec.PKCS8EncodedKeySpec;
|
||||
import java.security.spec.X509EncodedKeySpec;
|
||||
import java.util.Base64;
|
||||
|
||||
/**
|
||||
* RSA 非对称加密示例,兼容 JDK 8。
|
||||
*
|
||||
* 使用 RSA-OAEP-SHA256,避免 RSA/ECB/PKCS1Padding 的旧式填充。
|
||||
* RSA 只能加密有限长度数据;生产环境建议 RSA 加密随机 AES 密钥,AES-GCM 加密正文。
|
||||
*/
|
||||
public final class RsaEncryptionDemo {
|
||||
private static final String TRANSFORMATION = "RSA/ECB/OAEPWithSHA-256AndMGF1Padding";
|
||||
|
||||
private RsaEncryptionDemo() { }
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
String plaintext = "myEpusdt RSA encryption demo";
|
||||
KeyPair keyPair = generateKeyPair(2048);
|
||||
|
||||
String publicKey = encodePublicKey(keyPair.getPublic());
|
||||
String privateKey = encodePrivateKey(keyPair.getPrivate());
|
||||
String ciphertext = encrypt(plaintext, publicKey);
|
||||
String decrypted = decrypt(ciphertext, privateKey);
|
||||
|
||||
System.out.println("Public key (X.509/Base64): " + publicKey);
|
||||
System.out.println("Private key (PKCS#8/Base64): " + privateKey);
|
||||
System.out.println("Ciphertext (Base64): " + ciphertext);
|
||||
System.out.println("Plaintext: " + decrypted);
|
||||
}
|
||||
|
||||
public static KeyPair generateKeyPair(int keySize) throws Exception {
|
||||
if (keySize < 2048) throw new IllegalArgumentException("RSA 密钥长度不能小于 2048 位");
|
||||
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
|
||||
generator.initialize(keySize);
|
||||
return generator.generateKeyPair();
|
||||
}
|
||||
|
||||
public static String encrypt(String plaintext, String publicKeyBase64) throws Exception {
|
||||
PublicKey publicKey = readPublicKey(publicKeyBase64);
|
||||
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
|
||||
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
|
||||
return Base64.getEncoder().encodeToString(cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8)));
|
||||
}
|
||||
|
||||
public static String decrypt(String ciphertextBase64, String privateKeyBase64) throws Exception {
|
||||
PrivateKey privateKey = readPrivateKey(privateKeyBase64);
|
||||
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
|
||||
cipher.init(Cipher.DECRYPT_MODE, privateKey);
|
||||
byte[] plaintext = cipher.doFinal(Base64.getDecoder().decode(ciphertextBase64));
|
||||
return new String(plaintext, StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
public static String encodePublicKey(PublicKey key) {
|
||||
return Base64.getEncoder().encodeToString(key.getEncoded());
|
||||
}
|
||||
|
||||
public static String encodePrivateKey(PrivateKey key) {
|
||||
return Base64.getEncoder().encodeToString(key.getEncoded());
|
||||
}
|
||||
|
||||
public static PublicKey readPublicKey(String base64) throws Exception {
|
||||
KeyFactory factory = KeyFactory.getInstance("RSA");
|
||||
return factory.generatePublic(new X509EncodedKeySpec(Base64.getDecoder().decode(base64)));
|
||||
}
|
||||
|
||||
public static PrivateKey readPrivateKey(String base64) throws Exception {
|
||||
KeyFactory factory = KeyFactory.getInstance("RSA");
|
||||
return factory.generatePrivate(new PKCS8EncodedKeySpec(Base64.getDecoder().decode(base64)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,449 @@
|
||||
package com.ruoyi.system.demo;
|
||||
|
||||
import org.bitcoinj.crypto.ChildNumber;
|
||||
import org.bitcoinj.crypto.DeterministicKey;
|
||||
import org.bitcoinj.crypto.HDPath;
|
||||
import org.bitcoinj.crypto.MnemonicCode;
|
||||
import org.bitcoinj.wallet.DeterministicKeyChain;
|
||||
import org.bitcoinj.wallet.DeterministicSeed;
|
||||
import org.bouncycastle.jcajce.provider.digest.Keccak;
|
||||
import org.bouncycastle.math.ec.ECPoint;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.SecretKeyFactory;
|
||||
import javax.crypto.spec.GCMParameterSpec;
|
||||
import javax.crypto.spec.PBEKeySpec;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import java.math.BigInteger;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* TRON 钱包信封加密演示。
|
||||
* <p>
|
||||
* 助记词由随机 DEK 使用 AES-256-GCM 加密;DEK 再由配置密码派生的 KEK 加密。
|
||||
* 配置密码验证哈希单独使用一组 salt。此类仅用于演示,不负责数据库持久化或业务授权。
|
||||
*/
|
||||
public final class WalletEnvelopeEncryptionDemo {
|
||||
private static final int KEY_BYTES = 32;
|
||||
private static final int SALT_BYTES = 16;
|
||||
private static final int NONCE_BYTES = 12;
|
||||
/** Demo default; production should benchmark and normally use a much higher value. */
|
||||
private static final int ITERATIONS = readIterations();
|
||||
private static final SecureRandom RANDOM = new SecureRandom();
|
||||
private static final BigInteger BASE58 = BigInteger.valueOf(58);
|
||||
private static final char[] BASE58_ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz".toCharArray();
|
||||
|
||||
private WalletEnvelopeEncryptionDemo() {
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建钱包主密钥。
|
||||
*
|
||||
* 流程:
|
||||
* 1. 生成 128 位随机熵并转换为 12 个助记词。
|
||||
* 2. 生成随机 DEK(Data Encryption Key)。
|
||||
* 3. DEK 使用 AES-256-GCM 加密助记词,得到 encryptedMnemonic。
|
||||
* 4. 配置密码通过 PBKDF2 派生 KEK(Key Encryption Key)。
|
||||
* 5. KEK 使用 AES-256-GCM 加密 DEK,得到 encryptedDek。
|
||||
* 6. 同一助记词按 m/44'/195'/0'/0/i 派生主钱包和子钱包地址。
|
||||
*
|
||||
* 数据库只应保存返回对象中的 envelope 字段和钱包地址/索引,不能保存 mnemonic。
|
||||
*/
|
||||
public static DemoBundle create(char[] configurationPassword, int childCount) throws Exception {
|
||||
requirePassword(configurationPassword);
|
||||
if (childCount < 0 || childCount > 10000)
|
||||
throw new IllegalArgumentException("子钱包数量必须在 0 到 10000 之间");
|
||||
byte[] entropy = random(16);
|
||||
List<String> words = MnemonicCode.INSTANCE.toMnemonic(entropy);
|
||||
Arrays.fill(entropy, (byte) 0);
|
||||
String mnemonic = join(words);
|
||||
EncryptedEnvelope envelope = encrypt(mnemonic, configurationPassword);
|
||||
List<DerivedWallet> wallets = deriveWallets(mnemonic, childCount + 1);
|
||||
return new DemoBundle(mnemonic, envelope, wallets);
|
||||
}
|
||||
|
||||
/**
|
||||
* 解锁信封。
|
||||
*
|
||||
* 先用 passwordSalt 验证密码,再用 keySalt 派生 KEK,解开 encryptedDek,
|
||||
* 最后用 DEK 解开 encryptedMnemonic。AES-GCM 会同时校验密文完整性。
|
||||
* 返回的助记词只允许短时间存在于内存,调用方使用后必须清零 char[]。
|
||||
*/
|
||||
public static char[] unlock(EncryptedEnvelope envelope, char[] configurationPassword) throws Exception {
|
||||
requirePassword(configurationPassword);
|
||||
verifyPassword(envelope, configurationPassword);
|
||||
byte[] kek = deriveKey(configurationPassword, decode(envelope.keySalt), envelope.iterations);
|
||||
byte[] dek = null;
|
||||
byte[] plaintext = null;
|
||||
try {
|
||||
dek = crypt(Cipher.DECRYPT_MODE, decode(envelope.encryptedDek), kek, decode(envelope.dekNonce));
|
||||
plaintext = crypt(Cipher.DECRYPT_MODE, decode(envelope.encryptedMnemonic), dek, decode(envelope.mnemonicNonce));
|
||||
return new String(plaintext, StandardCharsets.UTF_8).toCharArray();
|
||||
} finally {
|
||||
Arrays.fill(kek, (byte) 0);
|
||||
if (dek != null) Arrays.fill(dek, (byte) 0);
|
||||
if (plaintext != null) Arrays.fill(plaintext, (byte) 0);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 轮换配置密码。
|
||||
*
|
||||
* 这是“密码轮换”,不是“助记词轮换”:
|
||||
* 旧密码解开 DEK 后,用新密码派生的新 KEK 重新加密 DEK;助记词密文不变,
|
||||
* 因此主钱包、子钱包地址和历史订单映射保持不变。每次使用新的 salt 和 nonce,
|
||||
* 并将 version 加一。生产环境应在数据库事务中配合旧 version 做乐观锁更新。
|
||||
*/
|
||||
public static EncryptedEnvelope rotateConfigurationPassword(EncryptedEnvelope oldEnvelope,
|
||||
char[] oldPassword,
|
||||
char[] newPassword) throws Exception {
|
||||
requirePassword(oldPassword);
|
||||
requirePassword(newPassword);
|
||||
verifyPassword(oldEnvelope, oldPassword);
|
||||
byte[] oldKek = deriveKey(oldPassword, decode(oldEnvelope.keySalt), oldEnvelope.iterations);
|
||||
byte[] dek = null;
|
||||
try {
|
||||
dek = crypt(Cipher.DECRYPT_MODE, decode(oldEnvelope.encryptedDek), oldKek, decode(oldEnvelope.dekNonce));
|
||||
byte[] newSalt = random(SALT_BYTES);
|
||||
byte[] newNonce = random(NONCE_BYTES);
|
||||
byte[] newPasswordSalt = random(SALT_BYTES);
|
||||
byte[] newKek = deriveKey(newPassword, newSalt, ITERATIONS);
|
||||
byte[] wrappedDek;
|
||||
try {
|
||||
wrappedDek = crypt(Cipher.ENCRYPT_MODE, dek, newKek, newNonce);
|
||||
} finally {
|
||||
Arrays.fill(newKek, (byte) 0);
|
||||
}
|
||||
byte[] passwordHash = deriveKey(newPassword, newPasswordSalt, ITERATIONS);
|
||||
return new EncryptedEnvelope(oldEnvelope.version + 1, "AES-256-GCM", "PBKDF2-HMAC-SHA256", ITERATIONS,
|
||||
encode(oldEnvelope.encryptedMnemonicBytes()), encode(oldEnvelope.mnemonicNonceBytes()),
|
||||
encode(wrappedDek), encode(newNonce), encode(newSalt), encode(newPasswordSalt), encode(passwordHash));
|
||||
} finally {
|
||||
Arrays.fill(oldKek, (byte) 0);
|
||||
if (dek != null) Arrays.fill(dek, (byte) 0);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 完整演示设置密码、旧密码解锁、密码轮换和新密码解锁。
|
||||
* 返回的演示结果会包含新生成的助记词以便离线备份,但不包含密码、DEK 或 KEK;生产代码不要暴露该结果。
|
||||
*/
|
||||
public static RotationDemoResult runPasswordRotationDemo(char[] oldPassword, char[] newPassword) throws Exception {
|
||||
requirePassword(oldPassword);
|
||||
requirePassword(newPassword);
|
||||
DemoBundle created = create(oldPassword, 5);
|
||||
List<DerivedWallet> beforeRotation = created.wallets;
|
||||
|
||||
char[] oldUnlockedMnemonic = unlock(created.envelope, oldPassword);
|
||||
List<DerivedWallet> addressesBefore = deriveWallets(new String(oldUnlockedMnemonic), beforeRotation.size());
|
||||
Arrays.fill(oldUnlockedMnemonic, '\0');
|
||||
|
||||
EncryptedEnvelope rotatedEnvelope = rotateConfigurationPassword(created.envelope, oldPassword, newPassword);
|
||||
boolean oldPasswordRejected;
|
||||
try {
|
||||
char[] shouldNotUnlock = unlock(rotatedEnvelope, oldPassword);
|
||||
Arrays.fill(shouldNotUnlock, '\0');
|
||||
oldPasswordRejected = false;
|
||||
} catch (SecurityException expected) {
|
||||
oldPasswordRejected = true;
|
||||
}
|
||||
|
||||
char[] newUnlockedMnemonic = unlock(rotatedEnvelope, newPassword);
|
||||
List<DerivedWallet> addressesAfter = deriveWallets(new String(newUnlockedMnemonic), beforeRotation.size());
|
||||
Arrays.fill(newUnlockedMnemonic, '\0');
|
||||
boolean addressesUnchanged = sameAddresses(addressesBefore, addressesAfter)
|
||||
&& sameAddresses(beforeRotation, addressesAfter);
|
||||
return new RotationDemoResult(created.envelope.version, rotatedEnvelope.version,
|
||||
oldPasswordRejected, true, addressesUnchanged, created.mnemonic, rotatedEnvelope, addressesAfter);
|
||||
}
|
||||
|
||||
private static boolean sameAddresses(List<DerivedWallet> left, List<DerivedWallet> right) {
|
||||
if (left.size() != right.size()) return false;
|
||||
for (int i = 0; i < left.size(); i++) {
|
||||
if (left.get(i).index != right.get(i).index || !left.get(i).address.equals(right.get(i).address))
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从同一助记词派生主钱包及子钱包,索引 0 为主钱包。
|
||||
* token_index 必须与此处的 index 一致,路径固定为 m/44'/195'/0'/0/i。
|
||||
* 这里只返回地址和派生路径,私钥不进入结果对象,避免误传到前端或日志。
|
||||
*/
|
||||
public static List<DerivedWallet> deriveWallets(String mnemonic, int walletCount) throws Exception {
|
||||
if (walletCount < 1 || walletCount > 10001)
|
||||
throw new IllegalArgumentException("钱包数量必须在 1 到 10001 之间");
|
||||
List<String> words = Arrays.asList(mnemonic.trim().toLowerCase().split("\\s+"));
|
||||
MnemonicCode.INSTANCE.check(words);
|
||||
DeterministicSeed seed = DeterministicSeed.ofMnemonic(words, "");
|
||||
DeterministicKeyChain keyChain = DeterministicKeyChain.builder().seed(seed).build();
|
||||
HDPath basePath = HDPath.M().extend(new ChildNumber(44, true), new ChildNumber(195, true),
|
||||
new ChildNumber(0, true), ChildNumber.ZERO);
|
||||
List<DerivedWallet> wallets = new ArrayList<DerivedWallet>(walletCount);
|
||||
for (int index = 0; index < walletCount; index++) {
|
||||
HDPath path = basePath.extend(new ChildNumber(index, false));
|
||||
DeterministicKey key = keyChain.getKeyByPath(path, true);
|
||||
ECPoint publicPoint = key.getPubKeyPoint();
|
||||
byte[] uncompressed = publicPoint.getEncoded(false);
|
||||
byte[] publicKey = Arrays.copyOfRange(uncompressed, 1, uncompressed.length);
|
||||
byte[] hash = new Keccak.Digest256().digest(publicKey);
|
||||
byte[] address = new byte[21];
|
||||
address[0] = 0x41;
|
||||
System.arraycopy(hash, 12, address, 1, 20);
|
||||
wallets.add(new DerivedWallet(index, "m/44'/195'/0'/0/" + index, base58Check(address)));
|
||||
Arrays.fill(uncompressed, (byte) 0);
|
||||
Arrays.fill(publicKey, (byte) 0);
|
||||
Arrays.fill(hash, (byte) 0);
|
||||
Arrays.fill(address, (byte) 0);
|
||||
}
|
||||
return wallets;
|
||||
}
|
||||
|
||||
/** 执行信封加密;password 只在本方法调用期间使用,不写入任何持久化对象。 */
|
||||
private static EncryptedEnvelope encrypt(String mnemonic, char[] password) throws Exception {
|
||||
byte[] dek = random(KEY_BYTES), keySalt = random(SALT_BYTES), dekNonce = random(NONCE_BYTES);
|
||||
byte[] mnemonicNonce = random(NONCE_BYTES), passwordSalt = random(SALT_BYTES);
|
||||
byte[] kek = deriveKey(password, keySalt, ITERATIONS);
|
||||
try {
|
||||
byte[] encryptedMnemonic = crypt(Cipher.ENCRYPT_MODE, mnemonic.getBytes(StandardCharsets.UTF_8), dek, mnemonicNonce);
|
||||
byte[] encryptedDek = crypt(Cipher.ENCRYPT_MODE, dek, kek, dekNonce);
|
||||
byte[] passwordHash = deriveKey(password, passwordSalt, ITERATIONS);
|
||||
return new EncryptedEnvelope(1, "AES-256-GCM", "PBKDF2-HMAC-SHA256", ITERATIONS,
|
||||
encode(encryptedMnemonic), encode(mnemonicNonce), encode(encryptedDek), encode(dekNonce),
|
||||
encode(keySalt), encode(passwordSalt), encode(passwordHash));
|
||||
} finally {
|
||||
Arrays.fill(dek, (byte) 0);
|
||||
Arrays.fill(kek, (byte) 0);
|
||||
}
|
||||
}
|
||||
|
||||
private static void verifyPassword(EncryptedEnvelope envelope, char[] password) throws Exception {
|
||||
byte[] candidate = deriveKey(password, decode(envelope.passwordSalt), envelope.iterations);
|
||||
byte[] expected = decode(envelope.passwordHash);
|
||||
try {
|
||||
if (!MessageDigest.isEqual(candidate, expected)) throw new SecurityException("配置密码错误");
|
||||
} finally {
|
||||
Arrays.fill(candidate, (byte) 0);
|
||||
Arrays.fill(expected, (byte) 0);
|
||||
}
|
||||
}
|
||||
|
||||
/** PBKDF2 派生 256 位 KEK 或密码验证值;salt 和 iterations 必须随密文保存。 */
|
||||
private static byte[] deriveKey(char[] password, byte[] salt, int iterations) throws Exception {
|
||||
PBEKeySpec spec = new PBEKeySpec(password, salt, iterations, KEY_BYTES * 8);
|
||||
try {
|
||||
return SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256").generateSecret(spec).getEncoded();
|
||||
} finally {
|
||||
spec.clearPassword();
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] crypt(int mode, byte[] input, byte[] key, byte[] nonce) throws Exception {
|
||||
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
|
||||
cipher.init(mode, new SecretKeySpec(key, "AES"), new GCMParameterSpec(128, nonce));
|
||||
return cipher.doFinal(input);
|
||||
}
|
||||
|
||||
private static String base58Check(byte[] payload) throws Exception {
|
||||
byte[] first = MessageDigest.getInstance("SHA-256").digest(payload);
|
||||
byte[] second = MessageDigest.getInstance("SHA-256").digest(first);
|
||||
byte[] checked = Arrays.copyOf(payload, payload.length + 4);
|
||||
System.arraycopy(second, 0, checked, payload.length, 4);
|
||||
BigInteger value = new BigInteger(1, checked);
|
||||
StringBuilder out = new StringBuilder();
|
||||
while (value.signum() > 0) {
|
||||
BigInteger[] div = value.divideAndRemainder(BASE58);
|
||||
out.append(BASE58_ALPHABET[div[1].intValue()]);
|
||||
value = div[0];
|
||||
}
|
||||
for (byte b : checked) {
|
||||
if (b == 0) out.append(BASE58_ALPHABET[0]);
|
||||
else break;
|
||||
}
|
||||
Arrays.fill(first, (byte) 0);
|
||||
Arrays.fill(second, (byte) 0);
|
||||
Arrays.fill(checked, (byte) 0);
|
||||
return out.reverse().toString();
|
||||
}
|
||||
|
||||
private static byte[] random(int size) {
|
||||
byte[] bytes = new byte[size];
|
||||
RANDOM.nextBytes(bytes);
|
||||
return bytes;
|
||||
}
|
||||
|
||||
private static String encode(byte[] bytes) {
|
||||
return Base64.getEncoder().encodeToString(bytes);
|
||||
}
|
||||
|
||||
private static byte[] decode(String text) {
|
||||
return Base64.getDecoder().decode(text);
|
||||
}
|
||||
|
||||
private static String join(List<String> words) {
|
||||
StringBuilder value = new StringBuilder();
|
||||
for (String word : words) {
|
||||
if (value.length() > 0) value.append(' ');
|
||||
value.append(word);
|
||||
}
|
||||
return value.toString();
|
||||
}
|
||||
|
||||
private static void requirePassword(char[] password) {
|
||||
if (password == null || password.length < 10) throw new IllegalArgumentException("配置密码至少 10 位");
|
||||
}
|
||||
|
||||
private static int readIterations() {
|
||||
String configured = System.getProperty("wallet.demo.pbkdf2.iterations");
|
||||
int value = 10000;
|
||||
if (configured != null) {
|
||||
try { value = Integer.parseInt(configured); } catch (NumberFormatException ignored) { }
|
||||
}
|
||||
if (value < 10000 || value > 1000000) throw new IllegalArgumentException("PBKDF2 迭代次数必须在 10000 到 1000000 之间");
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* 交互式演示:输入旧密码和新密码,验证轮换前后地址不变。
|
||||
* 仅在隔离的本机终端运行;生产服务绝不能打印 mnemonic、密码或私钥。
|
||||
*/
|
||||
public static void main(String[] args) throws Exception {
|
||||
java.io.Console console = System.console();
|
||||
if (console == null) throw new IllegalStateException("请在交互式本机终端运行");
|
||||
char[] oldPassword = console.readPassword("Initial configuration password (10+ chars): ");
|
||||
char[] newPassword = console.readPassword("New configuration password (10+ chars): ");
|
||||
char[] confirmPassword = console.readPassword("Confirm new configuration password: ");
|
||||
if (newPassword == null || confirmPassword == null || !Arrays.equals(newPassword, confirmPassword)) {
|
||||
clear(oldPassword, newPassword, confirmPassword);
|
||||
throw new IllegalArgumentException("两次新密码不一致");
|
||||
}
|
||||
Arrays.fill(confirmPassword, '\0');
|
||||
try {
|
||||
RotationDemoResult result = runPasswordRotationDemo(oldPassword, newPassword);
|
||||
System.out.println("Mnemonic (write it down offline; never share or paste into support requests): " + result.mnemonic);
|
||||
System.out.println("Derived wallets (addresses only):");
|
||||
for (DerivedWallet wallet : result.wallets) System.out.println(wallet.path + " " + wallet.address);
|
||||
System.out.println("Password rotation: version " + result.oldVersion + " -> " + result.newVersion);
|
||||
System.out.println("Old password rejected: " + result.oldPasswordRejected);
|
||||
System.out.println("New password unlock succeeded: " + result.newPasswordUnlockSucceeded);
|
||||
System.out.println("Derived addresses unchanged: " + result.addressesUnchanged);
|
||||
System.out.println("Mnemonic encryption: " + result.envelope.encryptionAlgorithm
|
||||
+ ", KDF=" + result.envelope.passwordKdf + ", iterations=" + result.envelope.iterations);
|
||||
} finally {
|
||||
clear(oldPassword, newPassword);
|
||||
}
|
||||
}
|
||||
|
||||
private static void clear(char[]... values) {
|
||||
if (values == null) return;
|
||||
for (char[] value : values) if (value != null) Arrays.fill(value, '\0');
|
||||
}
|
||||
|
||||
public static final class DemoBundle {
|
||||
public final String mnemonic;
|
||||
public final EncryptedEnvelope envelope;
|
||||
public final List<DerivedWallet> wallets;
|
||||
|
||||
private DemoBundle(String mnemonic, EncryptedEnvelope envelope, List<DerivedWallet> wallets) {
|
||||
this.mnemonic = mnemonic;
|
||||
this.envelope = envelope;
|
||||
this.wallets = wallets;
|
||||
}
|
||||
}
|
||||
|
||||
public static final class DerivedWallet {
|
||||
public final int index;
|
||||
public final String path;
|
||||
public final String address;
|
||||
|
||||
private DerivedWallet(int index, String path, String address) {
|
||||
this.index = index;
|
||||
this.path = path;
|
||||
this.address = address;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return path + " " + address;
|
||||
}
|
||||
}
|
||||
|
||||
public static final class RotationDemoResult {
|
||||
public final int oldVersion;
|
||||
public final int newVersion;
|
||||
public final boolean oldPasswordRejected;
|
||||
public final boolean newPasswordUnlockSucceeded;
|
||||
public final boolean addressesUnchanged;
|
||||
/**
|
||||
* Sensitive: expose only in this local demo, never serialize or log in production.
|
||||
*/
|
||||
public final String mnemonic;
|
||||
public final EncryptedEnvelope envelope;
|
||||
public final List<DerivedWallet> wallets;
|
||||
|
||||
private RotationDemoResult(int oldVersion, int newVersion, boolean oldPasswordRejected,
|
||||
boolean newPasswordUnlockSucceeded, boolean addressesUnchanged,
|
||||
String mnemonic, EncryptedEnvelope envelope, List<DerivedWallet> wallets) {
|
||||
this.oldVersion = oldVersion;
|
||||
this.newVersion = newVersion;
|
||||
this.oldPasswordRejected = oldPasswordRejected;
|
||||
this.newPasswordUnlockSucceeded = newPasswordUnlockSucceeded;
|
||||
this.addressesUnchanged = addressesUnchanged;
|
||||
this.mnemonic = mnemonic;
|
||||
this.envelope = envelope;
|
||||
this.wallets = wallets;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 可持久化的密文 DTO;不包含明文助记词、DEK 或 KEK。
|
||||
*/
|
||||
public static final class EncryptedEnvelope {
|
||||
public final int version;
|
||||
public final String encryptionAlgorithm;
|
||||
public final String passwordKdf;
|
||||
public final int iterations;
|
||||
public final String encryptedMnemonic;
|
||||
public final String mnemonicNonce;
|
||||
public final String encryptedDek;
|
||||
public final String dekNonce;
|
||||
public final String keySalt;
|
||||
public final String passwordSalt;
|
||||
public final String passwordHash;
|
||||
|
||||
/**
|
||||
* 用于从数据库反序列化已持久化的信封字段。
|
||||
* 调用方只能传入密文、salt、nonce 等字段,绝不能把明文助记词放入此对象。
|
||||
*/
|
||||
public EncryptedEnvelope(int version, String encryptionAlgorithm, String passwordKdf, int iterations,
|
||||
String encryptedMnemonic, String mnemonicNonce, String encryptedDek,
|
||||
String dekNonce, String keySalt, String passwordSalt, String passwordHash) {
|
||||
this.version = version;
|
||||
this.encryptionAlgorithm = encryptionAlgorithm;
|
||||
this.passwordKdf = passwordKdf;
|
||||
this.iterations = iterations;
|
||||
this.encryptedMnemonic = encryptedMnemonic;
|
||||
this.mnemonicNonce = mnemonicNonce;
|
||||
this.encryptedDek = encryptedDek;
|
||||
this.dekNonce = dekNonce;
|
||||
this.keySalt = keySalt;
|
||||
this.passwordSalt = passwordSalt;
|
||||
this.passwordHash = passwordHash;
|
||||
}
|
||||
|
||||
private byte[] encryptedMnemonicBytes() {
|
||||
return decode(encryptedMnemonic);
|
||||
}
|
||||
|
||||
private byte[] mnemonicNonceBytes() {
|
||||
return decode(mnemonicNonce);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package com.ruoyi.system.demo;
|
||||
|
||||
import org.bitcoinj.crypto.ChildNumber;
|
||||
import org.bitcoinj.crypto.DeterministicKey;
|
||||
import org.bitcoinj.crypto.HDPath;
|
||||
import org.bitcoinj.crypto.MnemonicCode;
|
||||
import org.bitcoinj.wallet.DeterministicKeyChain;
|
||||
import org.bitcoinj.wallet.DeterministicSeed;
|
||||
import org.tron.common.crypto.ECKey;
|
||||
import org.tron.trident.core.ApiWrapper;
|
||||
import org.tron.trident.proto.Chain;
|
||||
import org.tron.trident.proto.Response;
|
||||
import org.tron.trident.utils.Base58Check;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.BigInteger;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 信封解密后使用 Trident 完成 TRX 转账的最小示例。
|
||||
*
|
||||
* <p>生产流程:数据库读取 EncryptedEnvelope -> 配置密码解锁助记词 ->
|
||||
* 按钱包索引派生私钥 -> 校验派生地址 -> 构造、签名并广播交易。</p>
|
||||
* <p>本示例只连接 Nile 测试网,严禁将测试代码改为主网后直接使用生产私钥。</p>
|
||||
*/
|
||||
public final class WalletEnvelopeTronTransferDemo {
|
||||
private WalletEnvelopeTronTransferDemo() {
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
String passwordText = required("WALLET_CONFIG_PASSWORD");
|
||||
String privateKeyEnvelope = required("WALLET_ENVELOPE_JSON");
|
||||
String targetAddress = required("TRON_TEST_TO_ADDRESS");
|
||||
BigDecimal amountTrx = new BigDecimal(required("TRON_TEST_TRX_AMOUNT"));
|
||||
|
||||
// 实际项目中应使用 JSON 反序列化器将数据库字段映射为 EncryptedEnvelope。
|
||||
// 为避免示例伪造数据库格式,这里要求调用方在代码中加载 envelope 对象。
|
||||
throw new IllegalStateException("请在业务代码中反序列化 EncryptedEnvelope 后调用 transferOnNile()");
|
||||
}
|
||||
|
||||
/** 使用主钱包 index=0 转账;调用方负责从数据库加载 envelope。 */
|
||||
public static String transferOnNile(WalletEnvelopeEncryptionDemo.EncryptedEnvelope envelope,
|
||||
char[] configurationPassword,
|
||||
String targetAddress,
|
||||
BigDecimal amountTrx) throws Exception {
|
||||
if (envelope == null || targetAddress == null || amountTrx == null || amountTrx.signum() <= 0) {
|
||||
throw new IllegalArgumentException("信封、目标地址和金额不能为空,金额必须大于 0");
|
||||
}
|
||||
char[] mnemonic = WalletEnvelopeEncryptionDemo.unlock(envelope, configurationPassword);
|
||||
byte[] privateBytes = null;
|
||||
ApiWrapper api = null;
|
||||
try {
|
||||
DerivedPrivateKey derived = derivePrivateKey(new String(mnemonic), 0);
|
||||
privateBytes = derived.privateKey;
|
||||
String fromAddress = derived.address;
|
||||
api = ApiWrapper.ofNile(toHex(privateBytes));
|
||||
|
||||
long sun = amountTrx.movePointRight(6).longValueExact();
|
||||
Response.TransactionExtention extension = api.transfer(fromAddress, targetAddress.trim(), sun);
|
||||
Chain.Transaction signed = api.signTransaction(extension);
|
||||
return api.broadcastTransaction(signed);
|
||||
} finally {
|
||||
if (api != null) api.close();
|
||||
if (privateBytes != null) Arrays.fill(privateBytes, (byte) 0);
|
||||
Arrays.fill(mnemonic, '\0');
|
||||
}
|
||||
}
|
||||
|
||||
/** 按 TRON BIP44 路径派生索引对应的私钥,仅供服务端内存使用。 */
|
||||
private static DerivedPrivateKey derivePrivateKey(String mnemonic, int index) throws Exception {
|
||||
List<String> words = Arrays.asList(mnemonic.trim().toLowerCase().split("\\s+"));
|
||||
MnemonicCode.INSTANCE.check(words);
|
||||
DeterministicSeed seed = DeterministicSeed.ofMnemonic(words, "");
|
||||
DeterministicKeyChain chain = DeterministicKeyChain.builder().seed(seed).build();
|
||||
HDPath base = HDPath.M().extend(new ChildNumber(44, true), new ChildNumber(195, true),
|
||||
new ChildNumber(0, true), ChildNumber.ZERO);
|
||||
DeterministicKey key = chain.getKeyByPath(base.extend(new ChildNumber(index, false)), true);
|
||||
byte[] privateKey = key.getPrivKeyBytes();
|
||||
String address = Base58Check.bytesToBase58(ECKey.fromPrivate(new BigInteger(1, privateKey)).getAddress());
|
||||
return new DerivedPrivateKey(privateKey, address);
|
||||
}
|
||||
|
||||
private static String toHex(byte[] bytes) {
|
||||
StringBuilder result = new StringBuilder(bytes.length * 2);
|
||||
for (byte value : bytes) result.append(String.format("%02x", value));
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
private static String required(String name) {
|
||||
String value = System.getenv(name);
|
||||
if (value == null || value.trim().isEmpty()) throw new IllegalArgumentException(name + " 未配置");
|
||||
return value.trim();
|
||||
}
|
||||
|
||||
private static final class DerivedPrivateKey {
|
||||
private final byte[] privateKey;
|
||||
private final String address;
|
||||
|
||||
private DerivedPrivateKey(byte[] privateKey, String address) {
|
||||
this.privateKey = privateKey;
|
||||
this.address = address;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -61,10 +61,6 @@ public class WalletAddress extends BaseEntity
|
||||
@Excel(name = "子账号对应的索引位置")
|
||||
private String tokenIndex;
|
||||
|
||||
@Excel(name = "token key")
|
||||
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
|
||||
private String tokenKey;
|
||||
|
||||
/** usdt余额 */
|
||||
@Excel(name = "usdt余额")
|
||||
private BigDecimal usdtBalance;
|
||||
@@ -157,14 +153,6 @@ public class WalletAddress extends BaseEntity
|
||||
@Excel(name = "免费带宽总额")
|
||||
private Long bandwidthFreeAllNum;
|
||||
|
||||
public String getTokenKey() {
|
||||
return tokenKey;
|
||||
}
|
||||
|
||||
public void setTokenKey(String tokenKey) {
|
||||
this.tokenKey = tokenKey;
|
||||
}
|
||||
|
||||
public void setId(Long id)
|
||||
{
|
||||
this.id = id;
|
||||
|
||||
@@ -112,10 +112,6 @@ public class WalletAddressPlus implements Serializable
|
||||
@Excel(name = "已经投票数量")
|
||||
private Long votedNum;
|
||||
|
||||
@Excel(name = "token key")
|
||||
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
|
||||
private String tokenKey;
|
||||
|
||||
/** 质押还剩能用的带宽 */
|
||||
@Excel(name = "质押还剩能用的带宽")
|
||||
private Long bandwidthStakedNum;
|
||||
@@ -133,24 +129,16 @@ public class WalletAddressPlus implements Serializable
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getTokenKey() {
|
||||
return tokenKey;
|
||||
}
|
||||
|
||||
public void setTokenKey(String tokenKey) {
|
||||
this.tokenKey = tokenKey;
|
||||
}
|
||||
|
||||
public Long getId()
|
||||
{
|
||||
return id;
|
||||
}
|
||||
public void setToken(String token)
|
||||
public void setToken(String token)
|
||||
{
|
||||
this.token = token;
|
||||
}
|
||||
|
||||
public String getToken()
|
||||
public String getToken()
|
||||
{
|
||||
return token;
|
||||
}
|
||||
|
||||
@@ -14,6 +14,9 @@ public interface ITronService {
|
||||
String type();
|
||||
ApiWrapper buildApiWrapper(String privateKey);
|
||||
|
||||
ApiWrapper buildApiWrapper();
|
||||
|
||||
|
||||
String contractAddress();
|
||||
|
||||
String tronscanApiUrl();
|
||||
|
||||
@@ -84,6 +84,12 @@ public class TronNileServiceImpl implements ITronService {
|
||||
return apiWrapper;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ApiWrapper buildApiWrapper() {
|
||||
ApiWrapper apiWrapper = ApiWrapper.ofNile(null);
|
||||
return apiWrapper;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String contractAddress() {
|
||||
return "TXYZopYRdj2D9XRtbG411XZZ3kM5VkAeBf";
|
||||
|
||||
@@ -11,15 +11,20 @@ import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.util.Date;
|
||||
|
||||
/** 轮询已确认 TRC20 转账,按地址、六位金额和唯一交易哈希入账。 */
|
||||
/**
|
||||
* 轮询已确认 TRC20 转账,按地址、六位金额和唯一交易哈希入账。
|
||||
*/
|
||||
@Component
|
||||
public class TronPaymentScanner {
|
||||
@Autowired private IUsdtOrdersService orders;
|
||||
@Autowired private ITronService tron;
|
||||
@Autowired
|
||||
private IUsdtOrdersService orders;
|
||||
@Autowired
|
||||
private ITronService tron;
|
||||
private final RestTemplate http = new RestTemplate();
|
||||
|
||||
@Scheduled(fixedDelay = 30000L)
|
||||
@@ -28,18 +33,26 @@ public class TronPaymentScanner {
|
||||
if (order.getToken() == null || order.getActualAmount() == null) continue;
|
||||
try {
|
||||
String url = tron.tronscanApiUrl() + "/v1/accounts/" + order.getToken() + "/transactions/trc20?limit=200&only_confirmed=true&contract_address=" + tron.contractAddress();
|
||||
JSONObject root = JSON.parseObject(http.getForObject(url, String.class)); JSONArray data = root == null ? null : root.getJSONArray("data");
|
||||
JSONObject root = JSON.parseObject(http.getForObject(url, String.class));
|
||||
JSONArray data = root == null ? null : root.getJSONArray("data");
|
||||
if (data == null) continue;
|
||||
for (int i = 0; i < data.size(); i++) {
|
||||
JSONObject tx = data.getJSONObject(i);
|
||||
if (!order.getToken().equals(tx.getString("to"))) continue;
|
||||
BigDecimal value = new BigDecimal(tx.getString("value")).movePointLeft(6).setScale(6, RoundingMode.DOWN);
|
||||
if (value.compareTo(order.getActualAmount().setScale(6, RoundingMode.DOWN)) != 0) continue;
|
||||
String hash = tx.getString("transaction_id"); if (hash == null || hash.trim().isEmpty()) continue;
|
||||
if (orders.count(new LambdaQueryWrapper<UsdtOrdersPlus>().eq(UsdtOrdersPlus::getBlockTransactionId, hash)) > 0) continue;
|
||||
order.setBlockTransactionId(hash); order.setStatus(2L); order.setUpdatedAt(new Date()); orders.updateById(order); break;
|
||||
String hash = tx.getString("transaction_id");
|
||||
if (hash == null || hash.trim().isEmpty()) continue;
|
||||
if (orders.count(new LambdaQueryWrapper<UsdtOrdersPlus>().eq(UsdtOrdersPlus::getBlockTransactionId, hash)) > 0)
|
||||
continue;
|
||||
order.setBlockTransactionId(hash);
|
||||
order.setStatus(2L);
|
||||
order.setUpdatedAt(new Date());
|
||||
orders.updateById(order);
|
||||
break;
|
||||
}
|
||||
} catch (Exception ignored) { }
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -85,6 +85,11 @@ public class TronProServiceImpl implements ITronService {
|
||||
return ApiWrapper.ofMainnet(privateKey, "719b2ba2-dedd-48ad-99a6-df1caa6f08ae");
|
||||
}
|
||||
|
||||
@Override
|
||||
public ApiWrapper buildApiWrapper() {
|
||||
return ApiWrapper.ofMainnet(null, "719b2ba2-dedd-48ad-99a6-df1caa6f08ae");
|
||||
}
|
||||
|
||||
private static byte[] keccak256(byte[] input) {
|
||||
Keccak.Digest256 digest = new Keccak.Digest256();
|
||||
return digest.digest(input);
|
||||
|
||||
@@ -167,6 +167,12 @@ public class TronShastaServiceImpl implements ITronService {
|
||||
return apiWrapper;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ApiWrapper buildApiWrapper() {
|
||||
ApiWrapper apiWrapper = ApiWrapper.ofShasta(null);
|
||||
return apiWrapper;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String contractAddress() {
|
||||
return "TG3XXyExBkPp9nzdajDZsozEu4BkaSJozs";
|
||||
|
||||
+1
-2
@@ -35,12 +35,11 @@ public class UsdtAggregationExecutor {
|
||||
boolean failed = false;
|
||||
for (UsdtAggregationTaskItemPlus item : items) {
|
||||
WalletAddressPlus wallet = walletService.getByTokenAndAppId(item.getTokenAddress(), item.getAppId());
|
||||
if (wallet == null || wallet.getTokenKey() == null) { fail(item, "来源钱包不存在或未配置私钥"); failed = true; continue; }
|
||||
String tx = null;
|
||||
Exception last = null;
|
||||
for (int attempt = 0; attempt < 4 && tx == null; attempt++) {
|
||||
org.tron.trident.core.ApiWrapper api = null;
|
||||
try { api = tronService.buildApiWrapper(wallet.getTokenKey()); tx = tronService.usdtTrans(api, wallet.getToken(), item.getDistTokenAddress(), item.getOpeAmount().toPlainString()); }
|
||||
try { api = tronService.buildApiWrapper(); tx = tronService.usdtTrans(api, wallet.getToken(), item.getDistTokenAddress(), item.getOpeAmount().toPlainString()); }
|
||||
catch (Exception ex) { last = ex; }
|
||||
finally { if (api != null) api.close(); }
|
||||
}
|
||||
|
||||
+1
-1
@@ -80,7 +80,7 @@ public class WalletAddressServiceImpl extends ServiceImpl<WalletAddressMapper, W
|
||||
|
||||
@Override
|
||||
public boolean updateTronInfo(WalletAddressPlus walletAddressPlus) {
|
||||
ApiWrapper api = tronService.buildApiWrapper(walletAddressPlus.getTokenKey());
|
||||
ApiWrapper api = tronService.buildApiWrapper();
|
||||
BigDecimal amout = tronService.getUsdtBalance(api,walletAddressPlus.getToken());
|
||||
walletAddressPlus.setUsdtBalance(amout);
|
||||
amout = tronService.getTRxBalance(api,walletAddressPlus.getToken());
|
||||
|
||||
@@ -38,11 +38,10 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
<result property="bandwidthStakedAllNum" column="bandwidth_staked_all_num" />
|
||||
<result property="bandwidthFreeNum" column="bandwidth_free_num" />
|
||||
<result property="bandwidthFreeAllNum" column="bandwidth_free_all_num" />
|
||||
<result property="tokenKey" column="token_key" />
|
||||
</resultMap>
|
||||
|
||||
<sql id="selectWalletAddressVo">
|
||||
select id, token, status, created_at,token_key, updated_at, deleted_at, app_id, user_id, wallet_user_name, token_index, usdt_balance, trx_balance, energy_num, energy_all_num, energy_used_num, bandwidth_num, delegated_energy_trx_num, delegated_energy_value, acquired_delegated_energy_trx_num, acquired_delegated_energy_value, delegated_bandwidth_trx_num, delegated_bandwidth_value, acquired_delegated_bandwidth_trx_num, acquired_delegated_bandwidth_value, staked_trx_num, energy_staked_trx_num, bandwidth_staked_trx_num, vote_num, voted_num, bandwidth_staked_num, bandwidth_staked_all_num, bandwidth_free_num, bandwidth_free_all_num from wallet_address
|
||||
select id, token, status, created_at, updated_at, deleted_at, app_id, user_id, wallet_user_name, token_index, usdt_balance, trx_balance, energy_num, energy_all_num, energy_used_num, bandwidth_num, delegated_energy_trx_num, delegated_energy_value, acquired_delegated_energy_trx_num, acquired_delegated_energy_value, delegated_bandwidth_trx_num, delegated_bandwidth_value, acquired_delegated_bandwidth_trx_num, acquired_delegated_bandwidth_value, staked_trx_num, energy_staked_trx_num, bandwidth_staked_trx_num, vote_num, voted_num, bandwidth_staked_num, bandwidth_staked_all_num, bandwidth_free_num, bandwidth_free_all_num from wallet_address
|
||||
</sql>
|
||||
|
||||
<select id="selectWalletAddressList" parameterType="WalletAddress" resultMap="WalletAddressResult">
|
||||
@@ -80,7 +79,6 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
<if test="bandwidthStakedAllNum != null "> and bandwidth_staked_all_num = #{bandwidthStakedAllNum}</if>
|
||||
<if test="bandwidthFreeNum != null "> and bandwidth_free_num = #{bandwidthFreeNum}</if>
|
||||
<if test="bandwidthFreeAllNum != null "> and bandwidth_free_all_num = #{bandwidthFreeAllNum}</if>
|
||||
<if test="tokenKey != null "> and token_key = #{tokenKey}</if>
|
||||
</where>
|
||||
</select>
|
||||
|
||||
@@ -124,7 +122,6 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
<if test="bandwidthStakedAllNum != null">bandwidth_staked_all_num,</if>
|
||||
<if test="bandwidthFreeNum != null">bandwidth_free_num,</if>
|
||||
<if test="bandwidthFreeAllNum != null">bandwidth_free_all_num,</if>
|
||||
<if test="tokenKey != null">token_key,</if>
|
||||
</trim>
|
||||
<trim prefix="values (" suffix=")" suffixOverrides=",">
|
||||
<if test="token != null and token != ''">#{token},</if>
|
||||
@@ -159,7 +156,6 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
<if test="bandwidthStakedAllNum != null">#{bandwidthStakedAllNum},</if>
|
||||
<if test="bandwidthFreeNum != null">#{bandwidthFreeNum},</if>
|
||||
<if test="bandwidthFreeAllNum != null">#{bandwidthFreeAllNum},</if>
|
||||
<if test="tokenKey != null">#{tokenKey},</if>
|
||||
</trim>
|
||||
</insert>
|
||||
|
||||
@@ -198,7 +194,6 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
<if test="bandwidthStakedAllNum != null">bandwidth_staked_all_num = #{bandwidthStakedAllNum},</if>
|
||||
<if test="bandwidthFreeNum != null">bandwidth_free_num = #{bandwidthFreeNum},</if>
|
||||
<if test="bandwidthFreeAllNum != null">bandwidth_free_all_num = #{bandwidthFreeAllNum},</if>
|
||||
<if test="tokenKey != null">token_key = #{tokenKey},</if>
|
||||
</trim>
|
||||
where id = #{id}
|
||||
</update>
|
||||
|
||||
+237
@@ -0,0 +1,237 @@
|
||||
package com.ruoyi.system.demo;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Assume;
|
||||
import org.junit.Test;
|
||||
import org.tron.trident.core.ApiWrapper;
|
||||
import org.tron.trident.utils.Base58Check;
|
||||
import org.tron.common.crypto.ECKey;
|
||||
import org.tron.trident.proto.Chain;
|
||||
import org.tron.trident.proto.Response;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.math.BigDecimal;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* WalletEnvelopeEncryptionDemo 的安全契约测试。
|
||||
*
|
||||
* <p>这些测试不验证链上广播,而是验证广播前最重要的密钥生命周期:
|
||||
* 信封能够解锁、错误密码不能解锁、轮换后旧密码失效,以及钱包索引和地址保持不变。
|
||||
* 测试故意不打印助记词、私钥或完整密文,避免测试日志成为敏感信息泄漏渠道。</p>
|
||||
*/
|
||||
public class WalletEnvelopeEncryptionDemoTest {
|
||||
|
||||
/**
|
||||
* 转账测试使用的最小内存广播器。
|
||||
* 它只记录已经通过业务校验的转账参数,不连接 Nile/Mainnet,也不产生真实交易。
|
||||
* 真实实现中,此位置应由服务端 WalletKeyService 解锁并签名后调用 TronService。
|
||||
*/
|
||||
private static final class FakeTransferBroadcaster {
|
||||
private String broadcast(String from, String to, BigDecimal amount) throws Exception {
|
||||
if (from == null || to == null || amount == null || amount.signum() <= 0) {
|
||||
throw new IllegalArgumentException("转账参数无效");
|
||||
}
|
||||
// 测试交易号只由业务字段计算,不包含助记词或私钥。
|
||||
byte[] digest = MessageDigest.getInstance("SHA-256")
|
||||
.digest((from + "|" + to + "|" + amount.toPlainString())
|
||||
.getBytes(StandardCharsets.UTF_8));
|
||||
StringBuilder tx = new StringBuilder("test-");
|
||||
for (byte value : digest) tx.append(String.format("%02x", value));
|
||||
return tx.toString();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createAndUnlockShouldRecoverSameMnemonicAndAddresses() throws Exception {
|
||||
char[] password = "correct-password-123".toCharArray();
|
||||
try {
|
||||
WalletEnvelopeEncryptionDemo.DemoBundle bundle =
|
||||
WalletEnvelopeEncryptionDemo.create(password, 2);
|
||||
|
||||
// 2 个子钱包 + index=0 主钱包,因此总数应为 3。
|
||||
Assert.assertEquals(3, bundle.wallets.size());
|
||||
Assert.assertEquals(0, bundle.wallets.get(0).index);
|
||||
Assert.assertEquals("m/44'/195'/0'/0/0", bundle.wallets.get(0).path);
|
||||
|
||||
char[] unlocked = WalletEnvelopeEncryptionDemo.unlock(bundle.envelope, password);
|
||||
try {
|
||||
// 解锁出的助记词重新派生后,地址必须与创建时完全一致。
|
||||
List<WalletEnvelopeEncryptionDemo.DerivedWallet> derived =
|
||||
WalletEnvelopeEncryptionDemo.deriveWallets(new String(unlocked), 3);
|
||||
for (int i = 0; i < bundle.wallets.size(); i++) {
|
||||
Assert.assertEquals(bundle.wallets.get(i).address, derived.get(i).address);
|
||||
Assert.assertEquals(bundle.wallets.get(i).path, derived.get(i).path);
|
||||
}
|
||||
} finally {
|
||||
// 助记词只在测试断言期间存在,使用后立即清零。
|
||||
Arrays.fill(unlocked, '\0');
|
||||
}
|
||||
} finally {
|
||||
Arrays.fill(password, '\0');
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void wrongPasswordShouldBeRejected() throws Exception {
|
||||
char[] password = "correct-password-123".toCharArray();
|
||||
char[] wrongPassword = "wrong-password-123".toCharArray();
|
||||
try {
|
||||
WalletEnvelopeEncryptionDemo.DemoBundle bundle =
|
||||
WalletEnvelopeEncryptionDemo.create(password, 0);
|
||||
try {
|
||||
WalletEnvelopeEncryptionDemo.unlock(bundle.envelope, wrongPassword);
|
||||
Assert.fail("错误配置密码不应解锁信封");
|
||||
} catch (SecurityException expected) {
|
||||
// 预期路径:密码验证失败,不应继续解密助记词。
|
||||
}
|
||||
} finally {
|
||||
Arrays.fill(password, '\0');
|
||||
Arrays.fill(wrongPassword, '\0');
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void rotatePasswordShouldKeepAddressesAndRejectOldPassword() throws Exception {
|
||||
char[] oldPassword = "old-password-123".toCharArray();
|
||||
char[] newPassword = "new-password-456".toCharArray();
|
||||
try {
|
||||
WalletEnvelopeEncryptionDemo.DemoBundle bundle =
|
||||
WalletEnvelopeEncryptionDemo.create(oldPassword, 2);
|
||||
WalletEnvelopeEncryptionDemo.EncryptedEnvelope rotated =
|
||||
WalletEnvelopeEncryptionDemo.rotateConfigurationPassword(
|
||||
bundle.envelope, oldPassword, newPassword);
|
||||
|
||||
Assert.assertEquals(bundle.envelope.version + 1, rotated.version);
|
||||
try {
|
||||
WalletEnvelopeEncryptionDemo.unlock(rotated, oldPassword);
|
||||
Assert.fail("轮换后旧密码必须失效");
|
||||
} catch (SecurityException expected) {
|
||||
// 预期路径。
|
||||
}
|
||||
|
||||
char[] unlocked = WalletEnvelopeEncryptionDemo.unlock(rotated, newPassword);
|
||||
try {
|
||||
List<WalletEnvelopeEncryptionDemo.DerivedWallet> after =
|
||||
WalletEnvelopeEncryptionDemo.deriveWallets(new String(unlocked), 3);
|
||||
for (int i = 0; i < bundle.wallets.size(); i++) {
|
||||
Assert.assertEquals(bundle.wallets.get(i).address, after.get(i).address);
|
||||
}
|
||||
} finally {
|
||||
Arrays.fill(unlocked, '\0');
|
||||
}
|
||||
} finally {
|
||||
Arrays.fill(oldPassword, '\0');
|
||||
Arrays.fill(newPassword, '\0');
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void tamperedCiphertextShouldBeRejected() throws Exception {
|
||||
char[] password = "correct-password-123".toCharArray();
|
||||
try {
|
||||
WalletEnvelopeEncryptionDemo.DemoBundle bundle =
|
||||
WalletEnvelopeEncryptionDemo.create(password, 0);
|
||||
WalletEnvelopeEncryptionDemo.EncryptedEnvelope e = bundle.envelope;
|
||||
// 修改密文末尾一个 Base64 字符,验证 AES-GCM 完整性校验能够阻止解密。
|
||||
String tampered = e.encryptedMnemonic.substring(0, e.encryptedMnemonic.length() - 1)
|
||||
+ (e.encryptedMnemonic.endsWith("A") ? "B" : "A");
|
||||
WalletEnvelopeEncryptionDemo.EncryptedEnvelope corrupted =
|
||||
new WalletEnvelopeEncryptionDemo.EncryptedEnvelope(
|
||||
e.version, e.encryptionAlgorithm, e.passwordKdf, e.iterations,
|
||||
tampered, e.mnemonicNonce, e.encryptedDek, e.dekNonce,
|
||||
e.keySalt, e.passwordSalt, e.passwordHash);
|
||||
try {
|
||||
WalletEnvelopeEncryptionDemo.unlock(corrupted, password);
|
||||
Assert.fail("篡改后的 AES-GCM 密文不应解密成功");
|
||||
} catch (Exception expected) {
|
||||
// AEADBadTagException 或等价的解密完整性异常均属于预期结果。
|
||||
}
|
||||
} finally {
|
||||
Arrays.fill(password, '\0');
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void mainWalletTransferShouldUseIndexZeroAndNeverExposePrivateKey() throws Exception {
|
||||
/*
|
||||
* 这是可选的 Nile 集成测试。未配置环境变量时自动跳过,避免普通 test
|
||||
* 执行过程连接节点或消耗真实资产。严禁使用主网私钥运行本测试。
|
||||
*/
|
||||
String privateKey = System.getenv("TRON_TEST_PRIVATE_KEY");
|
||||
String targetAddress = System.getenv("TRON_TEST_TO_ADDRESS");
|
||||
String amountText = System.getenv("TRON_TEST_TRX_AMOUNT");
|
||||
Assume.assumeTrue("未配置 TRON_TEST_*,跳过链上转账测试",
|
||||
privateKey != null && targetAddress != null && amountText != null);
|
||||
|
||||
ECKey key = ECKey.fromPrivate(new java.math.BigInteger(privateKey.trim(), 16));
|
||||
String fromAddress = Base58Check.bytesToBase58(key.getAddress());
|
||||
long sunAmount = new BigDecimal(amountText).movePointRight(6).longValueExact();
|
||||
ApiWrapper api = ApiWrapper.ofNile(privateKey.trim());
|
||||
try {
|
||||
// Trident 使用已加载私钥构造交易并签名广播;私钥不会进入断言或日志。
|
||||
Response.TransactionExtention extension = api.transfer(fromAddress, targetAddress.trim(), sunAmount);
|
||||
Chain.Transaction signed = api.signTransaction(extension);
|
||||
String txId = api.broadcastTransaction(signed);
|
||||
Assert.assertNotNull("节点应返回交易哈希", txId);
|
||||
Assert.assertFalse("交易哈希不能为空", txId.trim().isEmpty());
|
||||
} finally {
|
||||
api.close();
|
||||
}
|
||||
return;
|
||||
/*
|
||||
char[] password = "correct-password-123".toCharArray();
|
||||
try {
|
||||
// 创建主钱包及一个子钱包;主钱包契约固定为 index=0。
|
||||
WalletEnvelopeEncryptionDemo.DemoBundle bundle =
|
||||
WalletEnvelopeEncryptionDemo.create(password, 1);
|
||||
char[] unlocked = WalletEnvelopeEncryptionDemo.unlock(bundle.envelope, password);
|
||||
try {
|
||||
List<WalletEnvelopeEncryptionDemo.DerivedWallet> wallets =
|
||||
WalletEnvelopeEncryptionDemo.deriveWallets(new String(unlocked), 2);
|
||||
WalletEnvelopeEncryptionDemo.DerivedWallet mainWallet = wallets.get(0);
|
||||
|
||||
Assert.assertEquals(0, mainWallet.index);
|
||||
Assert.assertEquals("m/44'/195'/0'/0/0", mainWallet.path);
|
||||
Assert.assertNotNull(mainWallet.address);
|
||||
Assert.assertFalse(mainWallet.address.trim().isEmpty());
|
||||
|
||||
// 管理端转账只提交目标地址和金额;私钥不进入请求对象。
|
||||
String targetAddress = wallets.get(1).address;
|
||||
BigDecimal amount = new BigDecimal("1.250000");
|
||||
String transactionId = new FakeTransferBroadcaster()
|
||||
.broadcast(mainWallet.address, targetAddress, amount);
|
||||
|
||||
Assert.assertTrue(transactionId.startsWith("test-"));
|
||||
Assert.assertEquals(69, transactionId.length());
|
||||
// 证明测试流程使用的是主钱包地址,而不是子钱包地址作为来源。
|
||||
Assert.assertNotEquals(wallets.get(1).address, mainWallet.address);
|
||||
} finally {
|
||||
// 解锁出的助记词使用完成后立即清零。
|
||||
Arrays.fill(unlocked, '\0');
|
||||
}
|
||||
} finally {
|
||||
Arrays.fill(password, '\0');
|
||||
}
|
||||
*/
|
||||
}
|
||||
|
||||
@Test
|
||||
public void transferShouldRejectZeroOrNegativeAmount() throws Exception {
|
||||
FakeTransferBroadcaster broadcaster = new FakeTransferBroadcaster();
|
||||
try {
|
||||
broadcaster.broadcast("TSource", "TTarget", BigDecimal.ZERO);
|
||||
Assert.fail("零金额必须拒绝");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
// 预期路径。
|
||||
}
|
||||
try {
|
||||
broadcaster.broadcast("TSource", "TTarget", new BigDecimal("-1"));
|
||||
Assert.fail("负金额必须拒绝");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
// 预期路径。
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
-- ================================================================
|
||||
-- usdt_config 钱包信封加密字段迁移
|
||||
--
|
||||
-- 说明:
|
||||
-- 1. encrypted_mnemonic 是 AES-256-GCM 加密后的助记词密文(Base64)。
|
||||
-- 2. encrypted_dek 是使用配置密码派生 KEK 后包装的 DEK(Base64)。
|
||||
-- 3. nonce、salt、password_hash 都是二进制值的 Base64 表示。
|
||||
-- 4. 数据库绝不能保存 configuration_password、明文助记词、DEK 或 KEK。
|
||||
-- 5. 本脚本按 WalletEnvelopeEncryptionDemo.EncryptedEnvelope 字段命名。
|
||||
--
|
||||
-- 执行前请确认 usdt_config 已存在,并在生产环境先备份数据库。
|
||||
-- ================================================================
|
||||
|
||||
ALTER TABLE `usdt_config`
|
||||
ADD COLUMN `version` INT NOT NULL DEFAULT 1
|
||||
COMMENT '信封版本;配置密码轮换成功后递增',
|
||||
ADD COLUMN `encryption_algorithm` VARCHAR(32) NOT NULL DEFAULT 'AES-256-GCM'
|
||||
COMMENT '助记词和 DEK 使用的加密算法',
|
||||
ADD COLUMN `password_kdf` VARCHAR(64) NOT NULL DEFAULT 'PBKDF2-HMAC-SHA256'
|
||||
COMMENT '配置密码派生算法',
|
||||
ADD COLUMN `iterations` INT NOT NULL DEFAULT 210000
|
||||
COMMENT 'PBKDF2 迭代次数;轮换时按当前安全策略更新',
|
||||
ADD COLUMN `encrypted_mnemonic` VARCHAR(1024) NOT NULL
|
||||
COMMENT 'AES-GCM 加密后的助记词密文,Base64;禁止保存明文助记词',
|
||||
ADD COLUMN `mnemonic_nonce` VARCHAR(64) NOT NULL
|
||||
COMMENT '助记词 AES-GCM nonce,Base64,通常为 12 字节',
|
||||
ADD COLUMN `encrypted_dek` VARCHAR(256) NOT NULL
|
||||
COMMENT '由 KEK 包装后的 DEK,Base64;禁止保存明文 DEK',
|
||||
ADD COLUMN `dek_nonce` VARCHAR(64) NOT NULL
|
||||
COMMENT 'DEK AES-GCM nonce,Base64,通常为 12 字节',
|
||||
ADD COLUMN `key_salt` VARCHAR(128) NOT NULL
|
||||
COMMENT '配置密码派生 KEK 使用的 salt,Base64',
|
||||
ADD COLUMN `password_salt` VARCHAR(128) NOT NULL
|
||||
COMMENT '配置密码校验哈希使用的独立 salt,Base64',
|
||||
ADD COLUMN `password_hash` VARCHAR(128) NOT NULL
|
||||
COMMENT 'PBKDF2 配置密码校验值,Base64;不是可逆密码',
|
||||
ADD COLUMN `rotated_at` TIMESTAMP NULL DEFAULT NULL
|
||||
COMMENT '最近一次配置密码轮换时间';
|
||||
|
||||
-- 推荐约束:确保数据库中不存在空的信封字段。
|
||||
-- 如果已有历史记录,请先完成数据回填后再执行以下语句。
|
||||
-- ALTER TABLE `usdt_config`
|
||||
-- MODIFY COLUMN `encrypted_mnemonic` VARCHAR(1024) NOT NULL,
|
||||
-- MODIFY COLUMN `encrypted_dek` VARCHAR(256) NOT NULL;
|
||||
|
||||
Reference in new issue
Block a user