Java encryption and digital signature Programming

Source: Internet
Author: User
Tags asymmetric encryption

This article mainly talks about encryption and digital signature in cryptography, and how to use it in java. For partners interested in cryptography, we recommend that you read Bruce Schneier's book: Applied Crypotography. Security has been greatly improved in the jdk1.5 release, and direct support for the RSA algorithm is also provided. Now we start with an example to solve the problem (this article is only for a brief introduction):

  I. concepts commonly used in cryptography

  1) Message summary:

This is a technology used in combination with message authentication codes to ensure message integrity. One-way hash function algorithms are mainly used to verify the integrity of messages and store messages in text format using hashed passwords. Currently, MD4, MD5, and SHA-1 are widely used algorithms, jdk1.5 provides support for the above. It is very easy to digest messages in java, java. security. messageDigest provides a simple operation method:

/**
* MessageDigestExample. java
* Copyright 2005-2-16
*/
Import java. security. MessageDigest;
/**
* A single message digest algorithm without a password. It can be used to hide and save plaintext messages (such as passwords ).
*/
Public class MessageDigestExample {
Public static void main (String [] args) throws Exception {
If (args. length! = 1 ){
System. err. println ("Usage: java MessageDigestExample text ");
System. exit (1 );
}

Byte [] plainText = args [0]. getBytes ("UTF8 ");

// Use getInstance ("algorithm") to obtain the message digest. Here the SHA-1 160-bit algorithm is used.
MessageDigest messageDigest = MessageDigest. getInstance ("SHA-1 ");

System. out. println ("" + messageDigest. getProvider (). getInfo ());
// Start using the algorithm
MessageDigest. update (plainText );
System. out. println ("Digest :");
// Output the algorithm operation result
System. out. println (new String (messageDigest. digest (), "UTF8 "));
}
}

The message authentication code can also be used for encryption. javax. crypto. Mac provides a solution. If you are interested, refer to the relevant API documentation. This article only briefly introduces what is the Digest algorithm.

 2) private key encryption:

Message digests can only check the integrity of messages, but one-way encryption is not allowed for plaintext messages. to encrypt plaintext messages, you must use other algorithms to ensure confidentiality, we need to use the private key cryptography to exchange private messages.

This is best understood by Using symmetric algorithms. For example, if A encrypts A file with A key, and B reads the file, it needs the same key as A. Both parties share A private key (in the web environment, private keys are easily listened upon Upon transmission ):

If you use the private key for encryption, you first need a key available for javax. crypto. keyGenerator generates a key (java. security. key), and then pass it to an encryption tool (javax. crypto. cipher), the tool uses the corresponding algorithms for encryption, the main symmetric algorithms are: DES (actual keys only use 56 bits), AES (three key lengths are supported: 128, 192, 256 bits), usually the first 128 bits, and the other are DESede. The jdk1.5 type also provides support for symmetric algorithms. The following example uses the AES algorithm for encryption:

/**
* PrivateExmaple. java
* Copyright 2005-2-16
*/
Import javax. crypto. Cipher;
Import javax. crypto. KeyGenerator;
Import java. security. Key;

/**
* Private token encryption ensures Message Confidentiality
*/
Public class PrivateExample {
Public static void main (String [] args) throws Exception {
If (args. length! = 1 ){
System. err. println ("Usage: java PrivateExample ");
System. exit (1 );
}
Byte [] plainText = args [0]. getBytes ("UTF8 ");

// Form a key through KeyGenerator
System. out. println ("Start generate AES key ");
KeyGenerator keyGen = KeyGenerator. getInstance ("AES ");
KeyGen. init (1, 128 );
Key key = keyGen. generateKey ();
System. out. println ("Finish generating DES key ");

// Obtain a private token Encryption Class Cipher. The ECB is the encryption method, and the PKCS5Padding is the filling method.
Cipher cipher = Cipher. getInstance ("AES/ECB/PKCS5Padding ");
System. out. println ("" + cipher. getProvider (). getInfo ());

// Use private keys for encryption
System. out. println ("Start encryption :");
Cipher. init (Cipher. ENCRYPT_MODE, key );
Byte [] cipherText = cipher. doFinal (plainText );
System. out. println ("Finish encryption :");
System. out. println (new String (cipherText, "UTF8 "));

System. out. println ("Start decryption :");
Cipher. init (Cipher. DECRYPT_MODE, key );
Byte [] newPlainText = cipher. doFinal (cipherText );
System. out. println ("Finish decryption :");

System. out. println (new String (newPlainText, "UTF8 "));

}
}

  3) public key encryption:

