Digital signatures - chapter 1

This is a code example of iText PDF, discover more.

1st November 2015
admin-marketing

Switch code for this example

C1_01_DigestDefault.java
  1. /*
  2.  * This class is part of the white paper entitled
  3.  * "Digital Signatures for PDF documents"
  4.  * written by Bruno Lowagie
  5.  *
  6.  * For more info, go to: http://itextpdf.com/learn
  7.  */
  8. package signatures.chapter1;
  9.  
  10. import java.math.BigInteger;
  11. import java.security.GeneralSecurityException;
  12. import java.security.MessageDigest;
  13. import java.util.Arrays;
  14.  
  15. public class C1_01_DigestDefault {
  16.  
  17.     protected byte[] digest;
  18.     protected MessageDigest md;
  19.    
  20.     protected C1_01_DigestDefault(String password, String algorithm, String provider) throws GeneralSecurityException {
  21.         if (provider == null)
  22.             md = MessageDigest.getInstance(algorithm);
  23.         else
  24.             md = MessageDigest.getInstance(algorithm, provider);
  25.         digest = md.digest(password.getBytes());
  26.     }
  27.    
  28.     public static C1_01_DigestDefault getInstance(String password, String algorithm) throws GeneralSecurityException {
  29.         return new C1_01_DigestDefault(password, algorithm, null);
  30.     }
  31.    
  32.     public int getDigestSize() {
  33.         return digest.length;
  34.     }
  35.    
  36.     public String getDigestAsHexString() {
  37.         return new BigInteger(1, digest).toString(16);
  38.     }
  39.  
  40.    
  41.     public boolean checkPassword(String password) {
  42.         return Arrays.equals(digest, md.digest(password.getBytes()));
  43.     }
  44.    
  45.     public static void showTest(String algorithm) {
  46.         try {
  47.             C1_01_DigestDefault app = getInstance("password", algorithm);
  48.             System.out.println("Digest using " + algorithm + ": " + app.getDigestSize());
  49.             System.out.println("Digest: " + app.getDigestAsHexString());
  50.             System.out.println("Is the password 'password'? " + app.checkPassword("password"));
  51.             System.out.println("Is the password 'secret'? " + app.checkPassword("secret"));
  52.         } catch (GeneralSecurityException e) {
  53.             System.out.println(e.getMessage());
  54.         }
  55.     }
  56.    
  57.     public static void testAll() {
  58.         showTest("MD5");
  59.         showTest("SHA-1");
  60.         showTest("SHA-224");
  61.         showTest("SHA-256");
  62.         showTest("SHA-384");
  63.         showTest("SHA-512");
  64.         showTest("RIPEMD128");
  65.         showTest("RIPEMD160");
  66.         showTest("RIPEMD256");
  67.     }
  68.    
  69.     public static void main(String[] args) {
  70.         testAll();
  71.     }
  72. }
C1_02_DigestBC.java
  1. /*
  2.  * This class is part of the white paper entitled
  3.  * "Digital Signatures for PDF documents"
  4.  * written by Bruno Lowagie
  5.  *
  6.  * For more info, go to: http://itextpdf.com/learn
  7.  */
  8. package signatures.chapter1;
  9.  
  10. import java.security.GeneralSecurityException;
  11. import java.security.Security;
  12.  
  13. import org.bouncycastle.jce.provider.BouncyCastleProvider;
  14.  
  15. public class C1_02_DigestBC extends C1_01_DigestDefault {
  16.  
  17.     public static final BouncyCastleProvider PROVIDER = new BouncyCastleProvider();
  18.     static {
  19.         Security.addProvider(PROVIDER);
  20.     }
  21.    
  22.     protected C1_02_DigestBC(String password, String algorithm)
  23.             throws GeneralSecurityException {
  24.         super(password, algorithm, PROVIDER.getName());
  25.     }
  26.    
  27.     public static C1_01_DigestDefault getInstance(String password, String algorithm) throws GeneralSecurityException {
  28.         return new C1_02_DigestBC(password, algorithm);
  29.     }
  30.  
  31.     public static void main(String[] args) {
  32.         testAll();
  33.     }
  34. }
