Java security, Part 1: cryptographic BASICS (digital signature)

Source: Internet
Author: User

Paperless Signature

Overview

In this chapter, we will study digital signatures, which are the first level to determine the identity of the contact who exchanges messages. We will use code samples to describe the two methods used to identify the message source (one is more difficult and the other is easier ). We will also list the digital signature Algorithms supported by JDK 1.4 and research the classes and methods involved.

Back to Top

What is a digital signature?

What is public key cryptography? Is there a defect in the public key message exchange described in? How can Bob confirm the message?IndeedIs it from Alice? Eve can replace Alice's public key with her public key. Then Bob will exchange messages with Eve and think she is Alice. This is calledMan-in-the-middle attack.

We can useDigital SignatureSolve this problem-digital signature is the bit mode that confirms that the message comes from a specific contact.

One of the ways to implement digital signatures is to use anti-What is public key cryptography? The public key process described in. Instead of using the public key to encrypt and decrypt the message, the sender uses the private key to sign the message, and the receiver uses the public key of the sender to decrypt the message. Because only the sender knows the private key, the receiver can ensure that the message actually comes from the receiver.

In fact, a message digest (what is a message digest ?) (But not the entire message) is a bit stream signed with a private key. Therefore, if Alice wants to send a signed message to Bob, she will generate the message digest of the message and then sign it with the private key. She sends the message (in plaintext) and the signed message digest to Bob. Bob decrypts the signature message digest with Alice's public key, computes the message digest of the plaintext message, and checks whether the two digests match. If they match
Bob can confirm that the message is from Alice.

Note: digital signatures do not provide message encryption, So if you still need confidentiality, you must combine encryption technology with signature.

You can use the RSA Algorithm for digital signature and encryption. The US standard digital signature algorithm (DSA) can be used for digital signatures, but cannot be used for encryption.

Back to Top

Algorithm

JDK 1.4 supports the following digital signature algorithms:

  • Md2/RSA
  • MD5/RSA
  • Sha1/DSA
  • Sha1/RSA

We will study two examples in this chapter. First, study the difficult method (see the digital signature code example: the difficult method). It uses the primitives we have discussed for message digest and public key cryptography to implement digital signature. Then study the simple method (see the digital signature code example: a simple method), which uses
JAVA supports signatures directly.

Back to Top

Example of digital signature code: difficult method

import java.security.*;import javax.crypto.*;//// This program demonstrates the digital signature technique at the// primative level by generating a message digest of the plaintext// and signing it with an RSA private key, to create the signature.// To verify the signature, the message digest is again generated from// the plaintext and compared with the decryption of the signature// using the public key.  If they match, the signature is verified.public class DigitalSignature1Example {  public static void main (String[] args) throws Exception {    //    // check args and get plaintext    if (args.length !=1) {      System.err.println("Usage: java DigitalSignature1Example text");      System.exit(1);    }    byte[] plainText = args[0].getBytes("UTF8");    //    // get an MD5 message digest object and compute the plaintext digest    MessageDigest messageDigest = MessageDigest.getInstance("MD5");    System.out.println( "\n" + messageDigest.getProvider().getInfo() );    messageDigest.update( plainText );    byte[] md = messageDigest.digest();    System.out.println( "\nDigest: " );    System.out.println( new String( md, "UTF8") );    //    // generate an RSA keypair    System.out.println( "\nStart generating RSA key" );    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");    keyGen.initialize(1024);    KeyPair key = keyGen.generateKeyPair();    System.out.println( "Finish generating RSA key" );    //    // get an RSA cipher and list the provider    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");    System.out.println( "\n" + cipher.getProvider().getInfo() );    //    // encrypt the message digest with the RSA private key    // to create the signature    System.out.println( "\nStart encryption" );    cipher.init(Cipher.ENCRYPT_MODE, key.getPrivate());    byte[] cipherText = cipher.doFinal(md);    System.out.println( "Finish encryption: " );    System.out.println( new String(cipherText, "UTF8") );    //    // to verify, start by decrypting the signature with the    // RSA private key    System.out.println( "\nStart decryption" );    cipher.init(Cipher.DECRYPT_MODE, key.getPublic());    byte[] newMD = cipher.doFinal(cipherText);    System.out.println( "Finish decryption: " );    System.out.println( new String(newMD, "UTF8") );    //    // then, recreate the message digest from the plaintext    // to simulate what a recipient must do    System.out.println( "\nStart signature verification" );    messageDigest.reset();    messageDigest.update(plainText);    byte[] oldMD = messageDigest.digest();    //    // verify that the two message digests match    int len = newMD.length;    if (len > oldMD.length) {      System.out.println( "Signature failed, length error");      System.exit(1);    }    for (int i = 0; i < len; ++i)      if (oldMD[i] != newMD[i]) {        System.out.println( "Signature failed, element error" );        System.exit(1);      }    System.out.println( "Signature verified" );  }}

