【问题标题】:Problem with decryption , cipher in android AES/CTR/NoPadding解密问题,android AES/CTR/NoPadding 中的密码
【发布时间】:2019-08-21 11:36:22
【问题描述】:

当我在 android Marshmallow(Android 6.0.1) 上使用此代码时,解密是好的,但是当我在带有 android Oreo(Android 8) 的设备上运行时,解密值不一样并且数据不正确。

private void decrypt(Cipher cipher, Uri uri) throws Exception {
    long a = 113845229;
    InputStream inputStream = getContentResolver().openInputStream(uri);
    CipherInputStream cipherInputStream = new CipherInputStream(inputStream, cipher);
    cipherInputStream.skip(a);
    byte[] buffer = new byte[8];
    cipherInputStream.read(buffer);
}

// create cipher
private Cipher createCipher(byte[] iv, byte[] salt, String password) throws Exception {
    IvParameterSpec mIvParameterSpec = new IvParameterSpec(iv);
    SecretKeySpec mSecretKeySpec = generate(password, salt);
    Cipher mCipher = Cipher.getInstance("AES/CTR/NoPadding");
    mCipher.init(Cipher.DECRYPT_MODE, mSecretKeySpec, mIvParameterSpec);
    return mCipher;
}
// generate key
private SecretKeySpec generate(String password, byte[] salt) throws Exception {
    MessageDigest md = MessageDigest.getInstance("SHA-256");
    md.update(salt);
    byte[] key = md.digest(password.getBytes(StandardCharsets.UTF_8));
    return new SecretKeySpec(key, "AES");
}

缓冲区数据在 android 6 中正常,但在 android 8 中数据不正确。

【问题讨论】:

  • 欢迎来到 SO。请在最小、完整、可验证的示例后获得更好的答案。
  • 您能测试skip 方法返回的值吗?这总是一种危险的方法,API 可能会跳过比请求更少的字节。还不清楚它对底层密码的作用:字节是否通过它?可能您应该跳过父流。
  • @MaartenBodewes:skip() 方法有效并通过密码传递数据,但您必须绝对检查返回值。由于内部缓冲区的大小,OpenJDK 版本每次调用不会跳过超过 512 个字节。我不知道 Android 是做什么的,但它可能是相似的。
  • 我个人会通过使用内存映射文件而不是使用流来解决这个问题。您可以通过巧妙地更改 IV 将计数器设置为 CTR 模式,无需跳过密码本身的任何内容。
  • 我应该指出skip() 的工作原理是它可以正确地跳过纯文本,但它对您的问题完全没用。要么使用read() 并丢弃字节,要么更有效地根据@MaartenBodewes 的建议和seek() 在块(16 字节)边界上将IV 巧妙地更改为您感兴趣的文件中的偏移量。如果流不可搜索,那么您将无法使用 read()

标签: java android encryption inputstream android-version


【解决方案1】:

我相信你正在寻找random access to ctr encrypted data; CipherInputStream 中的 Skip 方法并没有这样做,并且是“独立于 Android 版本”(仍在使用中;自 api 级别 1! 以来未弃用或替换!);

看一下 CipherInputStream 类文件;它的内部属性很少:

private Cipher cipher;//the cipher you pass to constructor;
// the underlying input stream
private InputStream input;
/* the buffer holding data that have been read in from the
   underlying stream, but have not been processed by the cipher
   engine. the size 512 bytes is somewhat randomly chosen */
private byte[] ibuffer = new byte[512];//holds encrypted data
// having reached the end of the underlying input stream
private boolean done = false;
/* the buffer holding data that have been processed by the cipher
   engine, but have not been read out */
private byte[] obuffer;//a portion of data that's decrypted but not yet read;
// the offset pointing to the next "new" byte
private int ostart = 0;
// the offset pointing to the last "new" byte
private int ofinish = 0;

这就是skip在CipherInputStream中所做的;

public long skip(long n) throws IOException {
    int available = ofinish - ostart;
    if (n > available) {
        n = available;
    }
    if (n < 0) {
        return 0;
    }
    ostart += n;
    return n;
}

它不会将新数据加载到缓冲区或 ibuffer;它只会跳过缓冲区中可用的内容(只是增加 ostart);

应该这样做(有改进的余地):

