新增tron加密逻辑

This commit is contained in:
lu7213 committed 2026-10-07 23:03:33 -04:00
1 parent 009955d560
commit 00a4a08c70
18 files changed
+1071 -55

No files matched your search

@@ -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);
}
}
}