> Java > java지도 시간 > 본문

자바 키스토어

王林
풀어 주다: 2024-08-30 15:39:24
원래의
568명이 탐색했습니다.

Keystore는 Java의 데이터베이스입니다. 이를 통해 데이터를 주요 형식으로 저장할 수 있습니다. 키 저장소는 Java 클래스 java.security.KeyStore 클래스에서 확장되므로 디스크에 keyStore를 작성하고 디스크 자체에서 읽을 수 있습니다. Java에서 키 저장소를 사용하는 주요 이점은 비밀번호를 사용하여 보호 형태로 데이터를 저장하는 기능이 있으므로 데이터를 보호할 수 있다는 것입니다. 이러한 종류의 저장 기능은 암호화 및 암호 해독 메커니즘을 구현해야 하는 경우를 처리하는 데 가장 적합하기 때문에 이러한 비밀번호는 비밀번호입니다.

무료 소프트웨어 개발 과정 시작

웹 개발, 프로그래밍 언어, 소프트웨어 테스팅 등

Java에서 KeyStore를 만드는 방법은 무엇입니까?

키 저장소를 만들기 전에 해당 유형을 이해해야 합니다. 사용할 수 있는 몇 가지 키 메커니즘이 있습니다. keyStore에는 공개 키(이 키에는 일반적으로 공개 관련 인증서가 포함되어 있음), 개인 및 공개(비대칭 유형의 암호화에 사용됨)가 있습니다. Java의 getInstance() 메소드를 사용하여 Java에서 Keystore를 생성할 수 있습니다. 이 메소드는 메인 클래스에 정의되어 있고 우리가 초과한 내장 메소드입니다. 다음은 Java에서 기본 KeyStore 유형을 생성하는 예입니다. 함수에 매개변수를 전달하지 않기 때문에 기본값으로 말하고 있습니다. 사용자 정의 키 저장소를 생성하려면 필수 키 저장소 유형에 대한 메서드의 인수를 전달할 수 있습니다.

KeyStore customKeyStore = KeyStore.getInstance(custom-format);
로그인 후 복사

여기서 custom-format = PKCS12를 전달할 수 있습니다

참고: PKCS12(공개 키이며 암호화 표준)는 서버의 인증서를 저장하는 형식을 정의합니다. 또한 개인 키를 암호화 가능한 단일 파일에 저장할 수도 있습니다.

아래는 getInstance() 메소드를 이용하여 스토어를 생성하는 예입니다.

코드:

import java.io.FileInputStream;
import java.security.KeyStore;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class KeyCreate {
public static void main(String args[]) throws Exception {
//Creation of Keystore
KeyStore ks = KeyStore.getInstance("JCEKS");
System.out.println("Key Store Created");
}
}
로그인 후 복사

출력:

자바 키스토어

Java에서 KeyStore를 로드하는 방법은 무엇입니까?

여기서 Keystore의 로딩 섹션에 대해 이야기한다면 로딩은 키 스토어의 중요한 메커니즘입니다. 필요할 때만 로드해야 하므로 이 작업을 수행하는 동안 주의해야 합니다. Keystore를 로드하지 않으면 사용할 수 없기 때문에 로드가 중요합니다. 빈 데이터로 키 저장소를 로드하는 것도 가능합니다. 일반적으로 모든 파일이나 다른 저장소에서 키 저장소를 로드할 수 있습니다. load()라는 메서드가 있습니다. 이 메서드는 데이터를 로드하는 작업을 수행합니다. 로드 메소드에 두 가지 속성을 전달할 수 있습니다. 속성은

  • InputStream: 이는 데이터를 읽을 입력 스트림입니다. 스트림은 모든 파일이나 다른 소스에서 가져올 수 있습니다.
  • Char []: 이 섹션은 보안을 위한 것입니다. 여기에서 암호화를 위한 KeyStore 비밀번호 문자열을 전달할 수 있습니다.

KeyStore.load(dataStream, 비밀번호)를 로드하는 기본 흐름을 이해해 보겠습니다. 여기서는 inputStream을 dataStream으로, 임의의 문자열을 비밀번호로 사용할 수 있습니다. 앞서 언급한 대로 KyeStore에 대한 빈 데이터를 로드할 수도 있습니다. 이는 KeyStore.load(null, Keystore 비밀번호)와 같이 keyStore의 dataStream에 대해 null 값을 전달하여 수행할 수 있습니다. null을 데이터 스트림으로 전달하면 null 값을 사용하고 빈 키 저장소가 생성됩니다. 키 저장소에 대한 중요한 점은 키 저장소를 로드하지 않으면 호출하는 모든 메서드에 대해 예외가 발생한다는 것입니다. 더 나은 코딩 연습을 위해서도 사용하기 전에 keyStore를 로드하는 것이 매우 중요합니다.

아래 예에서는 null 값이 있는 키 저장소를 로드합니다.

코드:

