Prevent adding newline if Base64 buffer encoded ends directly on MAX_LINE_LENGTH

Motivation:

We need to ensure we not add a newline if the Base64 encoded buffer ends directly on the MAX_LINE_LENGTH. If we miss to do so this produce invalid data.
Because of this bug OpenSslServerContext and OpenSslClientContext may fail to load a cert.

Modifications:

- Only add NEW_LINE if we not are on the end of the dst buffer.
- Add unit test

Result:

Correct result in all cases
This commit is contained in:
Norman Maurer 2015-12-18 09:44:57 +01:00
parent ee56a4a5c6
commit 63426fc3ed
2 changed files with 64 additions and 2 deletions

View File

@ -121,11 +121,15 @@ public final class Base64 {
int e = 0;
int len2 = len - 2;
int lineLength = 0;
for (; d < len2; d += 3, e += 4) {
for (; d < len2; e += 4) {
encode3to4(src, d + off, 3, dest, e, dialect);
lineLength += 4;
if (breakLines && lineLength == MAX_LINE_LENGTH) {
d += 3;
if (breakLines && lineLength == MAX_LINE_LENGTH
// Only add NEW_LINE if we not ended directly on the MAX_LINE_LENGTH
&& d < len2) {
dest.setByte(e + 4, NEW_LINE);
e ++;
lineLength = 0;

View File

@ -0,0 +1,58 @@
/*
* Copyright 2015 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.handler.codec.base64;
import io.netty.buffer.ByteBuf;
import io.netty.util.CharsetUtil;
import org.junit.Test;
import static io.netty.buffer.Unpooled.copiedBuffer;
import static org.junit.Assert.assertEquals;
public class Base64Test {
@Test
public void testNotAddNewLineWhenEndOnLimit() {
ByteBuf src = copiedBuffer("abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcde",
CharsetUtil.US_ASCII);
ByteBuf expectedEncoded =
copiedBuffer("YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXphYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5emFiY2Rl",
CharsetUtil.US_ASCII);
testEncode(src, expectedEncoded);
}
@Test
public void testAddNewLine() {
ByteBuf src = copiedBuffer("abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz12345678",
CharsetUtil.US_ASCII);
ByteBuf expectedEncoded =
copiedBuffer("YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXphYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ejEyMzQ1\nNjc4",
CharsetUtil.US_ASCII);
testEncode(src, expectedEncoded);
}
private static void testEncode(ByteBuf src, ByteBuf expectedEncoded) {
ByteBuf encoded = Base64.encode(src, true, Base64Dialect.STANDARD);
try {
assertEquals(expectedEncoded, encoded);
} finally {
src.release();
expectedEncoded.release();
encoded.release();
}
}
}