【问题标题】:Can not decrypt data which was encrypted using SecureRandom无法解密使用 SecureRandom 加密的数据
【发布时间】:2018-10-03 21:01:18
【问题描述】:

我在 2 年前使用此代码段来加密我的图像数据。当时我的目标 SDK 是 22。但是当我尝试更新我的 SDK 时,我面临我无法解密它。我发现 Android 弃用了这种加密方法。有什么办法可以解决这个问题,以便我可以解密我的图像。 提前致谢。

public byte[] EncryptByte(byte[] rawInputByte){        

    byte[] fileBytes = null;
    try {
        byte[] yourKey = generateKey("password");
        fileBytes = encodeFile(yourKey, rawInputByte);

    } catch (Exception e) {
        e.printStackTrace();            
    }

    return fileBytes;
}

public byte[] generateKey(String password) throws Exception
{
    byte[] keyStart = password.getBytes("UTF-8");

    KeyGenerator kgen = KeyGenerator.getInstance("AES");
    SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "Crypto");
    sr.setSeed(keyStart);
    kgen.init(128, sr);
    SecretKey skey = kgen.generateKey();
    return skey.getEncoded();
}

【问题讨论】:

标签: java android encryption cryptography


【解决方案1】:

我终于可以解决这个问题了。感谢 James K Polk 给我链接。下面给出了我的代码段,InsecureSHA1PRNGKeyDerivator 链接是this。希望对大家有所帮助。

public byte[] decodeFile(byte[] fileData) throws Exception
{     
    SecretKey insecureKey = deriveKeyInsecurely("password", 16);
    byte[] decryptedData = decryptData(fileData, insecureKey);

    return decryptedData;
}

@RequiresApi(api = Build.VERSION_CODES.KITKAT)
private static SecretKey deriveKeyInsecurely(String password, int
        keySizeInBytes) throws Exception {
    byte[] passwordBytes = password.getBytes(StandardCharsets.US_ASCII);
    return new SecretKeySpec( InsecureSHA1PRNGKeyDerivator.deriveInsecureKey(  passwordBytes, keySizeInBytes),  "AES");
}


private static byte[] decryptData(
        byte[] data, SecretKey key) {
    try {
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, key );

        return cipher.doFinal(data);
    } catch (GeneralSecurityException e) {
        throw new RuntimeException("This is unconceivable!", e);
    }
}

【讨论】:

    猜你喜欢
    • 2020-04-07
    • 1970-01-01
    • 1970-01-01
    • 2013-09-03
    • 2017-12-19
    • 2011-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多