首页 > Java > java教程 > 正文

Java 密钥库

王林
发布: 2024-08-30 15:39:24
原创
568 人浏览过

Keystore是Java中的数据库;它允许我们以关键格式存储数据; Keystore扩展自Java类java.security.KeyStore类,我们可以将keyStore写入磁盘并从磁盘本身读取;在 Java 中使用密钥库的主要好处是它允许我们保护数据,因为它具有以密码保护的形式存储数据的功能。这些密码就是他们的密码,因为这种存储功能最适合处理我们需要实现加密和解密机制的情况。

开始您的免费软件开发课程

网络开发、编程语言、软件测试及其他

如何在 Java 中创建密钥库?

在创建Keystore之前,我们需要了解它的类型;有一些可用的密钥机制 keyStore 是公钥(此密钥通常包含公开的关联证书)、私有和公开(用于任何非对称类型的加密)。我们可以使用Java的getInstance()方法来创建Java中的Keystore。该方法是主类中定义的内置方法,我们已经超出了该方法。下面是在 Java 中创建默认 KeyStore 类型的示例。我之所以说它是默认值,是因为我们没有在函数中传递任何参数。如果我们想创建任何自定义 keyStore,我们可以在方法中传递我们所需类型的 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 密钥库

如何在 Java 中加载 KeyStore?

这里,如果我们谈论密钥库的加载部分,加载是密钥库的一个重要机制。执行此操作时我们必须小心,因为它应该仅在需要时加载。加载很重要,因为如果不加载Keystore,我们就无法使用它。也可以使用任何空数据加载密钥库。一般来说,我们可以从任何文件或任何其他存储加载密钥库。有一个方法叫load();该方法将执行加载数据的任务。我们可以将两个属性传递给 load 方法;属性是

  • InputStream: 这是将从中读取数据的输入流;流可以来自任何文件或其他来源。
  • Char []: 这部分是为了安全;这里,我们可以传递一个字符串作为KeyStore密码进行加密。

让我们了解一下加载KeyStore.load(dataStream,password)的基本流程。这里我们可以将 inputStream 作为数据流,并使用任意字符串作为密码。正如我们所提到的,我们还可以为 KyeStore 加载空数据,这可以通过为 keyStore 的 dataStream 传递任何 null 值来实现,例如 KeyStore.load(null, Keystore password)。一旦我们将 null 作为数据流传递,它将采用 null 值并为我们创建一个空的 Keystore。关于密钥库的一个重要的事情是,如果我们不加载密钥库,它将为我们调用的任何方法抛出异常。为了更好的编码实践,在开始使用 keyStore 之前加载它非常重要。

示例

在下面的示例中,我们加载具有空值的密钥库。

代码:

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 密钥库

如何在Java中存储KeyStore?

我们有很多关于在 Java 中加载和创建 KeyStore 的讨论;现在让我们专注于存储。这里的存储是指我们想要存储以供将来使用的数据,因此存储可以在任何地方进行,可以在数据库上,也可以在磁盘上,具体取决于我们的选择。我们有一个名为 store 的方法,它将起到将数据存储在 KeyStore 中的作用。我们可以将两个属性传递给 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");
}
}
登录后复制

输出:

Java 密钥库

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 密钥库

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.

以上是Java 密钥库的详细内容。更多信息请关注PHP中文网其他相关文章!

相关标签:
来源:php
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!