C1_03_EncryptDecrypt.java
  1. /*
  2.  * This class is part of the white paper entitled
  3.  * "Digital Signatures for PDF documents"
  4.  * written by Bruno Lowagie
  5.  *
  6.  * For more info, go to: http://itextpdf.com/learn
  7.  */
  8. package signatures.chapter1;
  9.  
  10. import java.io.FileInputStream;
  11. import java.io.IOException;
  12. import java.math.BigInteger;
  13. import java.security.GeneralSecurityException;
  14. import java.security.Key;
  15. import java.security.KeyStore;
  16. import java.security.KeyStoreException;
  17. import java.security.cert.X509Certificate;
  18.  
  19. import javax.crypto.Cipher;
  20.  
  21. public class C1_03_EncryptDecrypt {
  22.  
  23.     protected KeyStore ks;
  24.    
  25.     public C1_03_EncryptDecrypt(String keystore, String ks_pass) throws GeneralSecurityException, IOException {
  26.         initKeyStore(keystore, ks_pass);
  27.     }
  28.    
  29.     public void initKeyStore(String keystore, String ks_pass) throws GeneralSecurityException, IOException {
  30.         ks = KeyStore.getInstance(KeyStore.getDefaultType());
  31.         ks.load(new FileInputStream(keystore), ks_pass.toCharArray());
  32.     }
  33.    
  34.     public X509Certificate getCertificate(String alias) throws KeyStoreException {
  35.         return (X509Certificate) ks.getCertificate(alias);
  36.     }
  37.    
  38.     public Key getPublicKey(String alias) throws GeneralSecurityException, IOException {
  39.         return getCertificate(alias).getPublicKey();
  40.     }
  41.    
  42.     public Key getPrivateKey(String alias, String pk_pass) throws GeneralSecurityException, IOException {
  43.         return ks.getKey(alias, pk_pass.toCharArray());
  44.     }
  45.    
  46.     public byte[] encrypt(Key key, String message) throws GeneralSecurityException {
  47.         Cipher cipher = Cipher.getInstance("RSA");
  48.         cipher.init(Cipher.ENCRYPT_MODE, key);
  49.         byte[] cipherData = cipher.doFinal(message.getBytes());
  50.         return cipherData;
  51.     }
  52.    
  53.     public String decrypt(Key key, byte[] message) throws GeneralSecurityException {
  54.         Cipher cipher = Cipher.getInstance("RSA");
  55.         cipher.init(Cipher.DECRYPT_MODE, key);
  56.         byte[] cipherData = cipher.doFinal(message);
  57.         return new String(cipherData);
  58.     }
  59.    
  60.     public static void main(String[] args) throws GeneralSecurityException, IOException {
  61.         C1_03_EncryptDecrypt app = new C1_03_EncryptDecrypt("src/main/resources/ks", "password");
  62.         Key publicKey = app.getPublicKey("demo");
  63.         Key privateKey = app.getPrivateKey("demo", "password");
  64.        
  65.         System.out.println("Let's encrypt 'secret message' with a public key");
  66.         byte[] encrypted = app.encrypt(publicKey, "secret message");
  67.         System.out.println("Encrypted message: " + new BigInteger(1, encrypted).toString(16));
  68.         System.out.println("Let's decrypt it with the corresponding private key");
  69.         String decrypted = app.decrypt(privateKey, encrypted);
  70.         System.out.println(decrypted);
  71.        
  72.         System.out.println("You can also encrypt the message with a private key");
  73.         encrypted = app.encrypt(privateKey, "secret message");
  74.         System.out.println("Encrypted message: " + new BigInteger(1, encrypted).toString(16));
  75.         System.out.println("Now you need the public key to decrypt it");
  76.         decrypted = app.decrypt(publicKey, encrypted);
  77.         System.out.println(decrypted);
  78.     }
  79.    
  80. }
