AesGcmInputStream.java org::apache::iceberg::encryption::AesGcmInputStream org::apache::iceberg::encryption /* *LicensedtotheApacheSoftwareFoundation(ASF)underone *ormorecontributorlicenseagreements.SeetheNOTICEfile *distributedwiththisworkforadditionalinformation *regardingcopyrightownership.TheASFlicensesthisfile *toyouundertheApacheLicense,Version2.0(the *"License");youmaynotusethisfileexceptincompliance *withtheLicense.YoumayobtainacopyoftheLicenseat * *http://www.apache.org/licenses/LICENSE-2.0 * *Unlessrequiredbyapplicablelaworagreedtoinwriting, *softwaredistributedundertheLicenseisdistributedonan *"ASIS"BASIS,WITHOUTWARRANTIESORCONDITIONSOFANY *KIND,eitherexpressorimplied.SeetheLicenseforthe *specificlanguagegoverningpermissionsandlimitations *undertheLicense. */ packageorg.apache.iceberg.encryption; importjava.io.EOFException; importjava.io.IOException; importjava.nio.ByteBuffer; importjava.nio.ByteOrder; importorg.apache.iceberg.io.IOUtil; importorg.apache.iceberg.io.SeekableInputStream; importorg.apache.iceberg.relocated.com.google.common.base.Preconditions; publicclassAesGcmInputStreamextendsSeekableInputStream{ privatefinalSeekableInputStreamsourceStream; privatefinalbyte[]fileAADPrefix; privatefinalCiphers.AesGcmDecryptordecryptor; privatefinalbyte[]cipherBlockBuffer; privatefinalbyte[]currentPlainBlock; privatefinallongnumBlocks; privatefinalintlastCipherBlockSize; privatefinallongplainStreamSize; privatefinalbyte[]singleByte; privatelongplainStreamPosition; privatelongcurrentPlainBlockIndex; privateintcurrentPlainBlockSize; AesGcmInputStream( SeekableInputStreamsourceStream,longsourceLength,byte[]aesKey,byte[]fileAADPrefix){ this.sourceStream=sourceStream; this.fileAADPrefix=fileAADPrefix; this.decryptor=newCiphers.AesGcmDecryptor(aesKey); this.cipherBlockBuffer=newbyte[Ciphers.CIPHER_BLOCK_SIZE]; this.currentPlainBlock=newbyte[Ciphers.PLAIN_BLOCK_SIZE]; this.plainStreamPosition=0; this.currentPlainBlockIndex=-1; this.currentPlainBlockSize=0; longstreamLength=sourceLength-Ciphers.GCM_STREAM_HEADER_LENGTH; longnumFullBlocks=Math.toIntExact(streamLength/Ciphers.CIPHER_BLOCK_SIZE); longcipherFullBlockLength=numFullBlocks*Ciphers.CIPHER_BLOCK_SIZE; intcipherBytesInLastBlock=Math.toIntExact(streamLength-cipherFullBlockLength); booleanfullBlocksOnly=(0==cipherBytesInLastBlock); this.numBlocks=fullBlocksOnly?numFullBlocks:numFullBlocks+1; this.lastCipherBlockSize= fullBlocksOnly?Ciphers.CIPHER_BLOCK_SIZE:cipherBytesInLastBlock;//never0 longlastPlainBlockSize= (long)lastCipherBlockSize-Ciphers.NONCE_LENGTH-Ciphers.GCM_TAG_LENGTH; this.plainStreamSize= numFullBlocks*Ciphers.PLAIN_BLOCK_SIZE+(fullBlocksOnly?0:lastPlainBlockSize); this.singleByte=newbyte[1]; } privatevoidvalidateHeader()throwsIOException{ byte[]headerBytes=newbyte[Ciphers.GCM_STREAM_HEADER_LENGTH]; IOUtil.readFully(sourceStream,headerBytes,0,headerBytes.length); Preconditions.checkState( Ciphers.GCM_STREAM_MAGIC.equals(ByteBuffer.wrap(headerBytes,0,4)), "InvalidGCMstream:magicdoesnotmatchAGS1"); intplainBlockSize=ByteBuffer.wrap(headerBytes,4,4).order(ByteOrder.LITTLE_ENDIAN).getInt(); Preconditions.checkState( plainBlockSize==Ciphers.PLAIN_BLOCK_SIZE, "InvalidGCMstream:blocksize%d!=%d", plainBlockSize, Ciphers.PLAIN_BLOCK_SIZE); } @Override publicintavailable(){ longmaxAvailable=plainStreamSize-plainStreamPosition; //SeeInputStream.availablecontract if(maxAvailable>=Integer.MAX_VALUE){ returnInteger.MAX_VALUE; }else{ return(int)maxAvailable; } } privateintavailableInCurrentBlock(){ if(blockIndex(plainStreamPosition)!=currentPlainBlockIndex){ return0; } returncurrentPlainBlockSize-offsetInBlock(plainStreamPosition); } @Override publicintread(byte[]b,intoff,intlen)throwsIOException{ Preconditions.checkArgument(len>=0,"Invalidreadlength:"+len); if(currentPlainBlockIndex<0){ decryptBlock(0); } if(available()<=0&&len>0){ return-1; } if(len==0){ return0; } inttotalBytesRead=0; intresultBufferOffset=off; intremainingBytesToRead=len; while(remainingBytesToRead>0){ intavailableInBlock=availableInCurrentBlock(); if(availableInBlock>0){ intbytesToCopy=Math.min(availableInBlock,remainingBytesToRead); intoffsetInBlock=offsetInBlock(plainStreamPosition); System.arraycopy(currentPlainBlock,offsetInBlock,b,resultBufferOffset,bytesToCopy); totalBytesRead+=bytesToCopy; remainingBytesToRead-=bytesToCopy; resultBufferOffset+=bytesToCopy; this.plainStreamPosition+=bytesToCopy; }elseif(available()>0){ decryptBlock(blockIndex(plainStreamPosition)); }else{ break; } } //return-1forEOF returntotalBytesRead>0?totalBytesRead:-1; } @Override publicvoidseek(longnewPos)throwsIOException{ if(newPos<0){ thrownewIOException("Invalidposition:"+newPos); }elseif(newPos>plainStreamSize){ thrownewEOFException( "Invalidposition:"+newPos+">streamlength,"+plainStreamSize); } this.plainStreamPosition=newPos; } @Override publiclongskip(longn){ if(n<=0){ return0; } longbytesLeftInStream=plainStreamSize-plainStreamPosition; if(n>bytesLeftInStream){ //skiptherestofthestream this.plainStreamPosition=plainStreamSize; returnbytesLeftInStream; } this.plainStreamPosition+=n; returnn; } @Override publiclonggetPos()throwsIOException{ returnplainStreamPosition; } @Override publicintread()throwsIOException{ intread=read(singleByte); if(read==-1){ return-1; } returnsingleByte[0]>=0?singleByte[0]:256+singleByte[0]; } @Override publicvoidclose()throwsIOException{ sourceStream.close(); } privatevoiddecryptBlock(longblockIndex)throwsIOException{ if(blockIndex==currentPlainBlockIndex){ return; } longblockPositionInStream=blockOffset(blockIndex); if(sourceStream.getPos()!=blockPositionInStream){ if(sourceStream.getPos()==0){ validateHeader(); } sourceStream.seek(blockPositionInStream); } booleanisLastBlock=blockIndex==numBlocks-1; intcipherBlockSize=isLastBlock?lastCipherBlockSize:Ciphers.CIPHER_BLOCK_SIZE; IOUtil.readFully(sourceStream,cipherBlockBuffer,0,cipherBlockSize); byte[]blockAAD=Ciphers.streamBlockAAD(fileAADPrefix,Math.toIntExact(blockIndex)); decryptor.decrypt(cipherBlockBuffer,0,cipherBlockSize,currentPlainBlock,0,blockAAD); this.currentPlainBlockSize=cipherBlockSize-Ciphers.NONCE_LENGTH-Ciphers.GCM_TAG_LENGTH; this.currentPlainBlockIndex=blockIndex; } privatestaticlongblockIndex(longplainPosition){ returnplainPosition/Ciphers.PLAIN_BLOCK_SIZE; } privatestaticintoffsetInBlock(longplainPosition){ returnMath.toIntExact(plainPosition%Ciphers.PLAIN_BLOCK_SIZE); } privatestaticlongblockOffset(longblockIndex){ returnblockIndex*Ciphers.CIPHER_BLOCK_SIZE+Ciphers.GCM_STREAM_HEADER_LENGTH; } staticlongcalculatePlaintextLength(longsourceLength){ longstreamLength=sourceLength-Ciphers.GCM_STREAM_HEADER_LENGTH; if(streamLength==0){ return0; } longnumberOfFullBlocks=streamLength/Ciphers.CIPHER_BLOCK_SIZE; longfullBlockSize=numberOfFullBlocks*Ciphers.CIPHER_BLOCK_SIZE; longcipherBytesInLastBlock=streamLength-fullBlockSize; booleanfullBlocksOnly=(0==cipherBytesInLastBlock); longplainBytesInLastBlock= fullBlocksOnly ?0 :(cipherBytesInLastBlock-Ciphers.NONCE_LENGTH-Ciphers.GCM_TAG_LENGTH); return(numberOfFullBlocks*Ciphers.PLAIN_BLOCK_SIZE)+plainBytesInLastBlock; } }