As mentioned above, private key encryption requires a shared key. How can we transmit the key? In the web environment, it is easy to listen for direct transfer. Fortunately, the emergence of public key encryption occurs. Public key encryption is also called asymmetric encryption. asymmetric algorithms use a pair of key pairs, a public key, a private key, and a public key to encrypt data. Only the private key can be unencrypted, only the public key can unbind the data encrypted with the private key ). However, it is slow (100 to 1000 times slower than private key encryption). The main public key algorithms include RSA, Blowfish, Diffie-Helman, and so on. jdk1.5 provides support for RSA, is an improvement:

/**
* PublicExample. java
* Copyright 2005-2-16
*/
Import java. security. Key;
Import javax. crypto. Cipher;
Import java. security. KeyPairGenerator;
Import java. security. KeyPair;
/**
* In a simple example of public encryption, the Cipher class uses the public and private keys generated by KeyPairGenerator.
*/
Public class PublicExample {
Public static void main (String [] args) throws Exception {
If (args. length! = 1 ){
System. err. println ("Usage: java PublicExample ");
System. exit (1 );
}

Byte [] plainText = args [0]. getBytes ("UTF8 ");
// Construct an RSA key
System. out. println ("Start generating RSA key ");
KeyPairGenerator keyGen = KeyPairGenerator. getInstance ("RSA ");
KeyGen. initialize (1024 );
KeyPair key = keyGen. generateKeyPair ();
System. out. println ("Finish generating RSA key ");

// Obtain an RSA Cipher class and use public encryption
Cipher cipher = Cipher. getInstance ("RSA/ECB/PKCS1Padding ");
System. out. println ("" + cipher. getProvider (). getInfo ());

System. out. println ("Start encryption ");
Cipher. init (Cipher. ENCRYPT_MODE, key. getPublic ());
Byte [] cipherText = cipher. doFinal (plainText );
System. out. println ("Finish encryption :");
System. out. println (new String (cipherText, "UTF8 "));

// Use private keys for decryption
System. out. println ("Start decryption ");
Cipher. init (Cipher. DECRYPT_MODE, key. getPrivate ());
Byte [] newPlainText = cipher. doFinal (cipherText );
System. out. println ("Finish decryption :");
System. out. println (new String (newPlainText, "UTF8 "));
}
}

   4) Digital signature:

Digital signature, which is the first level to determine the identity of the contact who exchanges messages. In the above example, A encrypts the data with the public key and sends it to B. B decrypts the data with the private key to obtain the required data. The problem arises because both are encrypted with the public key, how can we check the messages sent by? As mentioned above, the private key is unique, so A can use A's own private key for encryption, and then B can use A's public key for decryption; the principle of digital signature is based on this. To prove the authenticity of the sent data, a brief message content is obtained by using the message digest, then, use the private key to encrypt the hash data and send messages together. Java provides excellent support for digital signatures and java. security. Signature provides message signatures:

/**
* DigitalSignature2Example. java
* Copyright 2005-2-16
*/
Import java. security. Signature;
Import java. security. KeyPairGenerator;
Import java. security. KeyPair;
Import java. security. SignatureException;

/**
* Digital Signature: Use the RSA private key to sign the message digest, and then use the public signature for verification and testing.
*/
Public class DigitalSignature2Example {
Public static void main (String [] args) throws Exception {
If (args. length! = 1 ){
System. err. println ("Usage: java DigitalSignature2Example ");
System. exit (1 );
}

Byte [] plainText = args [0]. getBytes ("UTF8 ");
// Form an RSA public key pair
System. out. println ("Start generating RSA key ");
KeyPairGenerator keyGen = KeyPairGenerator. getInstance ("RSA ");
KeyGen. initialize (1024 );

KeyPair key = keyGen. generateKeyPair ();
System. out. println ("Finish generating RSA key ");
// Use the private signature
Signature sig = Signature. getInstance ("SHA1WithRSA ");
Sig. initSign (key. getPrivate ());
Sig. update (plainText );
Byte [] signature = sig. sign ();
System. out. println (sig. getProvider (). getInfo ());
System. out. println ("Signature :");
System. out. println (new String (signature, "UTF8 "));

// Use the public token for verification
System. out. println ("Start 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 e ){
System. out. println ("Signature failed ");
}
}
}


  5) digital certificate.

