
我找不到用于随机访问的AES CTR加密的任何有效示例.有人可以指导我如何在CTR MODE中使用计数器,又如何实现跳至流中的特定位置吗?
默认流实现(CipherinputStream)不会跳过流,并且会破坏纯文本.
我正在尝试解密存储在Android中sdcard上的加密视频文件.嵌入式http文件服务器会对其进行动态解密.一切正常,直到用户在视频中执行搜索:视频立即停止,因为它接收到损坏的视频流.
我正在使用以下代码初始化和加密/解密流(为简单起见,我对密钥进行了硬编码.在生产中不会对其进行硬编码)
ByteBuffer bb = ByteBuffer.allocate(16); bb.put("1234567891230000".getBytes()); byte[] ivString = bb.array(); // INITIAliSATION String keyString = "1234567812345678"; IvParameterSpec iv = new IvParameterSpec(ivString); SecretKeySpec keySpec = new SecretKeySpec(keyString.getBytes(), "AES"); // FOR ENCRYPTION Cipher cipher = Cipher.getInstance("AES/CTR/Nopadding"); cipher.init(Cipher.ENCRYPT_MODE, keySpec, new IvParameterSpec(ivString)); inputstream encrypted_is = new CipherinputStream(in, cipher); // FOR DECRYPTION cipher.init(Cipher.DECRYPT_MODE, keySpec, new IvParameterSpec(ivString)); inputstream decrypted_is = new CipherinputStream(in, cipher);解决方法:
您不应该使用流来实现它.流用于顺序访问数据.跳过仅用于向前短距离跳跃,而标记/重置仅用于向后短距离跳跃.
使用文件map可能是最有效的.对于稍微简单但效率较低的方法,可以改用RandomAccessFile.此外,您还应该使用“ IV”使用Cipher.getInstance(“ AES / CTR / Nopadding”),该“ IV”设置为在文件中起始位置所需的计数器.
使用带偏移的CTR的示例代码:
private static final int AES_BLOCK_SIZE = 16;public static final voID jumpToOffset(final Cipher c, final SecretKey aesKey, final IvParameterSpec iv, final long offset) { if (!c.getAlgorithm().toupperCase().startsWith("AES/CTR")) { throw new IllegalArgumentException( "InvalID algorithm, only AES/CTR mode supported"); } if (offset < 0) { throw new IllegalArgumentException("InvalID offset"); } final int skip = (int) (offset % AES_BLOCK_SIZE); final IvParameterSpec calculatedivForOffset = calculateIVForOffset(iv, offset - skip); try { c.init(Cipher.ENCRYPT_MODE, aesKey, calculatedivForOffset); final byte[] skipBuffer = new byte[skip]; c.update(skipBuffer, 0, skip, skipBuffer); Arrays.fill(skipBuffer, (byte) 0); } catch (ShortBufferException | InvalIDKeyException | InvalIDAlgorithmParameterException e) { throw new IllegalStateException(e); }}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;} 总结 以上是内存溢出为你收集整理的java-在android中使用AES CTR模式随机访问InputStream全部内容,希望文章能够帮你解决java-在android中使用AES CTR模式随机访问InputStream所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)