編輯:::問題中的代碼工作,但一旦圖像在相機中拍攝後,需要大約10秒才能恢復活動。我放棄了這種方法,並使用Facebook的隱藏庫來加密和解密圖像。鏈接到Facebook的解決方案:Facebook Conceal - Image Encryption and Decryption使用AES加密和解密圖像的正確方法
我已經看過很多例子,但還是沒能想出一個辦法來獲得加密和解密的權利。當我在互聯網上使用一些隨機代碼時,我以爲我知道它是正確的,但在解碼時,我得到了BadPadding異常。
所以,我正在努力解決它。正如大多數人所建議的那樣,我遵循以下問題(但是此代碼顯示如何加密字符串)。有人能幫我加密和解密圖像嗎?問題中的代碼是否適用於圖像?
鏈接到一個問題:Java 256-bit AES Password-Based Encryption
這裏是我做了什麼至今:
//全球ArrayList中存儲IV和密碼
static ArrayList<byte[]> ivandcipher = new ArrayList<byte[]>();
//生成鍵
public static SecretKey generateKey() throws NoSuchAlgorithmException {
char[] password = { 'a', 'b', 'c', 'd', 'e' };
byte[] salt = { 1, 2, 3, 4, 5 };
SecretKeyFactory factory = SecretKeyFactory
.getInstance("PBKDF2WithHmacSHA1");
KeySpec spec = new PBEKeySpec(password, salt, 65536, 256);
SecretKey tmp = null;
try {
tmp = factory.generateSecret(spec);
} catch (InvalidKeySpecException e) {
e.printStackTrace();
}
yourKey = new SecretKeySpec(tmp.getEncoded(), "AES");
return yourKey;
}
//編碼文件
//字節[] FILEDATA,包含位圖(圖像)轉換成字節[]
public static ArrayList<byte[]> encodeFile(SecretKey yourKey, byte[] fileData)
throws Exception {
byte[] encrypted = null;
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, yourKey);
AlgorithmParameters params = cipher.getParameters();
byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV();
encrypted = cipher.doFinal(fileData);
ivandcipher.clear();
ivandcipher.add(iv);
ivandcipher.add(encrypted);
return ivandcipher;
}
爲何我添加IV和加密的字節[] s到ivandcipher。因爲,正如鏈接中的答案所暗示的,我應該在解密時使用相同的iv。
//解碼文件
//我把這個方法裏面重載decodeFile方法。請注意
private Bitmap decodeFile(String filename) {
try {
yourKey = generateKey();
} catch (NoSuchAlgorithmException e1) {
e1.printStackTrace();
}
try {
byte[] decodedData = decodeFile(yourKey, readFile(filename));
Bitmap bitmap = bytesToBitmap(decodedData);
return bitmap;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
//重載decodeFile方法
public static byte[] decodeFile(SecretKey yourKey, byte[] fileData)
throws Exception {
byte[] decrypted = null;
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, yourKey, new IvParameterSpec(ivandcipher.get(0)));
decrypted = cipher.doFinal(fileData);
return decrypted;
}
我想這個問題與fileData []一起,我無法正確加密和解密。對於字符串顯示在上述鏈路的答案,即
byte[] ciphertext = cipher.doFinal("Hello, World!".getBytes("UTF-8"));
什麼應該被給定爲參數cipher.doFinal()?
讓我知道你是否需要任何其他代碼。
downvote的任何理由?我明白這已被問了很多次,但我無法對我的圖像進行適當的加密和解密。 – 2014-09-26 11:51:17
原因基本上是你複製了「在互聯網上的一些隨機代碼」,沒有得到它的工作,現在我們應該修復它。 – ntoskrnl 2014-09-26 11:57:55
@ntoskrnl,我不是要求任何人修復它。我在請求你的幫助,理解它並使之發揮作用。順便說一下,我在問題中發佈的代碼不是隨機的,而是來自我在問題中發佈的鏈接。 – 2014-09-26 11:58:48