使用 AES256 对称分组密码的图像加密/解密 [英] Image encryption/decryption using AES256 symmetric block ciphers

查看:47
本文介绍了使用 AES256 对称分组密码的图像加密/解密的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么好的例子可以说明如何在 Android 上使用 AES 加密和解密图像和其他文件?

Is there any good example of how to encrypt and decrypt image and other files with AES on Android?

推荐答案

警告:此答案包含您不应使用的代码,因为它不安全(使用 SHA1PRNG 进行密钥派生并在 ECB 模式下使用 AES)

相反(截至 2016 年),在 CBC 或 GCM 模式下使用 PBKDF2WithHmacSHA1 进行密钥派生和 AES(GCM 提供隐私和完整性)

您可以使用以下函数:

Warning: This answer contains code you should not use as it is insecure (using SHA1PRNG for key derivation and using AES in ECB mode)

Instead (as of 2016), use PBKDF2WithHmacSHA1 for key derivation and AES in CBC or GCM mode (GCM provides both privacy and integrity)

You could use functions like these:

private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
    SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
    byte[] encrypted = cipher.doFinal(clear);
    return encrypted;
}

private static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception {
    SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.DECRYPT_MODE, skeySpec);
    byte[] decrypted = cipher.doFinal(encrypted);
    return decrypted;
}

然后像这样调用它们:

ByteArrayOutputStream baos = new ByteArrayOutputStream();  
bm.compress(Bitmap.CompressFormat.PNG, 100, baos); // bm is the bitmap object   
byte[] b = baos.toByteArray();  

byte[] keyStart = "this is a key".getBytes();
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
sr.setSeed(keyStart);
kgen.init(128, sr); // 192 and 256 bits may not be available
SecretKey skey = kgen.generateKey();
byte[] key = skey.getEncoded();    

// encrypt
byte[] encryptedData = encrypt(key,b);
// decrypt
byte[] decryptedData = decrypt(key,encryptedData);

这应该可行,我现在在一个项目中使用类似的代码.

This should work, I use similar code in a project right now.

这篇关于使用 AES256 对称分组密码的图像加密/解密的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