File signing in java

How to create a digital signature and sign data?

In the following code snippet you will learn how to generate a digital signature to sign a data or file. To create a signature we will need a key pair of public and private key. But for the signing process we’ll only use the private key, while the public key will be used to verify the signature.

To create a digital signature we need an instance of java.security.Signature . To get one we can call the Signature.getInstance() method and pass the algorithm and the provider arguments. In this code snippet we’ll use SHA1withDSA and SUN for the algorithm and provider.

But before we can use the Signature object we have to initialize it first with a PrivateKey . You can also see how to get a private key in the code snippet below. To initialize call the Signature ‘s initSign() method.

And finally to generate the digital signature we need to update the Signature using the data that we are going to sign. To do this we read the file into byte[] using the helps of Files.readAllBytes() and supply the bytes into the Signature object using the update() method. To get the signature we call the sign() method which will return us a byte array of the signature.

And here is the complete code snippet:

package org.kodejava.security; import java.nio.file.Files; import java.nio.file.Paths; import java.security.*; public class GenerateDigitalSignature < public static void main(String[] args) < try < // Get instance and initialize a KeyPairGenerator object. KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA", "SUN"); SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN"); keyGen.initialize(1024, random); // Get a PrivateKey from the generated key pair. KeyPair keyPair = keyGen.generateKeyPair(); PrivateKey privateKey = keyPair.getPrivate(); // Get an instance of Signature object and initialize it. Signature signature = Signature.getInstance("SHA1withDSA", "SUN"); signature.initSign(privateKey); // Supply the data to be signed to the Signature object // using the update() method and generate the digital // signature. byte[] bytes = Files.readAllBytes(Paths.get("README.md")); signature.update(bytes); byte[] digitalSignature = signature.sign(); // Save digital signature and the public key to a file. Files.write(Paths.get("signature"), digitalSignature); Files.write(Paths.get("publickey"), keyPair.getPublic().getEncoded()); >catch (Exception e) < e.printStackTrace(); >> > 

On the next examples we are going to verify the digital signature. To verify the digital signature is to make sure that the data was sent by the original creator without any modification. To verify we’ll need the digital signature and the public key of the key pair. To get these in the code snippet above we have saved both the digital signature and the public key to files.

A programmer, recreational runner and diver, live in the island of Bali, Indonesia. Programming in Java, Spring, Hibernate / JPA. You can support me working on this project, buy me a cup of coffee ☕ every little bit helps, thank you 🙏

Читайте также:  Sort objects in collection java

Источник

Understanding Signing and Verification

The Java™ platform enables you to digitally sign JAR files. You digitally sign a file for the same reason you might sign a paper document with pen and ink — to let readers know that you wrote the document, or at least that the document has your approval.

When you sign a letter, for example, everyone who recognizes your signature can confirm that you wrote the letter. Similarly when you digitally sign a file, anyone who «recognizes» your digital signature knows that the file came from you. The process of «recognizing» electronic signatures is called verification.

When the JAR file is signed, you also have the option of time stamping the signature. Similar to putting a date on a paper document, time stamping the signature identifies when the JAR file was signed. The time stamp can be used to verify that the certificate used to sign the JAR file was valid at the time of signing.

The ability to sign and verify files is an important part of the Java platform’s security architecture. Security is controlled by the security policy that’s in force at runtime. You can configure the policy to grant security privileges to applets and to applications. For example, you could grant permission to an applet to perform normally forbidden operations such as reading and writing local files or running local executable programs. If you have downloaded some code that’s signed by a trusted entity, you can use that fact as a criterion in deciding which security permissions to assign to the code.

Once you (or your browser) have verified that an applet is from a trusted source, you can have the platform relax security restrictions to let the applet perform operations that would ordinarily be forbidden. A trusted applet can have freedoms as specified by the policy file in force.

The Java platform enables signing and verification by using special numbers called public and private keys. Public keys and private keys come in pairs, and they play complementary roles.

The private key is the electronic «pen» with which you can sign a file. As its name implies, your private key is known only to you so that no one else can «forge» your signature. A file signed with your private key can be verified only by the corresponding public key.

Public and private keys alone, however, aren’t enough to truly verify a signature. Even if you’ve verified that a signed file contains a matching key pair, you still need some way to confirm that the public key actually comes from the signer that it purports to come from.

One more element, therefore, is required to make signing and verification work. That additional element is the certificate that the signer includes in a signed JAR file. A certificate is a digitally signed statement from a recognized certification authority that indicates who owns a particular public key. Certification authorities are entities (typically firms specializing in digital security) that are trusted throughout the industry to sign and issue certificates for keys and their owners. In the case of signed JAR files, the certificate indicates who owns the public key contained in the JAR file.

Читайте также:  This in javascript w3schools

When you sign a JAR file your public key is placed inside the archive along with an associated certificate so that it’s easily available for use by anyone wanting to verify your signature.

To summarize digital signing:

  • The signer signs the JAR file using a private key.
  • The corresponding public key is placed in the JAR file, together with its certificate, so that it is available for use by anyone who wants to verify the signature.

Digests and the Signature File