C1_01_DigestDefault.cs
  1. /*
  2.  * This class is part of the white paper entitled
  3.  * "Digital Signatures for PDF documents"
  4.  * written by Bruno Lowagie
  5.  *
  6.  * For more info, go to: http://itextpdf.com/learn
  7.  */
  8.  
  9. using System;
  10. using System.Security.Cryptography;
  11. using System.Text;
  12. using Org.BouncyCastle.Math;
  13. using Org.BouncyCastle.Security;
  14. using Org.BouncyCastle.Utilities;
  15.  
  16. namespace signatures.chapter1
  17. {
  18.     public class C1_01_DigestDefault
  19.     {
  20.         protected byte[] digest;
  21.         protected HashAlgorithm hash = null;
  22.        
  23.         protected C1_01_DigestDefault(String password, String algorithm) {
  24.             switch (algorithm) {
  25.                 case "MD5":
  26.                     hash = new MD5CryptoServiceProvider();
  27.                     break;
  28.                 case "SHA-1":
  29.                     hash = new SHA1Managed();
  30.                     break;
  31.                 case "SHA-256":
  32.                     hash = new SHA256Managed();
  33.                     break;
  34.                 case "SHA-384":
  35.                     hash = new SHA384Managed();
  36.                     break;
  37.                 case "SHA-512":
  38.                     hash = new SHA512Managed();
  39.                     break;
  40.                 case "RIPEMD160":
  41.                     hash = new RIPEMD160Managed();
  42.                     break;
  43.             }
  44.             digest = hash.ComputeHash(new UTF8Encoding().GetBytes(password));
  45.         }
  46.        
  47.         public static C1_01_DigestDefault GetInstance(String password, String algorithm) {
  48.             return new C1_01_DigestDefault(password, algorithm);
  49.         }
  50.        
  51.         public int DigestSize {
  52.             get {
  53.                 return digest.Length;
  54.             }
  55.         }
  56.        
  57.         public String GetDigestAsHexString() {
  58.             return new BigInteger(1, digest).ToString(16);
  59.         }
  60.  
  61.        
  62.         public bool CheckPassword(String password) {
  63.             byte[] result = hash.ComputeHash(new UTF8Encoding().GetBytes(password));
  64.             return Arrays.AreEqual(result, digest);
  65.         }
  66.        
  67.         public static void ShowTest(String algorithm) {
  68.             try {
  69.                 C1_01_DigestDefault app = GetInstance("password", algorithm);
  70.                 Console.WriteLine("Digest using " + algorithm + ": " + app.DigestSize);
  71.                 Console.WriteLine("Digest: " + app.GetDigestAsHexString());
  72.                 Console.WriteLine("Is the password 'password'? " + app.CheckPassword("password"));
  73.                 Console.WriteLine("Is the password 'secret'? " + app.CheckPassword("secret"));
  74.             } catch (GeneralSecurityException e) {
  75.                 Console.WriteLine(e.Message);
  76.             }
  77.         }
  78.        
  79.         public static void TestAll() {
  80.             ShowTest("MD5");
  81.             ShowTest("SHA-1");
  82.             ShowTest("SHA-256");
  83.             ShowTest("SHA-384");
  84.             ShowTest("SHA-512");
  85.             ShowTest("RIPEMD160");
  86.         }
  87.        
  88.         static void Main(String[] args) {
  89.             TestAll();
  90.             Console.ReadKey();
  91.         }
  92.     }
  93. }
