This article mainly talks about encryption and digital signatures in cryptography, and how they are used in Java. For those interested in cryptography, please read Bruce Schneier's book: Applied Crypotography. There have been great improvements in the security in the jdk1.5 release version and provide direct support for the RSA algorithm. Now we start with the example to solve the problem (this article is just a brief introduction):
1. Commonly used concepts in cryptography
1) Message summary:
This is a technique used in conjunction with message authentication code to ensure message integrity. It mainly uses a one-way hash function algorithm, which can be used to verify the integrity of messages and save them directly in text through hash passwords. Currently, the widely used algorithms include MD4, MD5, SHA-1, and jdk1.5 provides support for all of them. It is very simple to summarize messages in Java, providing a simple operation method:
/**
*
*Copyright 2005-2-16
*/
import ;
/**
*Single message digest algorithm, no password is used. 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(!=1){
("Usage:java MessageDigestExample text");
(1);
}
byte[] plainText=args[0].getBytes("UTF8");
//Use getInstance("algorithm") to obtain message digest, here SHA-1's 160-bit algorithm is used here
MessageDigest messageDigest=("SHA-1");
(" "+().getInfo());
//Begin using the algorithm
(plainText);
(" Digest:");
//Output algorithm operation result
(new String((),"UTF8"));
}
}
It can also be encrypted through message authentication code, providing a solution. Interested people can refer to the relevant API documents. This article just briefly introduces what is a summary algorithm.
2) Private key encryption:
Message digest can only check the integrity of the message, but in one-way, plaintext messages cannot be encrypted. To encrypt plaintext messages, other algorithms must be used to ensure confidentiality, we need to use private key cryptography to exchange private messages.
This is best understood, using a symmetric algorithm. For example: A uses a key to encrypt a file, and B needs to read this file, it needs the same key as A, and both parties share a private key (and in the web environment, the private key is easily listened to when passed):
If you use a private key to encrypt, you first need a key, which can be generated, and then passed to an encryption tool (). The tool then uses the corresponding algorithm to encrypt. The main symmetric algorithms are: DES (the actual key is only 56 bits), AES (supports three key lengths: 128, 192, 256 bits), usually 128 bits first, and the others are DESede, etc. jdk1.5 also provides support for symmetric algorithms. The following example uses the AES algorithm to encrypt:
/**
*
*Copyright 2005-2-16
*/
import ;
import ;
import ;
/**
*Private encryption to ensure the confidentiality of messages
*/
public class PrivateExample{
public static void main(String[] args) throws Exception{
if(!=1){
("Usage:java PrivateExample
(1);
}
byte[] plainText=args[0].getBytes("UTF8");
//Form a key through KeyGenerator
(" Start generate AES key");
KeyGenerator keyGen=("AES");
(128);
Key key=();
("Finish generating DES key");
//Get a private encryption class Cipher, ECB is the encryption method, PKCS5Padding is the filling method
Cipher cipher=("AES/ECB/PKCS5Padding");
(" "+().getInfo());
//Use private encryption
(" Start encryption:");
(Cipher.ENCRYPT_MODE,key);
byte[] cipherText=(plainText);
("Finish encryption:");
(new String(cipherText,"UTF8"));
(" Start decryption:");
(Cipher.DECRYPT_MODE,key);
byte[] newPlainText=(cipherText);
("Finish decryption:");
(new String(newPlainText,"UTF8"));
}
}
3) Public key encryption:
As mentioned above, private key encryption requires a shared key, so how to pass the key? In the web environment, direct transmission is easily heard, but fortunately, public key encryption appears. Public key encryption is also called asymmetric encryption. The asymmetric algorithm uses a pair of key pairs, one public key, and one private key. Only the private key can be decrypted (can be used for encryption); at the same time, only the public key can be decrypted (signed) the data encrypted using the private key. But the speed is very slow (100 to 1000 times slower than private key encryption). The main algorithms for public keys include RSA, including Blowfish, Diffie-Helman, etc. jdk1.5 provides support for RSA, which is an improvement:
/**
*
*Copyright 2005-2-16
*/
import ;
import ;
import ;
import ;
/**
*A simple public cryptographic example, the Cipher class uses the public and private crypts generated by the KeyPairGenerator
*/
public class PublicExample{
public static void main(String[] args) throws Exception{
if(!=1){
("Usage:java PublicExample
(1);
}
byte[] plainText=args[0].getBytes("UTF8");
//Constitute an RSA key
(" Start generating RSA key");
KeyPairGenerator keyGen=("RSA");
(1024);
KeyPair key=();
("Finish generating RSA key");
//Get a RSA Cipher class, use public encryption
Cipher cipher=("RSA/ECB/PKCS1Padding");
(" "+().getInfo());
(" Start encryption");
(Cipher.ENCRYPT_MODE,());
byte[] cipherText=(plainText);
("Finish encryption:");
(new String(cipherText,"UTF8"));
//Use private decryption
(" Start decryption");
(Cipher.DECRYPT_MODE,());
byte[] newPlainText=(cipherText);
("Finish decryption:");
(new String(newPlainText,"UTF8"));
}
}
4) Digital signature:
Digital signature, which is the first level to determine the identity of the communicator who exchanges messages. A above uses the public key to encrypt the data and send it to B. B uses the private key to decrypt it to obtain the required data. The problem is that since all the public keys are encrypted, how to verify that it is a message sent by A? As mentioned above, the private key is unique, so A can use A's own private key to encrypt, and then B uses A's public key to decrypt, and that's enough; the principle of digital signature is based on this, and usually in order to prove the authenticity of the sent data, a short message content is obtained by using the message digest, and then the private key is used to encrypt hash data and send the message together. There is good support for digital signatures in Java, and the class provides message signatures:
/**
*
*Copyright 2005-2-16
*/
import ;
import ;
import ;
import ;
/**
*Digital signature, use RSA private key pair to sign the message digest, and then use public verification Test
*/
public class DigitalSignature2Example{
public static void main(String[] args) throws Exception{
if(!=1){
("Usage:java DigitalSignature2Example
(1);
}
byte[] plainText=args[0].getBytes("UTF8");
//Form an RSA public key pair
(" Start generating RSA key");
KeyPairGenerator keyGen=("RSA");
(1024);
KeyPair key=();
("Finish generating RSA key");
//Use private signature
Signature sig=("SHA1WithRSA");
(());
(plainText);
byte[] signature=();
(().getInfo());
(" Signature:");
(new String(signature,"UTF8"));
//Use public verification
(" Start signature verification");
(());
(plainText);
try{
if((signature)){
("Signature verified");
}else ("Signature failed");
}catch(SignatureException e){
("Signature failed");
}
}
}
5) Digital certificate.
There is another problem, which is the public key problem. A is encrypted with the private key, so after B receives the message, decrypts it with the public key provided by A; then there is now an annoying C. He intercepts the message, then encrypts it with his own private key, and sends his public key to B, and tells B that it is A's public key. As a result..., an intermediate agency needs to speak out (believe in authority, I am correct), and Certificate Authority (aka CA). Famous CA institutions include Verisign, etc. The current industry standard for digital certification is: CCITT's X.509:
Digital Certificate: It encapsulates an identity along with a 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, which is used as a resource library for keys and certificates. Physically, a keystore is a file with the default name .keystore (there is an option to make it an encrypted file). Keys and certificates can have names (called alias), each alias 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.
Using the tool keytool, let’s do a self-certification thing (trust my certification):
1. Create a keystore keytool -genkey -v -alias feiUserKey -keyalg RSA defaults to its own home directory (the .keystore file in the c:documents and settings <your username> directory in the windows system), and create a self-signed certificate with the alias feiUserKey using the RSA algorithm. 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 certificates in the keystore
You can also enter keytool -help under dos to view the help.
4) Digital signature:
Digital signature, which is the first level to determine the identity of the communicator who exchanges messages. A above uses the public key to encrypt the data and send it to B. B uses the private key to decrypt it to obtain the required data. The problem is that since all the public keys are encrypted, how to verify that it is a message sent by A? As mentioned above, the private key is unique, so A can use A's own private key to encrypt, and then B uses A's public key to decrypt, and that's enough; the principle of digital signature is based on this, and usually in order to prove the authenticity of the sent data, a short message content is obtained by using the message digest, and then the private key is used to encrypt hash data and send the message together. There is good support for digital signatures in Java, and the class provides message signatures:
/**
*
*Copyright 2005-2-16
*/
import ;
import ;
import ;
import ;
/**
*Digital signature, use RSA private key pair to sign the message digest, and then use public verification Test
*/
public class DigitalSignature2Example{
public static void main(String[] args) throws Exception{
if(!=1){
("Usage:java DigitalSignature2Example
(1);
}
byte[] plainText=args[0].getBytes("UTF8");
//Form an RSA public key pair
(" Start generating RSA key");
KeyPairGenerator keyGen=("RSA");
(1024);
KeyPair key=();
("Finish generating RSA key");
//Use private signature
Signature sig=("SHA1WithRSA");
(());
(plainText);
byte[] signature=();
(().getInfo());
(" Signature:");
(new String(signature,"UTF8"));
//Use public verification
(" Start signature verification");
(());
(plainText);
try{
if((signature)){
("Signature verified");
}else ("Signature failed");
}catch(SignatureException e){
("Signature failed");
}
}
}
5) Digital certificate.
There is another problem, which is the public key problem. A is encrypted with the private key, so after B receives the message, decrypts it with the public key provided by A; then there is now an annoying C. He intercepts the message, then encrypts it with his own private key, and sends his public key to B, and tells B that it is A's public key. As a result..., an intermediate agency needs to speak out (believe in authority, I am correct), and Certificate Authority (aka CA). Famous CA institutions include Verisign, etc. The current industry standard for digital certification is: CCITT's X.509:
Digital Certificate: It encapsulates an identity along with a 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, which is used as a resource library for keys and certificates. Physically, a keystore is a file with the default name .keystore (there is an option to make it an encrypted file). Keys and certificates can have names (called alias), each alias 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.
Using the tool keytool, let’s do a self-certification thing (trust my certification):
1. Create a keystore keytool -genkey -v -alias feiUserKey -keyalg RSA defaults to its own home directory (the .keystore file in the c:documents and settings <your username> directory in the windows system), and create a self-signed certificate with the alias feiUserKey using the RSA algorithm. 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 certificates in the keystore
You can also enter keytool -help under dos to view the help.