java/jca
SecureRandom 사용하기
tmxhsk99
2019. 6. 5. 08:49
package jce;
import java.security.NoSuchAlgorithmException;
import java.util.FormattableFlags;
import java.util.Formatter;
public class SecureRandom {
public static void main(String[] args) throws NoSuchAlgorithmException {
java.security.SecureRandom random = java.security.SecureRandom.getInstance("SHA1PRNG");
byte bytes [] = new byte[16];
random.nextBytes(bytes);
System.out.println(bytesToHexString(bytes));
}
public static String bytesToHexString(byte[] bytes){
/* StringBuilder sb = new StringBuilder(bytes.length*2);
Formatter formatter = new Formatter(sb);
for(byte b : bytes){
formatter.format("%02x", b);
}
return sb.toString();
*/
final char[] hexArray = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
char[] hexChars = new char[bytes.length * 2];
int v;
for ( int j = 0; j < bytes.length; j++ ) {
v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
}
덤 2. HexTobytes
public byte[] hexToByteArray(String hex) {
if (hex == null || hex.length() == 0) {
return null;
}
byte[] ba = new byte[hex.length() / 2];
for (int i = 0; i < ba.length; i++) {
ba[i] = (byte) Integer.parseInt(hex.substring(2 * i, 2 * i + 2), 16);
}
return ba;
}