]> git.argeo.org Git - lgpl/argeo-commons.git/blob - org.argeo.enterprise/src/org/argeo/osgi/useradmin/DigestUtils.java
Add JGit to client.
[lgpl/argeo-commons.git] / org.argeo.enterprise / src / org / argeo / osgi / useradmin / DigestUtils.java
1 package org.argeo.osgi.useradmin;
2
3 import java.nio.ByteBuffer;
4 import java.nio.CharBuffer;
5 import java.nio.charset.StandardCharsets;
6 import java.security.MessageDigest;
7 import java.util.Arrays;
8
9 /** Utilities around digests, mostly those related to passwords. */
10 class DigestUtils {
11 static byte[] sha1(byte[] bytes) {
12 try {
13 MessageDigest digest = MessageDigest.getInstance("SHA1");
14 digest.update(bytes);
15 byte[] checksum = digest.digest();
16 return checksum;
17 } catch (Exception e) {
18 throw new UserDirectoryException("Cannot SHA1 digest", e);
19 }
20 }
21
22 static char[] bytesToChars(Object obj) {
23 if (obj instanceof char[])
24 return (char[]) obj;
25 if (!(obj instanceof byte[]))
26 throw new IllegalArgumentException(obj.getClass() + " is not a byte array");
27 ByteBuffer fromBuffer = ByteBuffer.wrap((byte[]) obj);
28 CharBuffer toBuffer = StandardCharsets.UTF_8.decode(fromBuffer);
29 char[] res = Arrays.copyOfRange(toBuffer.array(), toBuffer.position(), toBuffer.limit());
30 // Arrays.fill(fromBuffer.array(), (byte) 0); // clear sensitive data
31 // Arrays.fill((byte[]) obj, (byte) 0); // clear sensitive data
32 // Arrays.fill(toBuffer.array(), '\u0000'); // clear sensitive data
33 return res;
34 }
35
36 static byte[] charsToBytes(char[] chars) {
37 CharBuffer charBuffer = CharBuffer.wrap(chars);
38 ByteBuffer byteBuffer = StandardCharsets.UTF_8.encode(charBuffer);
39 byte[] bytes = Arrays.copyOfRange(byteBuffer.array(), byteBuffer.position(), byteBuffer.limit());
40 // Arrays.fill(charBuffer.array(), '\u0000'); // clear sensitive data
41 // Arrays.fill(byteBuffer.array(), (byte) 0); // clear sensitive data
42 return bytes;
43 }
44
45 static String sha1str(String str) {
46 byte[] hash = sha1(str.getBytes(StandardCharsets.UTF_8));
47 return encodeHexString(hash);
48 }
49
50 final private static char[] hexArray = "0123456789abcdef".toCharArray();
51
52 /**
53 * From
54 * http://stackoverflow.com/questions/9655181/how-to-convert-a-byte-array-to
55 * -a-hex-string-in-java
56 */
57 public static String encodeHexString(byte[] bytes) {
58 char[] hexChars = new char[bytes.length * 2];
59 for (int j = 0; j < bytes.length; j++) {
60 int v = bytes[j] & 0xFF;
61 hexChars[j * 2] = hexArray[v >>> 4];
62 hexChars[j * 2 + 1] = hexArray[v & 0x0F];
63 }
64 return new String(hexChars);
65 }
66
67 private DigestUtils() {
68 }
69 }