无法解密使用SecureRandom加密的数据

时间:2018-10-03 21:01:19

标签: java android encryption cryptography

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();
}

1 个答案:

答案 0 :(得分:0)

最后我可以解决这个问题。感谢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);
    }
}