- Криптография в Java. Класс KeyPair
- Оглавление:
- Ключевая пара
- Доступ к открытому ключу
- Доступ к закрытому ключу
- Генератор ключей
- Создание экземпляра KeyGenerator
- Инициализация KeyGenerator
- Генерация ключа
- Генератор ключевой пары
- Открытые и закрытые ключи
- Создание экземпляра KeyPairGenerator
- Инициализация KeyPairGenerator
- Генерация ключевой пары
- Java generate key pair
- Methods inherited from class java.lang.Object
- Constructor Detail
- KeyPairGenerator
- Method Detail
- getAlgorithm
- getInstance
- getInstance
- getInstance
- getProvider
- initialize
- initialize
- initialize
- initialize
- genKeyPair
- generateKeyPair
Криптография в Java. Класс KeyPair
Привет, Хабр! Представляю вашему вниманию перевод 6, 7 и 8 статей автора Jakob Jenkov из серии статей для начинающих, желающих освоить основы криптографии в Java.
Оглавление:
Ключевая пара
Класс KeyPair (java.security.KeyPair) представляет собой пару асимметричных ключей (открытый ключ + закрытый ключ). Экземпляр KeyPair обычно используется в асимметричной криптографии(шифрование или подпись данных). Обычно экземпляр KeyPair получают из хранилища ключей Java или KeyPairGenerator который будет рассмотрен далее в этой статье.
Доступ к открытому ключу
Вы можете получить доступ к открытому ключу экземпляра KeyPair, вызвав его метод getPublic(). Пример получения открытого ключа:
PublicKey publicKey = keyPair.getPublic();
Доступ к закрытому ключу
Так же можно получить доступ к закрытому ключу экземпляра KeyPair, вызвав его метод getPrivate(). Вот пример получения закрытого ключа:
PrivateKey privateKey = keyPair.getPrivate();
Генератор ключей
Класс KeyGenerator (javax.crypto.KeyGenerator) используется для генерации симметричных ключей шифрования. Симметричный ключ шифрования — это ключ, который используется для шифрования и дешифрования данных алгоритмом симметричного шифрования.
Создание экземпляра KeyGenerator
Прежде чем вы сможете использовать класс KeyGenerator, вы должны создать экземпляр KeyGenerator. Экземпляр KeyGenerator создается вызывом статического метода getInstance(), в качестве параметра принимающего имя алгоритма шифрования, для которого создается ключ. Вот пример создания экземпляра KeyGenerator:
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
В этом примере создается экземпляр KeyGenerator, который может генерировать ключи для алгоритма шифрования AES.
Инициализация KeyGenerator
После создания экземпляра KeyGenerator его необходимо инициализировать. Инициализация экземпляра выполняется путем вызова метода init(). Пример инициализации экземпляра KeyGenerator:
SecureRandom secureRandom = new SecureRandom(); int keyBitSize = 256; keyGenerator.init(keyBitSize, secureRandom);
Метод init() принимает два параметра: длина ключа и SecureRandom, который используется во время генерации ключа.
Генерация ключа
После инициализации экземпляра KeyGenerator вы можете использовать его для генерации ключей. Генерация ключа выполняется путем вызова метода generateKey(). Вот пример генерации симметричного ключа:
SecretKey secretKey = keyGenerator.generateKey();
Генератор ключевой пары
Класс KeyPairGenerator (java.security.KeyPairGenerator) используется для генерации асимметричных ключевых пар. Пара асимметричных ключей состоит из двух ключей: первый ключ обычно используется для шифрования данных, а второй ключ используется для расшифровки данных, зашифрованных с помощью первого ключа.
Открытые и закрытые ключи
Наиболее известным типом пары асимметричных ключей является тип пары ключей вида: открытый ключ + закрытый ключ. Закрытый ключ используется для шифрования данных, а открытый ключ — для расшифровки данных. На самом деле, вы также можете зашифровать данные с помощью открытого ключа и расшифровать его с помощью закрытого ключа. Закрытый ключ обычно хранится в секрете, а открытый ключ может быть известен всем. Таким образом, если Джек зашифровывает некоторые данные своим закрытым ключом, каждый, кто владеет открытым ключом Джека, может расшифровать его.
Создание экземпляра KeyPairGenerator
Чтобы использовать KeyPairGenerator, вы должны сначала создать экземпляр класса KeyPairGenerator. Создание экземпляра KeyPairGenerator выполняется путем вызова метода getInstance(). Вот пример создания экземпляра:
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
Метод getInstance() принимает имя алгоритма шифрования, который будет использоваться. В этом примере мы используем алгоритм RSA.
Инициализация KeyPairGenerator
В зависимости от алгоритма, вам может потребоваться инициализация экземпляра KeyPairGenerator. Инициализация KeyPairGenerator выполняется путем вызова его метода initialize(). Пример инициализации экземпляра KeyPairGenerator:
keyPairGenerator.initialize(2048);
В этом примере инициализируется KeyPairGenerator для генерации ключей размером 2048 бит.
Генерация ключевой пары
Чтобы сгенерировать ключевую пару с помощью KeyPairGenerator вызывается метод generateKeyPair(). Вот пример генерации ключевой пары:
KeyPair keyPair = keyPairGenerator.generateKeyPair();
Java generate key pair
Returns a KeyPairGenerator object that generates public/private key pairs for the specified algorithm.
Returns a KeyPairGenerator object that generates public/private key pairs for the specified algorithm.
Returns a KeyPairGenerator object that generates public/private key pairs for the specified algorithm.
Initializes the key pair generator using the specified parameter set and the SecureRandom implementation of the highest-priority installed provider as the source of randomness.
Initializes the key pair generator for a certain keysize using a default parameter set and the SecureRandom implementation of the highest-priority installed provider as the source of randomness.
Initializes the key pair generator for a certain keysize with the given source of randomness (and a default parameter set).
Methods inherited from class java.lang.Object
Constructor Detail
KeyPairGenerator
Method Detail
getAlgorithm
Returns the standard name of the algorithm for this key pair generator. See the KeyPairGenerator section in the Java Cryptography Architecture Standard Algorithm Name Documentation for information about standard algorithm names.
getInstance
public static KeyPairGenerator getInstance(String algorithm) throws NoSuchAlgorithmException
Returns a KeyPairGenerator object that generates public/private key pairs for the specified algorithm. This method traverses the list of registered security Providers, starting with the most preferred Provider. A new KeyPairGenerator object encapsulating the KeyPairGeneratorSpi implementation from the first Provider that supports the specified algorithm is returned. Note that the list of registered providers may be retrieved via the Security.getProviders() method.
getInstance
public static KeyPairGenerator getInstance(String algorithm, String provider) throws NoSuchAlgorithmException, NoSuchProviderException
Returns a KeyPairGenerator object that generates public/private key pairs for the specified algorithm. A new KeyPairGenerator object encapsulating the KeyPairGeneratorSpi implementation from the specified provider is returned. The specified provider must be registered in the security provider list. Note that the list of registered providers may be retrieved via the Security.getProviders() method.
getInstance
public static KeyPairGenerator getInstance(String algorithm, Provider provider) throws NoSuchAlgorithmException
Returns a KeyPairGenerator object that generates public/private key pairs for the specified algorithm. A new KeyPairGenerator object encapsulating the KeyPairGeneratorSpi implementation from the specified Provider object is returned. Note that the specified Provider object does not have to be registered in the provider list.
getProvider
initialize
public void initialize(int keysize)
Initializes the key pair generator for a certain keysize using a default parameter set and the SecureRandom implementation of the highest-priority installed provider as the source of randomness. (If none of the installed providers supply an implementation of SecureRandom , a system-provided source of randomness is used.)
initialize
Initializes the key pair generator for a certain keysize with the given source of randomness (and a default parameter set).
initialize
public void initialize(AlgorithmParameterSpec params) throws InvalidAlgorithmParameterException
Initializes the key pair generator using the specified parameter set and the SecureRandom implementation of the highest-priority installed provider as the source of randomness. (If none of the installed providers supply an implementation of SecureRandom , a system-provided source of randomness is used.). This concrete method has been added to this previously-defined abstract class. This method calls the KeyPairGeneratorSpi initialize method, passing it params and a source of randomness (obtained from the highest-priority installed provider or system-provided if none of the installed providers supply one). That initialize method always throws an UnsupportedOperationException if it is not overridden by the provider.
initialize
public void initialize(AlgorithmParameterSpec params, SecureRandom random) throws InvalidAlgorithmParameterException
Initializes the key pair generator with the given parameter set and source of randomness. This concrete method has been added to this previously-defined abstract class. This method calls the KeyPairGeneratorSpi initialize method, passing it params and random . That initialize method always throws an UnsupportedOperationException if it is not overridden by the provider.
genKeyPair
Generates a key pair. If this KeyPairGenerator has not been initialized explicitly, provider-specific defaults will be used for the size and other (algorithm-specific) values of the generated keys. This will generate a new key pair every time it is called. This method is functionally equivalent to generateKeyPair .
generateKeyPair
Generates a key pair. If this KeyPairGenerator has not been initialized explicitly, provider-specific defaults will be used for the size and other (algorithm-specific) values of the generated keys. This will generate a new key pair every time it is called. This method is functionally equivalent to genKeyPair .
Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
Copyright © 1993, 2023, Oracle and/or its affiliates. All rights reserved. Use is subject to license terms. Also see the documentation redistribution policy.