View Javadoc
1   package net.sumaris.core.util.crypto;
2   
3   /*
4    * #%L
5    * Duniter4j :: Core API
6    * %%
7    * Copyright (C) 2014 - 2015 EIS
8    * %%
9    * This program is free software: you can redistribute it and/or modify
10   * it under the terms of the GNU General Public License as
11   * published by the Free Software Foundation, either version 3 of the 
12   * License, or (at your option) any later version.
13   * 
14   * This program is distributed in the hope that it will be useful,
15   * but WITHOUT ANY WARRANTY; without even the implied warranty of
16   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17   * GNU General Public License for more details.
18   * 
19   * You should have received a copy of the GNU General Public 
20   * License along with this program.  If not, see
21   * <http://www.gnu.org/licenses/gpl-3.0.html>.
22   * #L%
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  }