]>
git.argeo.org Git - lgpl/argeo-commons.git/blob - org.argeo.enterprise/src/org/argeo/osgi/useradmin/DigestUtils.java
1 package org
.argeo
.osgi
.useradmin
;
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
;
9 /** Utilities around digests, mostly those related to passwords. */
11 static byte[] sha1(byte[] bytes
) {
13 MessageDigest digest
= MessageDigest
.getInstance("SHA1");
15 byte[] checksum
= digest
.digest();
17 } catch (Exception e
) {
18 throw new UserDirectoryException("Cannot SHA1 digest", e
);
22 static char[] bytesToChars(Object obj
) {
23 if (obj
instanceof char[])
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
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
45 static String
sha1str(String str
) {
46 byte[] hash
= sha1(str
.getBytes(StandardCharsets
.UTF_8
));
47 return encodeHexString(hash
);
50 final private static char[] hexArray
= "0123456789abcdef".toCharArray();
54 * http://stackoverflow.com/questions/9655181/how-to-convert-a-byte-array-to
55 * -a-hex-string-in-java
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];
64 return new String(hexChars
);
67 private DigestUtils() {