From 7a5a062cd088010db729cd51514e3be72f33512a Mon Sep 17 00:00:00 2001 From: Luke Taylor Date: Tue, 14 Jun 2011 20:11:03 +0100 Subject: [PATCH] SEC-1764: Backport Utf8 encoder to 3.0.x --- .../security/core/codec/Utf8.java | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 core/src/main/java/org/springframework/security/core/codec/Utf8.java diff --git a/core/src/main/java/org/springframework/security/core/codec/Utf8.java b/core/src/main/java/org/springframework/security/core/codec/Utf8.java new file mode 100644 index 0000000000..ff1aeb8765 --- /dev/null +++ b/core/src/main/java/org/springframework/security/core/codec/Utf8.java @@ -0,0 +1,42 @@ +package org.springframework.security.core.codec; + +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. + *

+ * For internal use only. + * + * @author Luke Taylor + */ +public final class Utf8 { + private static final Charset CHARSET = Charset.forName("UTF-8"); + + /** + * Get the bytes of the String in UTF-8 encoded form. + */ + public static byte[] encode(CharSequence string) { + try { + 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); + } + } + + /** + * Decode the bytes in UTF-8 form into a String. + */ + public static String decode(byte[] bytes) { + try { + return CHARSET.newDecoder().decode(ByteBuffer.wrap(bytes)).toString(); + } catch (CharacterCodingException e) { + throw new IllegalArgumentException("Decoding failed", e); + } + } +}