private static IvParameterSpec calculateIVForOffset(final IvParameterSpec iv,
    final long blockOffset) {
    final BigInteger ivBI = new BigInteger(1, iv.getIV());
    final BigInteger ivForOffsetBI = ivBI.add(BigInteger.valueOf(blockOffset
        / AES_BLOCK_SIZE));

    final byte[] ivForOffsetBA = ivForOffsetBI.toByteArray();
    final IvParameterSpec ivForOffset;
    if (ivForOffsetBA.length >= AES_BLOCK_SIZE) {
    ivForOffset = new IvParameterSpec(ivForOffsetBA, ivForOffsetBA.length - AES_BLOCK_SIZE,
            AES_BLOCK_SIZE);
    } else {
        final byte[] ivForOffsetBASized = new byte[AES_BLOCK_SIZE];
        System.arraycopy(ivForOffsetBA, 0, ivForOffsetBASized, AES_BLOCK_SIZE
            - ivForOffsetBA.length, ivForOffsetBA.length);
        ivForOffset = new IvParameterSpec(ivForOffsetBASized);
    }
    return ivForOffset;
}
long offset = 113845229;// aka a
private void decrypt(Cipher cipher, Uri uri) throws Exception {
    long skip_this_much=offset-(offset%16);
    InputStream inputStream = getContentResolver().openInputStream(uri);
    do{
        skip_this_much=skip_this_much-inputStream.skip(skip_this_much);//InputStream.skip does not necessarily skip as much as specified in parameter and returns the actually skipped value;
    }while(skip_this_much!=0);//not there yet; keep skipping;
    CipherInputStream cipherInputStream = new CipherInputStream(inputStream, cipher);
    int read_this_much=8;
    byte[] buffer=new byte[read_this_much+(offset%16)];
    cipherInputStream.read(buffer,0,read_this_much+(offset%16));//improve this yourself
    buffer= Arrays.copyOfRange(buffer,offset%16,read_this_much+(offset%16));
}
// create cipher for offset
private Cipher createCipher(byte[] iv, byte[] salt, String password) throws Exception {
    IvParameterSpec mIvParameterSpec = new IvParameterSpec(iv);
    SecretKeySpec mSecretKeySpec = generate(password, salt);
    Cipher mCipher = Cipher.getInstance("AES/CTR/NoPadding");
    mCipher.init(Cipher.DECRYPT_MODE, mSecretKeySpec, calculateIVForOffset(mIvParameterSpec,offset));
    return mCipher;
}
// generate key
private SecretKeySpec generate(String password, byte[] salt) throws Exception {
    MessageDigest md = MessageDigest.getInstance("SHA-256");
    md.update(salt);
    byte[] key = md.digest(password.getBytes(StandardCharsets.UTF_8));
    return new SecretKeySpec(key, "AES");
}

【讨论】:

  • 这绝对是错误的。在底层输入流上调用 skip 会推进流而不推进计数器。然后被解密的数据将不正确。
  • @James K Polk 你是对的;它滑倒了;坏了;
  • 还是有点危险,直到cc 为零我才会调用skip,我宁愿倒数需要跳过的字节数而不是依赖于0 值(这可能是因为例如,文件更短)。或者,如前所述,最好不要依赖它。
【解决方案2】:

我经过研究得出结论。您应该使用特定的 Cipher 实现 InputStream。

private static final int AES_BLOCK_SIZE = 16;
private InputStream mUpstream;
private Cipher mCipher;
private SecretKeySpec mSecretKeySpec;
private IvParameterSpec mIvParameterSpec;

public StreamingCipherInputStream(InputStream inputStream, Cipher cipher, 
    SecretKeySpec secretKeySpec, IvParameterSpec ivParameterSpec) {
    super(inputStream, cipher);
    mUpstream = inputStream;
    mCipher = cipher;
    mSecretKeySpec = secretKeySpec;
    mIvParameterSpec = ivParameterSpec; }
@Override
public int read(byte[] b, int off, int len) throws IOException {
    return super.read(b, off, len);  }
public long forceSkip(long bytesToSkip) throws IOException {
    long skipped = mUpstream.skip(bytesToSkip);
    try {
        int skip = (int) (bytesToSkip % AES_BLOCK_SIZE);
        long blockOffset = bytesToSkip - skip;
        long numberOfBlocks = blockOffset / AES_BLOCK_SIZE;

        BigInteger ivForOffsetAsBigInteger = new BigInteger(1, 
        mIvParameterSpec.getIV()).add(BigInteger.valueOf(numberOfBlocks));
        byte[] ivForOffsetByteArray = ivForOffsetAsBigInteger.toByteArray();
        IvParameterSpec computedIvParameterSpecForOffset;
        if (ivForOffsetByteArray.length < AES_BLOCK_SIZE) {
            byte[] resizedIvForOffsetByteArray = new byte[AES_BLOCK_SIZE];
            System.arraycopy(ivForOffsetByteArray, 0, resizedIvForOffsetByteArray, 
            AES_BLOCK_SIZE - ivForOffsetByteArray.length, ivForOffsetByteArray.length);
            computedIvParameterSpecForOffset = new IvParameterSpec(resizedIvForOffsetByteArray);
        } else {
            computedIvParameterSpecForOffset = new IvParameterSpec(ivForOffsetByteArray, ivForOffsetByteArray.length - AES_BLOCK_SIZE, AES_BLOCK_SIZE);
        }
        mCipher.init(Cipher.ENCRYPT_MODE, mSecretKeySpec, computedIvParameterSpecForOffset);
        byte[] skipBuffer = new byte[skip];
        mCipher.update(skipBuffer, 0, skip, skipBuffer);
        Arrays.fill(skipBuffer, (byte) 0);
    } catch (Exception e) {
        return 0;
    }
    return skipped;
}
@Override
public int available() throws IOException {
    return mUpstream.available();}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-01
    • 2016-11-14
    • 2015-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多