Cryptography in Java. Signature class
- Transfer
Hello, Habr! I present to you the translation of the fifth article "Java Signature" by Jakob Jenkov from a series of articles for beginners who want to learn the basics of cryptography in Java.
Table of contents:
- Java cryptography
- Java cipher
- Messagedigest
- Mac
- Signature
- Keypair
- Keygenerator
- KeyPairGenerator
- Keystore
- Keytool
- Certificate
- CertificateFactory
- CertPath
Java Signature
The Signature class ( java.security.Signature ) creates a digital signature for binary data. A digital signature is a message digest encrypted with the private key of a private / public key pair. Anyone who owns the public key can verify the digital signature.
Create a signature instance
Before you can use the Signature class, you must instantiate this class by calling the static getInstance () method . Below is an example in which a Signature instance is created:
Signature signature = Signature.getInstance("SHA256WithDSA");
The string parameter passed to the getInstance () method determines the digital signature encryption algorithm used.
Signature Instance Initialization
After creating the Signature instance, you need to initialize it before you start using it. The Signature instance is initialized by calling its init () method . An example of initializing a Java signature instance:
SecureRandom secureRandom = new SecureRandom();
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("DSA");
KeyPair keyPair = keyPairGenerator.generateKeyPair();
signature.initSign(keyPair.getPrivate(), secureRandom);
As you can see, the Signature instance is initialized with the private key of the secret / public key pair and the SecureRandom instance.
Digital Signature Creation
When the Signature instance is initialized, you can use it to create digital signatures. A digital signature is created by calling the update () method (one or more times) and ending with a call to sign () . Example of creating a digital signature for binary data:
byte[] data = "abcdefghijklmnopqrstuvxyz".getBytes("UTF-8");
signature.update(data);
byte[] digitalSignature = signature.sign();
Digital Signature Verification
If you want to verify a digital signature created by someone else, you must initialize the signature instance in verification mode (instead of signature mode). This is how initializing a Signature instance in validation mode looks like:
Signature signature = Signature.getInstance("SHA256WithDSA");
signature.initVerify(keyPair.getPublic());
Note that the Signature instance is now initialized in verification mode, passing the public key of the key pair as a parameter. After initialization in verification mode, you can use the Signature instance to verify the digital signature:
byte[] data2 = "abcdefghijklmnopqrstuvxyz".getBytes("UTF-8");
signature2.update(data2);
boolean verified = signature2.verify(digitalSignature);