반응형
Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 | 29 |
30 | 31 |
Tags
- Eclipse
- 이클립스
- 자바스크립트
- js
- 이탈리아
- vscode
- 문자열
- string
- windows
- 인텔리제이
- list
- table
- Maven
- javascript
- Button
- IntelliJ
- 배열
- Java
- 자바
- html
- date
- ArrayList
- input
- 테이블
- 정규식
- CSS
- CMD
- Array
- json
- Visual Studio Code
Archives
- Today
- Total
어제 오늘 내일
[Java] 랜덤 문자열 생성하기 본문
Java에서 랜덤 문자열 생성 방법
Java에서 영문자, 숫자, 특수 문자 등으로 이루어진 랜덤 문자열을 생성하는 방법을 살펴보겠습니다.
1. Random 클래스를 이용한 랜덤 문자열 생성 (기본 방법)
import java.util.Random;
public class RandomStringGenerator {
public static void main(String[] args) {
int length = 10; // 원하는 문자열 길이
String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; // 사용 가능한 문자
StringBuilder sb = new StringBuilder();
Random random = new Random();
for (int i = 0; i < length; i++) {
int index = random.nextInt(characters.length()); // 랜덤 인덱스 선택
sb.append(characters.charAt(index));
}
System.out.println("랜덤 문자열: " + sb.toString());
}
}
출력 예시
랜덤 문자열: Xy9aZ3LmQp
설명
- characters → 사용할 문자들(영문 대소문자 + 숫자).
- random.nextInt(characters.length()) → 문자열에서 랜덤한 문자 선택.
- StringBuilder를 사용하여 랜덤하게 선택된 문자들을 추가.
2. UUID를 이용한 랜덤 문자열 생성
UUID (Universally Unique Identifier) 는 중복 가능성이 극히 낮은 고유 문자열을 생성하는 데 사용됩니다.
import java.util.UUID;
public class UUIDExample {
public static void main(String[] args) {
String randomUUID = UUID.randomUUID().toString();
System.out.println("랜덤 UUID: " + randomUUID);
// 하이픈 제거한 짧은 버전
String shortUUID = randomUUID.replace("-", "");
System.out.println("짧은 랜덤 문자열: " + shortUUID);
}
}
출력 예시
랜덤 UUID: 4b1e2a64-5c39-4c9e-b1d6-48a9d06cb8e5
짧은 랜덤 문자열: 4b1e2a645c394c9eb1d648a9d06cb8e5
설명
- UUID.randomUUID().toString() → 고유한 UUID 생성하여 문자열로 변환
- UUID는 32자리 16진수(0
9, af)와 4개의 하이픈(-)으로 이루어진 36자리 문자열. - 형식: 8-4-4-4-12 (하이픈 포함)
- UUID는 32자리 16진수(0
- .replace("-", "") → UUID에서 모든 -(하이픈)을 제거.
3. SecureRandom을 이용한 보안성이 높은 랜덤 문자열 생성
SecureRandom은 일반 Random보다 예측 불가능한 난수를 생성합니다.
import java.security.SecureRandom;
public class SecureRandomString {
public static void main(String[] args) {
int length = 12;
String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*";
StringBuilder sb = new StringBuilder();
SecureRandom secureRandom = new SecureRandom();
for (int i = 0; i < length; i++) {
int index = secureRandom.nextInt(characters.length());
sb.append(characters.charAt(index));
}
System.out.println("보안 랜덤 문자열: " + sb.toString());
}
}
출력 예시
보안 랜덤 문자열: A8#b$LmZ9Qp*
4. Apache Commons Lang 라이브러리 사용
Apache Commons Lang의 RandomStringUtils 클래스를 사용하면 매우 쉽게 랜덤 문자열을 생성할 수 있습니다.
1) Maven 의존성 추가
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
2) 코드 구현
import org.apache.commons.lang3.RandomStringUtils;
public class ApacheRandomString {
public static void main(String[] args) {
// 10자리의 알파벳 + 숫자 조합 랜덤 문자열 생성
String randomString = RandomStringUtils.randomAlphanumeric(10);
System.out.println("Apache 랜덤 문자열: " + randomString);
}
}
출력 예시
Apache 랜덤 문자열: A1bX9ZLmQp
설명
- RandomStringUtils 클래스는
- Apache Commons Lang 3 라이브러리에서 제공하는 유틸리티 클래스.
- 기본적인 난수 생성보다 간편하고 강력한 기능 제공.
- RandomStringUtils.randomAlphanumeric(10)
- 10자리의 랜덤 문자열 생성.
- 영문 대소문자(A-Z, a-z) + 숫자(0-9) 포함.
5. 비밀번호 생성기 (영문자 + 숫자 + 특수문자 포함)
이 코드는 대문자, 소문자, 숫자, 특수문자를 포함하는 랜덤 비밀번호를 생성하는 Java 프로그램입니다.
import java.security.SecureRandom;
public class RandomPasswordGenerator {
// 사용 가능한 문자집합 정의 (대문자, 소문자, 숫자, 특수문자)
private static final String UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static final String LOWERCASE = "abcdefghijklmnopqrstuvwxyz";
private static final String DIGITS = "0123456789";
private static final String SPECIAL_CHARACTERS = "!@#$%^&*()_+[]{}|;:,.<>?";
private static final String ALL_CHARACTERS = UPPERCASE + LOWERCASE + DIGITS + SPECIAL_CHARACTERS;
public static String generatePassword(int length) {
// SecureRandom은 일반 Random보다 보안성이 높은 난수를 생성함.
SecureRandom random = new SecureRandom();
StringBuilder password = new StringBuilder();
// 최소 1개씩 포함
password.append(UPPERCASE.charAt(random.nextInt(UPPERCASE.length())));
password.append(LOWERCASE.charAt(random.nextInt(LOWERCASE.length())));
password.append(DIGITS.charAt(random.nextInt(DIGITS.length())));
password.append(SPECIAL_CHARACTERS.charAt(random.nextInt(SPECIAL_CHARACTERS.length())));
// 나머지 랜덤 채우기
for (int i = 4; i < length; i++) {
password.append(ALL_CHARACTERS.charAt(random.nextInt(ALL_CHARACTERS.length())));
}
// 문자열 섞기 (랜덤 정렬)
char[] passwordArray = password.toString().toCharArray();
for (int i = passwordArray.length - 1; i > 0; i--) {
int j = random.nextInt(i + 1);
char temp = passwordArray[i];
passwordArray[i] = passwordArray[j];
passwordArray[j] = temp;
}
return new String(passwordArray);
}
public static void main(String[] args) {
String password = generatePassword(12);
System.out.println("랜덤 비밀번호: " + password);
}
}
출력 예시
랜덤 비밀번호: G8!mZb@9QxLp
설명
- SecureRandom을 사용하여 보안성이 높은 랜덤 문자열 생성.
- 대문자, 소문자, 숫자, 특수문자를 최소 1개 이상 포함.
- 비밀번호를 섞어서 패턴을 없애고 더 강력한 보안 제공.
- 비밀번호 길이는 generatePassword(int length)를 통해 조정 가능.
반응형
'IT > Java' 카테고리의 다른 글
[Java] 로또 번호 생성하기 (1) | 2025.03.22 |
---|---|
[Java] 중복되지 않는 난수 생성하기 (0) | 2025.03.20 |
[Java] 4자리 수 난수 생성하기 (0) | 2025.03.19 |
[Java] Random 클래스의 시드(Seed)란 (0) | 2025.03.18 |
[Java] Random 클래스 주요 메소드 및 사용법 (0) | 2025.03.17 |
Comments