diff --git a/core/src/main/java/org/springframework/security/crypto/codec/Utf8.java b/core/src/main/java/org/springframework/security/crypto/codec/Utf8.java index 94b80f77a9..9a2d0c568d 100644 --- a/core/src/main/java/org/springframework/security/crypto/codec/Utf8.java +++ b/core/src/main/java/org/springframework/security/crypto/codec/Utf8.java @@ -4,6 +4,7 @@ import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.CharacterCodingException; import java.nio.charset.Charset; +import java.util.*; /** * UTF-8 Charset encoder/decoder. @@ -20,7 +21,9 @@ public final class Utf8 { */ public static byte[] encode(CharSequence string) { try { - return CHARSET.newEncoder().encode(CharBuffer.wrap(string)).array(); + ByteBuffer bytes = CHARSET.newEncoder().encode(CharBuffer.wrap(string)); + + return Arrays.copyOfRange(bytes.array(), 0, bytes.limit()); } catch (CharacterCodingException e) { throw new IllegalArgumentException("Encoding failed", e); } @@ -31,9 +34,9 @@ public final class Utf8 { */ public static String decode(byte[] bytes) { try { - return new String(CHARSET.newDecoder().decode(ByteBuffer.wrap(bytes)).array()); + return CHARSET.newDecoder().decode(ByteBuffer.wrap(bytes)).toString(); } catch (CharacterCodingException e) { - throw new IllegalArgumentException("Encoding failed", e); + throw new IllegalArgumentException("Decoding failed", e); } } } diff --git a/core/src/test/java/org/springframework/security/crypto/codec/Utf8Tests.java b/core/src/test/java/org/springframework/security/crypto/codec/Utf8Tests.java new file mode 100644 index 0000000000..363de65560 --- /dev/null +++ b/core/src/test/java/org/springframework/security/crypto/codec/Utf8Tests.java @@ -0,0 +1,25 @@ +package org.springframework.security.crypto.codec; + +import static org.junit.Assert.*; + +import org.junit.*; + +import java.util.*; + +/** + * @author Luke Taylor + */ +public class Utf8Tests { + + // SEC-1752 + @Test + public void utf8EncodesAndDecodesCorrectly() throws Exception { + byte[] bytes = Utf8.encode("6048b75ed560785c"); + assertEquals(16, bytes.length); + assertTrue(Arrays.equals("6048b75ed560785c".getBytes("UTF-8"), bytes)); + + String decoded = Utf8.decode(bytes); + + assertEquals("6048b75ed560785c", decoded); + } +}