mirror of
https://github.com/spring-projects/spring-security.git
synced 2025-06-12 07:02:13 +00:00
SEC-1764: Backport Utf8 encoder to 3.0.x
This commit is contained in:
parent
977da0da1f
commit
7a5a062cd0
@ -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.
|
||||
* <p>
|
||||
* 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);
|
||||
}
|
||||
}
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user