When you sign a JAR file, each file in the archive is given a digest entry in the archive’s manifest. Here’s an example of what such an entry might look like:

Name: test/classes/ClassOne.class SHA1-Digest: TD1GZt8G11dXY2p4olSZPc5Rj64=

The digest values are hashes or encoded representations of the contents of the files as they were at the time of signing. A file’s digest will change if and only if the file itself changes.

When a JAR file is signed, a signature file is automatically generated and placed in the JAR file’s META-INF directory, the same directory that contains the archive’s manifest. Signature files have filenames with an .SF extension. Here is an example of the contents of a signature file:

Signature-Version: 1.0 SHA1-Digest-Manifest: h1yS+K9T7DyHtZrtI+LxvgqaMYM= Created-By: 1.7.0_06 (Oracle Corporation) Name: test/classes/ClassOne.class SHA1-Digest: fcav7ShIG6i86xPepmitOVo4vWY= Name: test/classes/ClassTwo.class SHA1-Digest: xrQem9snnPhLySDiZyclMlsFdtM= Name: test/images/ImageOne.gif SHA1-Digest: kdHbE7kL9ZHLgK7akHttYV4XIa0= Name: test/images/ImageTwo.gif SHA1-Digest: mF0D5zpk68R4oaxEqoS9Q7nhm60=

As you can see, the signature file contains digest entries for the archive’s files that look similar to the digest-value entries in the manifest. However, while the digest values in the manifest are computed from the files themselves, the digest values in the signature file are computed from the corresponding entries in the manifest. Signature files also contain a digest value for the entire manifest (see the SHA1-Digest-Manifest header in the above example).

When a signed JAR file is being verified, the digests of each of its files are re-computed and compared with the digests recorded in the manifest to ensure that the contents of the JAR file haven’t changed since it was signed. As an additional check, digest values for the manifest file itself are re-computed and compared against the values recorded in the signature file.

You can read additional information about signature files on the Manifest Format page of the JDK™ documentation.

The Signature Block File

In addition to the signature file, a signature block file is automatically placed in the META-INF directory when a JAR file is signed. Unlike the manifest file or the signature file, signature block files are not human-readable.

The signature block file contains two elements essential for verification:

  • The digital signature for the JAR file that was generated with the signer’s private key
  • The certificate containing the signer’s public key, to be used by anyone wanting to verify the signed JAR file

Signature block filenames typically will have a .DSA extension indicating that they were created by the default Digital Signature Algorithm. Other filename extensions are possible if keys associated with some other standard algorithm are used for signing.

Читайте также:  Php trim to null

For additional information about keys, certificates, and certification authorities, see

For more information about the Java platform’s security architecture, see this related documentation:

Источник

Sign Documents with Digital Signatures using Java

Sign Documents with Digital Signatures using Java

A digital signature is a mathematical technique to verify the document’s authenticity. For documents, the digital signature is represented by certificate with private and public keys. As a Java developer, you can easily sign your documents with digital certificates programmatically. This article will be focusing on how to electronically sign documents with digital signatures using Java.

The following topics are discussed/covered in this article:

Java API for Signing Documents#

I will be using GroupDocs.Signature for Java API for signing documents with the digital certificate. It helps you develop Java applications to electronically sign digital documents of supported formats. It also allows signing images and documents with Image, QR-Code, Barcode, Metadata, Text & Stamp Type electronic signatures.

Download and Configure#

You can download the JAR of the API or just add the following pom.xml configuration in your Maven-based Java applications to try the below-mentioned code examples.

 GroupDocsJavaAPI GroupDocs Java API http://repository.groupdocs.com/repo/  
 com.groupdocs groupdocs-signature 20.9  

Sign PDF Documents with Digital Signatures using Java#

You can electronically sign your PDF documents with digital signatures by following the simple steps mentioned below:

  • Create an instance of the Signature class
  • Provide path of the PDF document
  • Create an instance of the DigitalSignOptions class
  • Provide the certificate file path
  • Set the image file path
  • Set required sign options such as position (Top, Left etc.)
  • Then call the Sign method to sign the document

The following code sample shows how to sign the PDF documents with the certificate using Java.

Sign PDF Document with Digital Certificate using Java

The Signature class is the main class that controls the document signing process. This class provides various methods to sign, verify, update and search signatures.

The DigitalSignOptions class provides various methods to set and get sign options to represent digital signatures.

Sign Word Documents with Digital Signatures using Java#

You can electronically sign your Word documents with digital signatures by following the simple steps mentioned below:

  • Create an instance of the Signature class
  • Provide path of the Word file
  • Create an instance of the DigitalSignOptions class
  • Provide the certificate file path
  • Set the image file path
  • Set required sign options such as position (Top, Left etc.)
  • Then call the Sign method to sign the document

The following code sample shows how to sign the DOCX file with the certificate using Java.

Sign Word documents with digital certificates using Java

Get a Free License#

You can try the API without evaluation limitations by requesting a free temporary license.

Conclusion#

In this article, you have learned how to electronically sign documents with digital signatures using Java. You can learn more about GroupDocs.Signature for Java API using the documentation. In case of any ambiguity, please feel free to contact us on the forum.

See Also#

Источник

Оцените статью