我目前正在使用 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 物件中的每個變數,然后將每個加密的變數保存到一個新的 ```Stack encryptedAccInformation``
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);
}
uj5u.com熱心網友回復:
假設您確定堆疊將始終按照您在此處期望的順序(您似乎是)。
代替通用堆疊(我相信它僅限于一個 T 值),您可以使用一個堆疊Object并轉換peek()函式的結果。
private Account getInformation(Stack<Object> stack) {
Boolean isApproved = (Boolean) stack.peek();
stack.pop();
Boolean isAdmin = (Boolean) stack.peek();
stack.pop();
Double balance = (Double) stack.peek();
stack.pop();
String password = (String) stack.peek();
stack.pop();
String iBan = (String) stack.peek();
stack.pop();
String uuid = (String) stack.peek();
stack.pop();
return new Account(uuid, iBan, password, balance, isAdmin, isApproved);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/339399.html
