我将数据加密并将其存储在如下所示的firebase中: db,其中note是加密的消息,key是要解密的密钥。
AES类进行加密/解密:
public class Aes {
public SecretKey secretKey;
public Aes(SecretKey secretKey) {
this.secretKey = secretKey;
}
public Aes() {
try {
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(256);
this.secretKey = keyGenerator.generateKey();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
public byte[] makeAes(byte[] rawMessage, int cipherMode){
try {
Cipher cipher = Cipher.getInstance("AES");
cipher.init(cipherMode, this.secretKey, new IvParameterSpec(new byte[16]));
byte [] output = cipher.doFinal(rawMessage);
return output;
} catch (Exception e){
Log.d("TAG", e.toString());
e.printStackTrace();
return null;
}
}
}
这部分代码负责将密钥转换为字符串并加密消息以进一步保存到数据库:
Aes aes = new Aes();
String stringKey = Base64.encodeToString(aes.secretKey.getEncoded(), Base64.DEFAULT);
String noteToCrypt = note_text.getText().toString();
String note = "";
try {
note = new String (aes.makeAes(noteToCrypt.getBytes("UTF-8"), Cipher.ENCRYPT_MODE));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
这段代码负责从数据库接收数据并对其进行解码:
try {
String note = post.child(note_id).child("note").getValue().toString();
String key = post.child(note_id).child("key").getValue().toString();
byte[] encodedKey = Base64.decode(key.getBytes("UTF-8"), Base64.DEFAULT);
SecretKey originalKey = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
Aes aes = new Aes(originalKey);
byte[] result = aes.makeAes(note.getBytes("UTF-8"), Cipher.DECRYPT_MODE); // error
note = new String(result);
note_text.setText(note);
} catch (NullPointerException e) { } catch (UnsupportedEncodingException e){
e.printStackTrace();
}
我收到此错误:
12-05 14:11:56.163 8384-8384/com.example.androidedx.safe1 W/System.err: javax.crypto.IllegalBlockSizeException: last block incomplete in decryption
at com.android.org.bouncycastle.jcajce.provider.symmetric.util.BaseBlockCipher.engineDoFinal(BaseBlockCipher.java:853)
at javax.crypto.Cipher.doFinal(Cipher.java:1502)
at com.example.androidedx.safe1.Aes.makeAes(Aes.java:34)
at com.example.androidedx.safe1.EditNoteActivity$1.onDataChange(EditNoteActivity.java:102)
at com.google.android.gms.internal.zzegf.zza(Unknown Source)
at com.google.android.gms.internal.zzeia.zzbyc(Unknown Source)
at com.google.android.gms.internal.zzeig.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
12-05 14:11:56.164 8384-8384/com.example.androidedx.safe1 W/System.err:
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
我该怎么办?