C1_02_DigestBC.cs
  1. /*
  2.  * This class is part of the white paper entitled
  3.  * "Digital Signatures for PDF documents"
  4.  * written by Bruno Lowagie
  5.  *
  6.  * For more info, go to: http://itextpdf.com/learn
  7.  */
  8.  
  9. using System;
  10. using System.Text;
  11. using Org.BouncyCastle.Crypto;
  12. using Org.BouncyCastle.Math;
  13. using Org.BouncyCastle.Security;
  14. using Org.BouncyCastle.Utilities;
  15.  
  16. namespace signatures.chapter1
  17. {
  18.     class C1_02_DigestBC
  19.     {
  20.         protected byte[] digest;
  21.         protected IDigest hash;
  22.        
  23.         protected C1_02_DigestBC(String password, String algorithm) {
  24.             hash = DigestUtilities.GetDigest(algorithm);
  25.             byte[] bytes = new UTF8Encoding().GetBytes(password);
  26.             hash.BlockUpdate(bytes, 0, bytes.Length);
  27.             digest = new byte[hash.GetDigestSize()];
  28.             hash.DoFinal(digest, 0);
  29.         }
  30.        
  31.         public static C1_02_DigestBC GetInstance(String password, String algorithm) {
  32.             return new C1_02_DigestBC(password, algorithm);
  33.         }
  34.        
  35.         public int DigestSize {
  36.             get {
  37.                 return digest.Length;
  38.             }
  39.         }
  40.        
  41.         public String GetDigestAsHexString() {
  42.             return new BigInteger(1, digest).ToString(16);
  43.         }
  44.  
  45.        
  46.         public bool CheckPassword(String password) {
  47.             byte[] bytes = new UTF8Encoding().GetBytes(password);
  48.             hash.BlockUpdate(bytes, 0, bytes.Length);
  49.             byte[] result = new byte[hash.GetDigestSize()];
  50.             hash.DoFinal(result, 0);
  51.             return Arrays.AreEqual(result, digest);
  52.         }
  53.        
  54.         public static void ShowTest(String algorithm) {
  55.             try {
  56.                 C1_02_DigestBC app = GetInstance("password", algorithm);
  57.                 Console.WriteLine("Digest using " + algorithm + ": " + app.DigestSize);
  58.                 Console.WriteLine("Digest: " + app.GetDigestAsHexString());
  59.                 Console.WriteLine("Is the password 'password'? " + app.CheckPassword("password"));
  60.                 Console.WriteLine("Is the password 'secret'? " + app.CheckPassword("secret"));
  61.             } catch (GeneralSecurityException e) {
  62.                 Console.WriteLine(e.Message);
  63.             }
  64.         }
  65.        
  66.         public static void TestAll() {
  67.             ShowTest("MD5");
  68.             ShowTest("SHA-1");
  69.             ShowTest("SHA-224");
  70.             ShowTest("SHA-256");
  71.             ShowTest("SHA-384");
  72.             ShowTest("SHA-512");
  73.             ShowTest("RIPEMD128");
  74.             ShowTest("RIPEMD160");
  75.             ShowTest("RIPEMD256");
  76.         }
  77.        
  78.         static void Main(String[] args) {
  79.             TestAll();
  80.             Console.ReadKey();
  81.         }
  82.     }
  83. }
