-
SecureRandom 사용하기java/jca 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; }
'java > jca' 카테고리의 다른 글
블록 암호를 사용한 암/복호화 (0) 2019.06.24 Runnable을 활용한 파일의 해시값 계산 (0) 2019.06.24 MessageDigest 클래스를 사용한 해시값 생성 (0) 2019.06.11 Bouncy Castle Provider 등록하기 (0) 2019.06.04 자바 대칭키 암호화 복호화 예제 (0) 2019.04.26