Java - 加密部分文件(音频和图像)而不是整个文件?

时间:2011-04-06 01:24:02

标签: java android

我在这里读到了一些相关内容 Android - Increase speed of encryption

我只需要加密部分文件(音频和图像)。这可能吗?如果有可能,有人可以提供加密和解密的片段吗?

提前致谢=)

1 个答案:

答案 0 :(得分:1)

您可以定义加密成员和类的非加密成员。然后,恰好将它们序列化。例如,你的班级可能是这样的:

public Class partiallyEncrypted {
  private transient byte[] imagePart1Decrypted; // transient member will not be serialized by default
  private byte[] imagePart1Encrypted;
  private byte[] imagePart2;
  private static final int BYTES_TO_ENCRYPT = 2048;
  // other non-encrypted fields
  ...

  public setImage(byte[] imageBytes) {
    // calc bytes to encrypt and those left over, initialize arrays
    int bytesToEncrypt = Math.min(imageBytes.length, BYTES_TO_ENCRYPT);
    int bytesLeftOver = Math.max(imageBytes.length - bytesToEncrypt, 0);
    imagePart1Decrypted = new byte[bytesToEncrypt];
    imagePart2 = new byte[bytesLeftOver];

    // copy data into local arrays
    System.arraycopy(imageBytes, 0, imagePart1Decrypted, 0, bytesToEncrypt);
    if (bytesLeftOver > 0)
        System.arraycopy(imageBytes, bytesToEncrypt, imagePart2, 0, bytesLeftOver);

    imagePart1Encrypted = encrypt(bytesToEncrypt);
  }

  public byte[] getImage() {
    if (imagePart1Decrypted == null)
      imagePart1Decrypted = decrypt(imagePart1Encrypted);

    byte[] fullImage = new byte[imagePart1Decrypted.length + imagePart2.length];
    System.arraycopy(imagePart1Decrypted, 0, fullImage, 0, imagePart1Decrypted.length);
    if (imagePart2 != null && imagePart2.length > 0)
        System.arraycopy(imagePart2, 0, fullImage, imagePart1Decrypted.length, imagePart2.length);

    return fullImage;
  }
}