Another problem is the public key. If A is encrypted with the private key, B will decrypt the message with the public key provided by A. Now there is A nasty C, he intercepted the message, encrypted it with his private key, sent his public key to B, and told B that it was the public key of A. The result is ...., at this time, we need an intermediate organization to speak out (believe in Authority, I am correct), and then there will be Certificate Authority (that is, CA), famous CA institutions such as Verisign, currently, the industrial standard for digital authentication is: CCITT X.509:
Digital Certificate: it encapsulates an identity together with the public key and is digitally signed by a third party called an authentication center or CA.

Keystore: the java platform provides you with a keystore as a repository of keys and certificates. Physically, the keystore is a file named. keystore by default (there is an option to make it an encrypted file ). The key and certificate can have a name (called an alias). Each alias is protected by a unique password. The keystore itself is also password protected; you can choose to match each alias password with the master keystore password.

Use the keytool tool to perform self-authentication (believe my authentication ):

1. Create the keystore keytool-genkey-v-alias feiUserKey-keyalg RSA in its home directory by default (windows system is c: documents and settings <your username> directory. keystore file), create a self-signed certificate that we use the RSA algorithm to generate an alias for feiUserKey, if-keystore mm is used, create a keystore mm file in the current directory to save the key and certificate.

2. view the certificate: keytool-list lists all the certificates of the keystore.

You can also enter keytool-help in dos to view help.

  4) Digital signature:

Digital signature, which is the first level to determine the identity of the contact who exchanges messages. In the above example, A encrypts the data with the public key and sends it to B. B decrypts the data with the private key to obtain the required data. The problem arises because both are encrypted with the public key, how can we check the messages sent by? As mentioned above, the private key is unique, so A can use A's own private key for encryption, and then B can use A's public key for decryption; the principle of digital signature is based on this. To prove the authenticity of the sent data, a brief message content is obtained by using the message digest, then, use the private key to encrypt the hash data and send messages together. Java provides excellent support for digital signatures and java. security. Signature provides message signatures:

/**
* DigitalSignature2Example. java
* Copyright 2005-2-16
*/
Import java. security. Signature;
Import java. security. KeyPairGenerator;
Import java. security. KeyPair;
Import java. security. SignatureException;

/**
* Digital Signature: Use the RSA private key to sign the message digest, and then use the public signature for verification and testing.
*/
Public class DigitalSignature2Example {
Public static void main (String [] args) throws Exception {
If (args. length! = 1 ){
System. err. println ("Usage: java DigitalSignature2Example ");
System. exit (1 );
}

Byte [] plainText = args [0]. getBytes ("UTF8 ");
// Form an RSA public key pair
System. out. println ("Start generating RSA key ");
KeyPairGenerator keyGen = KeyPairGenerator. getInstance ("RSA ");
KeyGen. initialize (1024 );

KeyPair key = keyGen. generateKeyPair ();
System. out. println ("Finish generating RSA key ");
// Use the private signature
Signature sig = Signature. getInstance ("SHA1WithRSA ");
Sig. initSign (key. getPrivate ());
Sig. update (plainText );
Byte [] signature = sig. sign ();
System. out. println (sig. getProvider (). getInfo ());
System. out. println ("Signature :");
System. out. println (new String (signature, "UTF8 "));

// Use the public token for verification
System. out. println ("Start 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 e ){
System. out. println ("Signature failed ");
}
}
}

  5) digital certificate.

Another problem is the public key. If A is encrypted with the private key, B will decrypt the message with the public key provided by A. Now there is A nasty C, he intercepted the message, encrypted it with his private key, sent his public key to B, and told B that it was the public key of A. The result is ...., at this time, we need an intermediate organization to speak out (believe in Authority, I am correct), and then there will be Certificate Authority (that is, CA), famous CA institutions such as Verisign, currently, the industrial standard for digital authentication is: CCITT X.509:
Digital Certificate: it encapsulates an identity together with the public key and is digitally signed by a third party called an authentication center or CA.

Keystore: the java platform provides you with a keystore as a repository of keys and certificates. Physically, the keystore is a file named. keystore by default (there is an option to make it an encrypted file ). The key and certificate can have a name (called an alias). Each alias is protected by a unique password. The keystore itself is also password protected; you can choose to match each alias password with the master keystore password.

Use the keytool tool to perform self-authentication (believe my authentication ):

1. Create the keystore keytool-genkey-v-alias feiUserKey-keyalg RSA in its home directory by default (windows system is c: documents and settings <your username> directory. keystore file), create a self-signed certificate that we use the RSA algorithm to generate an alias for feiUserKey, if-keystore mm is used, create a keystore mm file in the current directory to save the key and certificate.

2. view the certificate: keytool-list lists all the certificates of the keystore.

You can also enter keytool-help in dos to view help.

Related Article

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.