1 /*
2 * Copyright 2015-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License").
5 * You may not use this file except in compliance with the License.
6 * A copy of the License is located at
7 *
8 * http://aws.amazon.com/apache2.0
9 *
10 * or in the "license" file accompanying this file. This file is distributed
11 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
12 * express or implied. See the License for the specific language governing
13 * permissions and limitations under the License.
14 */
15 package com.amazonaws.util;
16
17 /**
18 * A Base 16 codec API, which encodes into hex string in lower case.
19 *
20 * See http://www.ietf.org/rfc/rfc4648.txt
21 *
22 * @author Hanson Char
23 */
24 public enum Base16Lower {
25 ;
26 private static final Base16Codec codec = new Base16Codec(false);
27
28 /**
29 * Returns a base 16 encoded string (in lower case) of the given bytes.
30 */
31 public static String encodeAsString(byte ... bytes) {
32 if (bytes == null)
33 return null;
34 return bytes.length == 0 ? "" : CodecUtils.toStringDirect(codec.encode(bytes));
35 }
36
37 /**
38 * Returns a base 16 encoded byte array of the given bytes.
39 */
40 public static byte[] encode(byte[] bytes) { return bytes == null || bytes.length == 0 ? bytes : codec.encode(bytes); }
41
42 /**
43 * Decodes the given base 16 encoded string,
44 * skipping carriage returns, line feeds and spaces as needed.
45 */
46 public static byte[] decode(String b16) {
47 if (b16 == null)
48 return null;
49 if (b16.length() == 0)
50 return new byte[0];
51 byte[] buf = new byte[b16.length()];
52 int len = CodecUtils.sanitize(b16, buf);
53 return codec.decode(buf, len);
54 }
55
56 /**
57 * Decodes the given base 16 encoded bytes.
58 */
59 public static byte[] decode(byte[] b16) { return b16 == null || b16.length == 0 ? b16 : codec.decode(b16, b16.length); }
60 }
61