【发布时间】:2021-12-12 12:54:38
【问题描述】:
我目前正在使用 Google Tink 为我的应用程序提供加密和解密服务。
问题如下:我想在不使用(几乎)重复代码的情况下对其进行编程,因此我有了使用泛型的想法。
如果将字符串解析为 byte[] 是我将这样做的唯一选择,但我宁愿不这样做。
这些是方法和变量:
我正在使用的 3 个堆栈:
private Stack<String> plaintextAccInformation = new Stack<>();
private Stack<byte[]> encryptedAccInformation = new Stack<>();
private Stack<String> decryptedAccInformation = new Stack<>();
该方法用于从堆栈中获取信息(我想用泛型解决这个问题,但也不起作用)。不,解析不起作用,因为该方法必须可以使用两种不同的数据类型访问。
private <T> Account getInformation(Stack<T> stack) {
boolean isApproved = stack.peek();
stack.pop();
boolean isAdmin = stack.peek();
stack.pop();
double balance = stack.peek();
stack.pop();
String password = stack.peek();
stack.pop();
String iBan = stack.peek();
stack.pop();
String uuid = stack.peek();
stack.pop();
return new Account(uuid, iBan, password, balance, isAdmin, isApproved);
}
用于加密 Account 对象的所有数据的方法。
其思想是遍历 ```Stack plaintextAccInformation`` 并加密 Account 对象中的每个变量,然后将每个加密的变量保存到一个新的 `` `堆栈加密的AccInformation```
public Account encrypt(Account account) throws GeneralSecurityException {
this.plaintextAccInformation.empty();
this.encryptedAccInformation.empty();
agjEncryption = new AesGcmJce(key.getBytes());
this.plaintextAccInformation.push(account.getUuid());
this.plaintextAccInformation.push(account.getIban());
this.plaintextAccInformation.push(account.getPassword());
this.plaintextAccInformation.push(String.valueOf(account.getBalance()));
this.plaintextAccInformation.push(String.valueOf(account.isAdmin()));
this.plaintextAccInformation.push(String.valueOf(account.isApproved()));
Iterator<String> iterator = plaintextAccInformation.iterator();
while (iterator.hasNext()) {
encryptedAccInformation.push(agjEncryption.encrypt(plaintextAccInformation.peek().getBytes(), aad.getBytes()));
plaintextAccInformation.pop();
}
return getInformation(this.encryptedAccInformation);
}
用于解密保存在```Stack encryptedAccInformation```中的变量并保存到```Stack encryptedAccInformation```的方法
public Account decrypt() throws GeneralSecurityException {
this.decryptedAccInformation.empty();
this.agjDecryption = new AesGcmJce(key.getBytes());
Iterator<byte[]> iterator2 = encryptedAccInformation.iterator();
while (iterator2.hasNext()) {
decryptedAccInformation.push(new String(agjDecryption.decrypt(encryptedAccInformation.peek(), aad.getBytes())));
encryptedAccInformation.pop();
}
return getInformation(this.decryptedAccInformation);
}
【问题讨论】:
-
我不知道为什么代码没有显示为代码。
-
请澄清您的具体问题或提供其他详细信息以准确突出您的需求。正如目前所写的那样,很难准确地说出你在问什么。
标签: java generics encryption stack tink