Secret Key and String Conversion in Java – Java中的密匙和字符串转换

最后修改: 2021年 5月 30日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In a real-life scenario, we come across several situations where we need encryption and decryption for security purposes. We can achieve this easily using a secret key. So for encrypting and decrypting a secret key, we have to know the way of converting the secret keys to string and vice-versa. In this tutorial, we’ll see the secret key and String conversion in Java. Also, we’ll go through different ways of creating Secret Key in Java with examples.

在现实生活中,我们会遇到一些情况,需要为安全目的进行加密和解密。我们可以使用密匙轻松实现这一目的。因此,为了加密和解密秘密密钥,我们必须知道将秘密密钥转换为字符串的方法,反之亦然。在本教程中,我们将看到Java中的秘钥和String转换。此外,我们还将通过实例来了解在Java中创建秘钥的不同方法。

2. Secret Key

2.秘密钥匙

A secret key is the piece of information or parameter that is used to encrypt and decrypt messages.  In Java, we have SecretKey an interface that defines it as a secret (symmetric) key. The purpose of this interface is to group (and provide type safety for) all secret key interfaces.

秘钥是用于加密和解密信息的信息或参数。 在Java中,我们有SecretKey一个接口,将其定义为一个秘密(对称)密钥。这个接口的目的是将所有的秘钥接口分组(并为其提供类型安全)。

There are two ways for generating a secret key in Java: generating from a random number or deriving from a given password.

在Java中,有两种生成秘钥的方法:从随机数中生成或从给定的密码中导出。

In the first approach, the secret key is generated from a Cryptographically Secure (Pseudo-)Random Number Generator like the SecureRandom class.

在第一种方法中,秘密密钥是由类似SecureRandom类的加密安全(伪)随机数发生器生成的。

For generating a secret key, we can use the KeyGenerator class. Let’s define a method for generating a SecretKey — the parameter n specifies the length (128, 192, or 256) of the key in bits:

为了生成一个密匙,我们可以使用KeyGenerator类。让我们定义一个生成SecretKey的方法–参数n指定密钥的长度(128,192,或256),单位为比特。

public static SecretKey generateKey(int n) throws NoSuchAlgorithmException {
    KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
    keyGenerator.init(n);
    SecretKey originalKey = keyGenerator.generateKey();
    return originalKey;
}

In the second approach, the secret key is derived from a given password using a password-based key derivation function like PBKDF2. We also need a salt value for turning a password into a secret key. The salt is also a random value.

在第二种方法中,秘密密钥是使用基于密码的密钥推导函数(如PBKDF2)从给定的密码推导出来的。我们还需要一个盐值来把密码变成秘钥。该盐值也是一个随机值。

We can use the SecretKeyFactory class with the PBKDF2WithHmacSHA256 algorithm for generating a key from a given password.

我们可以使用SecretKeyFactory类和PBKDF2WithHmacSHA256算法来从给定的密码生成一个密钥。

Let’s define a method for generating the SecretKey from a given password with 65,536 iterations and a key length of 256 bits:

让我们定义一个方法,从一个给定的密码生成SecretKey,迭代65,536次,密钥长度为256位。

public static SecretKey getKeyFromPassword(String password, String salt)
  throws NoSuchAlgorithmException, InvalidKeySpecException {
    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
    KeySpec spec = new PBEKeySpec(password.toCharArray(), salt.getBytes(), 65536, 256);
    SecretKey originalKey = new SecretKeySpec(factory.generateSecret(spec).getEncoded(), "AES");
    return originalKey;
}

3. SecretKey and String Conversion

3.秘钥和字符串转换

3.1. SecretKey to String

3.1.SecretKeyString

We’ll convert the SecretKey into a byte array. Then, we’ll convert the byte array into String using Base64 encoding:

我们将把SecretKey转换成一个byte数组。然后,我们将使用Base64编码将byte数组转换为String

public static String convertSecretKeyToString(SecretKey secretKey) throws NoSuchAlgorithmException {
    byte[] rawData = secretKey.getEncoded();
    String encodedKey = Base64.getEncoder().encodeToString(rawData);
    return encodedKey;
}

3.2. String to SecretKey

3.2.StringSecretKey

We’ll convert the encoded String key into a byte array using Base64 decoding. Then, using SecretKeySpecs, we’ll convert the byte array into the SecretKey:

我们将使用Base64解码将编码后的String密钥转换成byte数组。然后,使用SecretKeySpecs,我们将把byte阵列转换成SecretKey

public static SecretKey convertStringToSecretKeyto(String encodedKey) {
    byte[] decodedKey = Base64.getDecoder().decode(encodedKey);
    SecretKey originalKey = new SecretKeySpec(decodedKey, 0, decodedKey.length, "AES");
    return originalKey;
}

Let’s verify the conversion quickly:

让我们快速验证一下这个转换。

SecretKey encodedKey = ConversionClassUtil.getKeyFromPassword("Baeldung@2021", "@$#baelDunG@#^$*");
String encodedString = ConversionClassUtil.convertSecretKeyToString(encodedKey);
SecretKey decodeKey = ConversionClassUtil.convertStringToSecretKeyto(encodedString);
Assertions.assertEquals(encodedKey, decodeKey);

4. Conclusion

4.总结

In summary, we’ve learned how to convert a SecretKey into String and vice versa in Java. Additionally, we’ve discussed various ways of creating SecretKey in Java.

综上所述,我们已经学会了如何在Java中把SecretKey转换成String,反之亦然。此外,我们还讨论了在Java中创建SecretKey的各种方法。

As always, the full source code of the article is available over on GitHub.

一如既往,文章的完整源代码可在GitHub上获得