import java.io.FileInputStream;
import java.security.KeyStore;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class KeyLoad {
public static void main(String args[]) throws Exception {
//Creation of Keystore
KeyStore ks = KeyStore.getInstance("JCEKS");
ks.load(null);
System.out.println("Loading of an empty Keystore done");
}
}
로그인 후 복사

출력:

자바 키스토어

Java에서 KeyStore를 어떻게 저장하나요?

Java에서 KeyStore를 로드하고 생성하는 것에 대해 많은 논의가 있었습니다. 이제 저장에 집중하겠습니다. 여기서 저장이란 향후 사용을 위해 저장하려는 데이터를 의미하므로 선택에 따라 데이터베이스나 디스크 등 어디에서나 저장을 수행할 수 있습니다. KeyStore에 데이터를 저장하는 역할을 하는 store라는 메서드가 있습니다. KeyStore store() 메서드에 두 가지 속성을 전달할 수 있습니다. 다음은 이에 대한 간단한 구문 예입니다.

구문

keyStore.store(streamOfOutputData ,password);
로그인 후 복사

여기서 streamOfOutputData 스트림은 모든 경로 및 파일에서 데이터를 읽을 수 있으며 비밀번호는 저장된 데이터를 암호화하기 위한 문자열 비밀번호입니다. 나중에 저장한 데이터가 필요한 경우 다시 로드하여 저장된 장소에서 해당 데이터를 검색할 수 있습니다.

코드:

import java.io.FileInputStream;
import java.security.KeyStore;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class KeyStoreExample {
public static void main(String args[]) throws Exception {
//Creation of Keystore
KeyStore ks = KeyStore.getInstance("JCEKS");
//Loading the KeyStore object
char[] ps = "ranjan".toCharArray();
String filePath = "./cacerts";
java.io.FileInputStream streamInput = new FileInputStream(filePath);
ks.load(null);
KeyStore.ProtectionParameter pp = new KeyStore.PasswordProtection(ps);
//Here we are creating an secret object
SecretKey ms = new SecretKeySpec("anypassword".getBytes(), "DSA");
//Creating SecretKeyEntry object
KeyStore.SecretKeyEntry ske = new KeyStore.SecretKeyEntry(ms);
ks.setEntry("secretKeyAlias", ske, pp);
//Storing the object
java.io.FileOutputStream storeData = null;
storeData = new java.io.FileOutputStream("nameOfNewKey");
ks.store(storeData, ps);
System.out.println("data stored");
}
}
로그인 후 복사

출력:

자바 키스토어

How to Get and Set Keys?

We can use two methods called getKey and setKey to get and set the keys. These methods are part of the KeyStore in Java. The method getEntry will allow us to get the value stored. Note that we have stored the value on the key with a password, so we need to pass the alias name of the key and the password used for storing the key. Similarly, we have a method called setKeyEntry.After getting the value from the keyStore again, we can access the data with various available methods like getPrivateKey(),getcertificate(),getPrivateKey(), and getCertificateChain(). These methods can be used to get the data according to our requirements from the KeyStore.

Example

In the example below, we check if the key is available from any KeyStore.

Code:

import java.security.*;
import java.security.cert.*;
import java.util.*;
import java.io.*;
public class SetAndGetKey {
public static void main(String[] argv)
{
try {
KeyStore store = KeyStore.getInstance("JCEKS");
store.load(null);
Boolean status
= store.isKeyEntry("test");
if (status)
System.out.println("The key available");
else
System.out.println("The key is not available");
}
catch (NoSuchAlgorithmException e) {
//catch code to handle exception
}
catch (NullPointerException e) {
//catch code to handle exception
}
catch (KeyStoreException e) {
//catch code to handle exception
}
catch (FileNotFoundException e) {
//catch code to handle exception
}
catch (IOException e) {
//catch code to handle exception
}
catch (CertificateException e) {
//catch code to handle exception
}
}
}
로그인 후 복사

Output:

자바 키스토어

Java KeyStore Methods

To perform various operations on the KeyStore, we have various methods below.

  • load(inputStream, password): It will load the keyStore data, and it needs two parameters, one as the input stream(file or any disk data) and password of string
  • store(outputStream, password): This method will be used for storing the data, and it will take two params one is output stream which from where data is going to read it could be file or disk and the second parameter is the password which will encrypt the data which we are storing.
  • getInstance(): This method is used to create a keyStore; if we pass nothing to this method, then it will create a default keyStore else, we can pass PKCS12 as the keyStore type.
  • getPrivateKey(): After getting keyStore, we can fetch private keys with this method.
  • getCertificate(): We can use this method to get the certificates.
  • getCertificateChain(): If we want to get a chain of certificates, we can use this method.

Conclusion

From this tutorial, we learned the basic concept of KeyStore in Java and about the creation, loading, and getting of various types of data from the Keystore data; we learned about the various available methods and their uses in Java for KeyStore.

위 내용은 자바 키스토어의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!