From 647184e617c396b5e96dd1a65ffd0eb3ec362da4 Mon Sep 17 00:00:00 2001 From: Yutong Xiao Date: Thu, 23 Dec 2021 00:00:12 +0800 Subject: [PATCH] HBASE-26613 The logic of the method incrementIV in Encryption class has problem (#3968) Signed-off-by: Duo Zhang --- .../hadoop/hbase/io/crypto/Encryption.java | 21 ++++++++----------- .../hbase/io/crypto/TestEncryption.java | 20 ++++++++++++++++++ 2 files changed, 29 insertions(+), 12 deletions(-) diff --git a/hbase-common/src/main/java/org/apache/hadoop/hbase/io/crypto/Encryption.java b/hbase-common/src/main/java/org/apache/hadoop/hbase/io/crypto/Encryption.java index 6adcae5b22e..807758958d0 100644 --- a/hbase-common/src/main/java/org/apache/hadoop/hbase/io/crypto/Encryption.java +++ b/hbase-common/src/main/java/org/apache/hadoop/hbase/io/crypto/Encryption.java @@ -640,20 +640,17 @@ public final class Encryption { } public static void incrementIv(byte[] iv, int v) { + // v should be > 0 int length = iv.length; - boolean carry = true; - // TODO: Optimize for v > 1, e.g. 16, 32 - do { - for (int i = 0; i < length; i++) { - if (carry) { - iv[i] = (byte) ((iv[i] + 1) & 0xFF); - carry = 0 == iv[i]; - } else { - break; - } + int sum = 0; + for (int i = 0; i < length; i++) { + if (v <= 0) { + break; } - v--; - } while (v > 0); + sum = v + (iv[i] & 0xFF); + v = sum / 256; + iv[i] = (byte)(sum % 256); + } } /** diff --git a/hbase-common/src/test/java/org/apache/hadoop/hbase/io/crypto/TestEncryption.java b/hbase-common/src/test/java/org/apache/hadoop/hbase/io/crypto/TestEncryption.java index 829be39f612..8d850a7aa4e 100644 --- a/hbase-common/src/test/java/org/apache/hadoop/hbase/io/crypto/TestEncryption.java +++ b/hbase-common/src/test/java/org/apache/hadoop/hbase/io/crypto/TestEncryption.java @@ -89,6 +89,26 @@ public class TestEncryption { } } + @Test + public void testIncrementIV() { + byte[] iv = new byte[] {1, 2, 3}; + byte[] iv_neg = new byte[] {-3, -13, 25}; + Encryption.incrementIv(iv); + assertTrue(Bytes.equals(iv, new byte[] {2, 2, 3})); + + Encryption.incrementIv(iv, 255); + assertTrue(Bytes.equals(iv, new byte[] {1, 3, 3})); + + Encryption.incrementIv(iv, 1024); + assertTrue(Bytes.equals(iv, new byte[] {1, 7, 3})); + + Encryption.incrementIv(iv_neg); + assertTrue(Bytes.equals(iv_neg, new byte[] {-2, -13, 25})); + + Encryption.incrementIv(iv_neg, 5); + assertTrue(Bytes.equals(iv_neg, new byte[] {3, -12, 25})); + } + private void checkTransformSymmetry(byte[] keyBytes, byte[] iv, byte[] plaintext) throws Exception { LOG.info("checkTransformSymmetry: AES, plaintext length = " + plaintext.length);