Back to Top

Sample execution

D:\IBM>java DigitalSignature1Example "This is a test!"SUN (DSA key/parameter generation; DSA signing; SHA-1, MD5 digests; SecureRandom; X.509 certificates; JKS keystore; PKIX CertPathValidator; PKIX CertPathBuilder; LDAP, Collection CertStores)Digest:D647dbdek12*e,ad.?eStart generating RSA keyFinish generating RSA keyBouncyCastle Security Provider v1.12Start encryptionFinish encryption:Akjsdfp-9q8237nrcas-9de8fn239-4rb[*[OPOsjkdfJDL:JF;lkjs;ldjStart decryptionFinish decryption:iNdf6D213$dcd(ndz!0)Start signature verificationSignature verified

Back to Top

Example of digital signature code: A Simple Method

SignatureClass usageKeyPairGeneratorClass to operate on digital signatures. The following method is used in the example below:

  • KeyPairGenerator.getInstance("RSA"),.initialize(1024)And.generateKeyPair(): Generate a key.

  • Cipher.getInstance("MD5WithRSA"): CreateSignatureObject.

  • .initSign(key.getPrivate()): InitializationSignatureObject.

  • .update(plainText)And.sign(): Calculate the signature using a plaintext string.

  • .initVerify(key.getPublic())And.verify(signature): Verify the signature.
import java.security.*;import javax.crypto.*;//// This example uses the digital signature features to generate and// verify a signature much more easily than the previous examplepublic class DigitalSignature2Example {  public static void main (String[] args) throws Exception {    //    // check args and get plaintext    if (args.length !=1) {      System.err.println("Usage: java DigitalSignature1Example text");      System.exit(1);    }    byte[] plainText = args[0].getBytes("UTF8");    //    // generate an RSA keypair    System.out.println( "\nStart generating RSA key" );    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");    keyGen.initialize(1024);    KeyPair key = keyGen.generateKeyPair();    System.out.println( "Finish generating RSA key" );    //    // get a signature object using the MD5 and RSA combo    // and sign the plaintext with the private key,    // listing the provider along the way    Signature sig = Signature.getInstance("MD5WithRSA");    sig.initSign(key.getPrivate());    sig.update(plainText);    byte[] signature = sig.sign();    System.out.println( sig.getProvider().getInfo() );    System.out.println( "\nSignature:" );    System.out.println( new String(signature, "UTF8") );    //    // verify the signature with the public key    System.out.println( "\nStart signature verification" );    sig.initVerify(key.getPublic());    sig.update(plainText);    try {      if (sig.verify(signature)) {        System.out.println( "Signature verified" );      } else System.out.println( "Signature failed" );    } catch (SignatureException se) {      System.out.println( "Signature failed" );    }  }}

Back to Top

Sample execution

Start generating RSA keyFinish generating RSA keySun JSSE provider(implements RSA Signatures, PKCS12, SunX509 key/trust factories, SSLv3, TLSv1)Signature:Ldkjahasdlkjfq[?owc42093nhasdk1a;sn;a#a;lksjd;fl@#kjas;ldjf78qwe09r7Start signature verificationSignature verified
From: http://www.ibm.com/developerworks/cn/education/java/j-sec1/section6.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.