1 package net.sumaris.core.util.crypto;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26 import com.lambdaworks.codec.Base64;
27 import net.sumaris.core.exception.SumarisTechnicalException;
28 import org.abstractj.kalium.crypto.Util;
29
30 import java.nio.charset.Charset;
31
32 public class CryptoUtils extends Util {
33
34 public static final Charset CHARSET_UTF8 = Charset.forName("UTF-8");
35 public static final Charset CHARSET_ASCII = Charset.forName("US-ASCII");
36
37 public static byte[] zeros(int n) {
38 return new byte[n];
39 }
40
41 public static byte[] copyEnsureLength(byte[] source, int length) {
42 byte[] result = zeros(length);
43 if (source.length > length) {
44 System.arraycopy(source, 0, result, 0, length);
45 }
46 else {
47 System.arraycopy(source, 0, result, 0, source.length);
48 }
49 return result;
50 }
51
52 protected static Charset initCharset(String charsetName) {
53 Charset result = Charset.forName(charsetName);
54 if (result == null) {
55 throw new SumarisTechnicalException("Could not load charset: " + charsetName);
56 }
57 return result;
58 }
59
60 public static byte[] decodeUTF8(String string) {
61 return string.getBytes(CHARSET_UTF8);
62 }
63
64 public static String encodeUTF8(byte[] bytes) {
65 return new String(bytes, CHARSET_UTF8);
66 }
67
68 public static byte[] decodeAscii(String string) {
69 return string.getBytes(CHARSET_ASCII);
70 }
71
72
73 public static byte[] decodeBase64(String data) {
74 return Base64.decode(data.toCharArray());
75 }
76
77 public static String encodeBase64(byte[] data) {
78 return new String(Base64.encode(data));
79 }
80
81 public static byte[] decodeBase58(String data) {
82 try {
83 return Base58.decode(data);
84 } catch (AddressFormatException e) {
85 throw new SumarisTechnicalException("Could decode from base 58: " + e.getMessage());
86 }
87 }
88
89 public static String encodeBase58(byte[] data) {
90 return Base58.encode(data);
91 }
92 }