Hi, 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.
The Signature class ( java.security.Signature ) creates a digital signature for binary data. A digital signature is a message digest , encrypted with a private key from a private / public key pair. Anyone who owns a public key can verify a digital signature.
Before you can use the Signature class, you must create an instance of 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.
After creating a Signature instance, you need to initialize it before you start using it. A 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 private / public key pair and the SecureRandom instance.
When the Signature instance is initialized, you can use it to create digital signatures. The digital signature is created by calling the update () method (one or more times) and ending with the sign () call. An example of creating a digital signature for binary data:
byte[] data = "abcdefghijklmnopqrstuvxyz".getBytes("UTF-8"); signature.update(data); byte[] digitalSignature = signature.sign();
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). Here is what the initialization of the Signature instance looks like in scan mode:
Signature signature = Signature.getInstance("SHA256WithDSA"); signature.initVerify(keyPair.getPublic());
Note that the Signature instance is now initialized in check 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);
Source: https://habr.com/ru/post/445330/
All Articles