我正在对我的文件实施加密/解密。代码如下。我找不到问题。
我有什么想念的吗?我需要实现128位AES加密。
有什么问题吗?
结果以错误结束

 "javax.crypto.BadPaddingException: error:1e06b065:Cipher functions:EVP_DecryptFinal_ex:BAD_DECRYPT"


请帮我。

private static byte[] encodeFile(byte[] yourKey, byte[] fileData)
        throws Exception {
    byte[] encrypted = null;
    SecretKeySpec skeySpec = new SecretKeySpec(yourKey, 0, yourKey.length, "AES");
    Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7PADDING");
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
    encrypted = cipher.doFinal(fileData);
    return encrypted;
}

private static byte[] generateKey() throws NoSuchAlgorithmException {
    byte[] keyStart = "This is my key".getBytes();
    String id = "dummypass";
    int iterationCount = 1000;
    int saltLength = 32;
    int keyLength = 128;
    SecureRandom random = new SecureRandom();
    byte[] salt = Arrays.copyOf(keyStart,saltLength);
    random.nextBytes(salt);
    KeySpec keySpec = new PBEKeySpec(id.toCharArray(), salt,
            iterationCount, keyLength);
    SecretKeyFactory keyFactory = SecretKeyFactory
            .getInstance("PBKDF2WithHmacSHA1");
    byte[] keyBytes = new byte[0];
    try {
        keyBytes = keyFactory.generateSecret(keySpec).getEncoded();
    } catch (InvalidKeySpecException e) {
        e.printStackTrace();
    }
    SecretKey key = new SecretKeySpec(keyBytes, "AES");
    return key.getEncoded();
}

private static byte[] decodeFile(byte[] yourKey, byte[] encryptedData)
        throws Exception {
    SecretKeySpec skeySpec = new SecretKeySpec(yourKey, 0, yourKey.length,
            "AES");
    Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7PADDING");
    cipher.init(Cipher.DECRYPT_MODE, skeySpec);
    byte[] decrypted = cipher.doFinal(encryptedData);
    return decrypted;
}

public static void Encrypt(byte[] bytesToEncrypt, File target) {
    try {
        BufferedOutputStream bos = new BufferedOutputStream(
                new FileOutputStream(target));
        byte[] key = generateKey();
        byte[] encryptedBytes = encodeFile(key, bytesToEncrypt);
        bos.write(encryptedBytes);
        bos.flush();
        bos.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
public static  byte[] DecryptFile(byte[] bytesToDecrypt) {
    byte[] decodedData = new byte[0];
    try {
        byte[] key = generateKey();
        decodedData = decodeFile(key, bytesToDecrypt);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return decodedData;
}

最佳答案

验证keyEncrypt中的DecryptFile是否相同。

由于呼叫generateKeygenerateKey都呼叫SecureRandom nextBytes,因此键将有所不同。

您需要保存加密密钥以供解密期间使用。

关于android - Android javax.crypto.BadPaddingException,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42505829/

10-10 10:27