C1_03_EncryptDecrypt.cs
  1. /*
  2.  * This class is part of the white paper entitled
  3.  * "Digital Signatures for PDF documents"
  4.  * written by Bruno Lowagie
  5.  *
  6.  * For more info, go to: http://itextpdf.com/learn
  7.  */
  8.  
  9. using System;
  10. using System.Collections.Generic;
  11. using System.IO;
  12. using System.Text;
  13. using Org.BouncyCastle.Crypto;
  14. using Org.BouncyCastle.Crypto.Engines;
  15. using Org.BouncyCastle.Math;
  16. using Org.BouncyCastle.Pkcs;
  17. using Org.BouncyCastle.Crypto.Encodings;
  18.  
  19. namespace signatures.chapter1
  20. {
  21.     class C1_03_EncryptDecrypt
  22.     {
  23.         protected Pkcs12Store store;
  24.         public const String KEYSTORE = "../../../../resources/pkcs12";
  25.  
  26.         public C1_03_EncryptDecrypt(String keystore, String ks_pass) {
  27.             store = new Pkcs12Store(new FileStream(keystore, FileMode.Open), ks_pass.ToCharArray());
  28.         }
  29.  
  30.         public X509CertificateEntry GetCertificate(String alias){
  31.             return store.GetCertificate(alias);
  32.         }
  33.  
  34.         public AsymmetricKeyParameter GetPublicKey(String alias) {
  35.             return GetCertificate(alias).Certificate.GetPublicKey();
  36.         }
  37.  
  38.         public AsymmetricKeyEntry GetPrivateKey(String alias) {
  39.             return store.GetKey(alias);
  40.         }
  41.  
  42.         public byte[] Encrypt(ICipherParameters parameters, String message) {
  43.             List encryptedBytes = new List();
  44.             IAsymmetricBlockCipher cipher = new RsaEngine();
  45.             cipher = new Pkcs1Encoding(cipher);
  46.             cipher.Init(true, parameters);
  47.             byte[] messageBytes = new UTF8Encoding().GetBytes(message);
  48.             int i = 0;
  49.             int len = cipher.GetInputBlockSize();
  50.             while (i < messageBytes.Length)
  51.             {
  52.                 if (i + len > messageBytes.Length)
  53.                     len = messageBytes.Length - i;
  54.                 byte[] hexEncodedCipher = cipher.ProcessBlock(messageBytes, i, len);
  55.                 encryptedBytes.AddRange(hexEncodedCipher);
  56.                 i += cipher.GetInputBlockSize();
  57.             }
  58.             byte[] cipherData = new byte[encryptedBytes.Count];
  59.             encryptedBytes.CopyTo(cipherData);
  60.             return cipherData;
  61.         }
  62.        
  63.         public String Decrypt(ICipherParameters parameters, byte[] message) {
  64.             List encryptedBytes = new List();
  65.             IAsymmetricBlockCipher cipher = new RsaEngine();
  66.             cipher = new Pkcs1Encoding(cipher);
  67.             cipher.Init(false, parameters);
  68.             int i = 0;
  69.             int len = cipher.GetInputBlockSize();
  70.             while (i < message.Length)
  71.             {
  72.                 if (i + len > message.Length)
  73.                     len = message.Length - i;
  74.                 byte[] hexEncodedCipher = cipher.ProcessBlock(message, i, len);
  75.                 encryptedBytes.AddRange(hexEncodedCipher);
  76.                 i += cipher.GetInputBlockSize();
  77.             }
  78.             byte[] cipherData = new byte[encryptedBytes.Count];
  79.             encryptedBytes.CopyTo(cipherData);
  80.             return new UTF8Encoding().GetString(cipherData);
  81.         }
  82.        
  83.         static void Main(string[] args)
  84.         {
  85.             C1_03_EncryptDecrypt app = new C1_03_EncryptDecrypt(KEYSTORE, "password");
  86.             AsymmetricKeyParameter publicKey = app.GetPublicKey("demo");
  87.             AsymmetricKeyEntry privateKey = app.GetPrivateKey("demo");
  88.             Console.Write("Let's encrypt 'secret message' with a public key\n");
  89.             byte[] encrypted = app.Encrypt(publicKey, "secret message");
  90.             Console.WriteLine("Encrypted message: " + new BigInteger(1, encrypted).ToString(16));
  91.             Console.Write("Let's decrypt it with the corresponding private key\n");
  92.             String decrypted = app.Decrypt(privateKey.Key, encrypted);
  93.             Console.WriteLine(decrypted);
  94.  
  95.             Console.Write("\nYou can also encrypt the message with a private key\n");
  96.             encrypted = app.Encrypt(privateKey.Key, "secret message");
  97.             Console.WriteLine("Encrypted message: " + new BigInteger(1, encrypted).ToString(16));
  98.             Console.Write("Now you need the public key to decrypt it\n");
  99.             decrypted = app.Decrypt(publicKey, encrypted);
  100.             Console.WriteLine(decrypted);
  101.             Console.ReadKey();
  102.         }
  103.     }
  104. }
Contact

Still have questions? 

We're happy to answer your questions. Reach out to us and we'll get back to you shortly.

Contact us
Stay updated

Join 11,000+ subscribers and become an iText PDF expert by staying up to date with our new products, updates, tips, technical solutions and happenings.

Subscribe Now