This article mainly discusses cryptography and digital signature, and how it is used in Java. The partner who is interested in cryptography is recommended to see Bruce Schneier's book: Applied Crypotography. There has been a great improvement in security in the release of jdk1.5, as well as direct support for RSA algorithms, and now we're going to solve the problem from the example (this article is just a brief introduction):
first, the commonly used concepts in cryptography
1) Message Summary:
This is a technique that is used in conjunction with the message authentication code to ensure message integrity. The main use of one-way hash function algorithm, can be used to verify the integrity of the message, and through the hash password directly in the form of text preservation, etc., the current widely used algorithms are MD4, MD5, sha-1,jdk1.5 to provide support for the above, in the Java Message digest is very simple, Java.security.MessageDigest provides an easy way to operate:
/**
*messagedigestexample.java
*copyright 2005-2-16
*/
Import Java.security.MessageDigest;
/**
* A single message digest algorithm, without a password. Can be used to hide and save plaintext messages (e.g., 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 the getinstance ("algorithm") to get the message digest, which uses the SHA-1 160-bit algorithm
MessageDigest messagedigest=messagedigest.getinstance ("SHA-1");
System.out.println ("" +messagedigest.getprovider (). GetInfo ());
Start using algorithms
Messagedigest.update (plaintext);
System.out.println ("Digest:");
Output algorithm operation result
System.out.println (New String (Messagedigest.digest (), "UTF8"));
}
}
The message authentication code can also be used to encrypt the implementation, JAVAX.CRYPTO.MAC provides a solution, interested people can refer to the relevant API documentation, this article simply describes what is the digest algorithm.
2) Private key encryption:
Message digest can only check the integrity of the message, but one-way, plaintext messages can not be encrypted, to encrypt plaintext messages, it is necessary to use other algorithms, to ensure confidentiality, we need to use the private key cryptography to exchange private messages.
This is best understood using symmetric algorithms. For example: A encrypts a file with a key, and B reads the file, requires the same key as a, and the two sides share a private key (and in the Web environment, the private key is easy to listen to when it is passed):
Using the private key encryption, first requires a key, can be javax.crypto.KeyGenerator to generate a key (Java.security.Key), and then passed to a cryptographic tool (Javax.crypto.Cipher), The tool is then used to encrypt the corresponding algorithm, the main symmetric algorithm is: DES (the actual key to use only 56 bits), AES (support three key lengths: 128, 192, 256 bits), usually first 128 digits, and other desede, etc. The jdk1.5 species also provides support for symmetric algorithms, and the following examples use the AES algorithm to encrypt:
/**
*privateexmaple.java
*copyright 2005-2-16
*/
Import Javax.crypto.Cipher;
Import Javax.crypto.KeyGenerator;
Import Java.security.Key;
/**
* Private 鈅 encryption, to ensure the confidentiality of the message
*/
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 (128);
Key Key=keygen.generatekey ();
SYSTEM.OUT.PRINTLN ("Finish generating DES key");
Get a private 鈅 encryption class CIPHER,ECB is encrypted, pkcs5padding is the Fill method
Cipher cipher=cipher.getinstance ("aes/ecb/pkcs5padding");
System.out.println ("" +cipher.getprovider (). GetInfo ());
Use private 鈅 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 cryptography:
As mentioned above, private key encryption requires a shared key, so how do you pass the key? In the Web environment, the direct transmission of words can easily be heard, fortunately with the emergence of public key encryption. Public-key cryptography is also called Asymmetric encryption, which uses a pair of key pairs, a public key, a private key, and a public key to encrypt the data, only the private key can be untied (can be used for encryption), and the data encrypted with the private key can only be untied (signed). But the speed is slow (100 to 1000 times times faster than the private key encryption), the main algorithm of the public key has RSA, also includes Blowfish,diffie-helman, etc., jdk1.5 provides the support to RSA, is an improvement place:
/**
*publicexample.java
*copyright 2005-2-16
*/
Import Java.security.Key;
Import Javax.crypto.Cipher;
Import Java.security.KeyPairGenerator;
Import Java.security.KeyPair;
/**
* A simple public 鈅 encryption example, cipher class using keypairgenerator generated public 鈅 and private 鈅
*/
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");
form 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");
Get an RSA cipher class that uses a 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 鈅 to decrypt
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:
A digital signature, which is the first level of communication identity that determines the exchange of messages. Above A through the use of public key to encrypt the data sent to B,b to decrypt the use of the private key to get the required data, the problem is, because the use of public key encryption, then how to verify that a sent over the message? It also mentions a bit, the private key is unique, then a can use a own private key to encrypt, then B and then use a public key to decrypt, it can be, the principle of digital signature is based on this, and usually to prove the authenticity of sending data, by using a message digest to obtain short message content, The cryptographic hash data is then sent with the message using the private key. Java provides good support for digital signatures, and the Java.security.Signature class provides message signing:
/**
*digitalsignature2example.java
*copyright 2005-2-16
*/
Import Java.security.Signature;
Import Java.security.KeyPairGenerator;
Import Java.security.KeyPair;
Import java.security.SignatureException;
/**
* Digitally sign, use RSA private key pair to sign message digest, then use public 鈅 to verify test
*/
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 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 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"));
Using public 鈅 Validation
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 that the public key problem, a is encrypted with the private key, then B is decrypted with the public key provided by a when the message is received; So now there's a nasty C, he intercepts the message, encrypts it with his private key, sends his public key to B, and tells B, that's a public key, the result ..., At this time need a intermediary to speak out (believe authority, I was right), on the Emergence of certificate authority (also known as CA), a well-known CA organization, such as VeriSign, the current digital certification of the Industrial standard is: CCITT X.509:
Digital certificate: It encapsulates an identity along with the public key and is digitally signed by a third party called a certification center or CA.
KeyStore: The Java platform provides you with a keystore that serves as a repository for keys and certificates. Physically, a keystore is a file with a default name of. KeyStore (with an option to make it an encrypted file). Keys and certificates can have names (called aliases), and each alias is protected by a unique password. The KeyStore itself is also password protected; You can choose to have each alias password match the master KeyStore password.
Using tool Keytool, let's do a Self certification thing (Trust my certification):
1. Create KeyStore keytool-genkey-v-alias feiuserkey-keyalg RSA defaults to your home directory (Windows system is c:documents and settings< your username > Directory, create a self-signed certificate that uses the RSA algorithm to generate aliases for Feiuserkey, and if you use-keystore mm, create a keystore mm file in the current directory to hold the keys and certificates.
2, view the certificate: Keytool-list listed all the certificates of the KeyStore
You can also enter KEYTOOL-HELP in DOS to view Help.
4) Digital signature:
A digital signature, which is the first level of communication identity that determines the exchange of messages. Above A through the use of public key to encrypt the data sent to B,b to decrypt the use of the private key to get the required data, the problem is, because the use of public key encryption, then how to verify that a sent over the message? It also mentions a bit, the private key is unique, then a can use a own private key to encrypt, then B and then use a public key to decrypt, it can be, the principle of digital signature is based on this, and usually to prove the authenticity of sending data, by using a message digest to obtain short message content, The cryptographic hash data is then sent with the message using the private key. Java provides good support for digital signatures, and the Java.security.Signature class provides message signing:
/**
*digitalsignature2example.java
*copyright 2005-2-16
*/
Import Java.security.Signature;
Import Java.security.KeyPairGenerator;
Import Java.security.KeyPair;
Import java.security.SignatureException;
/**
* Digitally sign, use RSA private key pair to sign message digest, then use public 鈅 to verify test
*/
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 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 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"));
Using public 鈅 Validation
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 that the public key problem, a is encrypted with the private key, then B is decrypted with the public key provided by a when the message is received; So now there's a nasty C, he intercepts the message, encrypts it with his private key, sends his public key to B, and tells B, that's a public key, the result ..., At this time need a intermediary to speak out (believe authority, I was right), on the Emergence of certificate authority (also known as CA), a well-known CA organization, such as VeriSign, the current digital certification of the Industrial standard is: CCITT X.509:
Digital certificate: It encapsulates an identity along with the public key and is digitally signed by a third party called a certification center or CA.
KeyStore: The Java platform provides you with a keystore that serves as a repository for keys and certificates. Physically, a keystore is a file with a default name of. KeyStore (with an option to make it an encrypted file). Keys and certificates can have names (called aliases), and each alias is protected by a unique password. The KeyStore itself is also password protected; You can choose to have each alias password match the master KeyStore password.
Using tool Keytool, let's do a Self certification thing (Trust my certification):
1. Create KeyStore keytool-genkey-v-alias feiuserkey-keyalg RSA defaults to your home directory (Windows system is c:documents and settings< your username > Directory, create a self-signed certificate that uses the RSA algorithm to generate aliases for Feiuserkey, and if you use-keystore mm, create a keystore mm file in the current directory to hold the keys and certificates.
2, view the certificate: Keytool-list listed all the certificates of the KeyStore
You can also enter KEYTOOL-HELP in DOS to view Help.