Secure learning in Java (including encryption, digital signatures, certificates and certifications)

Source: Internet
Author: User
Tags decrypt asymmetric encryption

(1) Message Summary:

message Digest, also known as a Digital digest (digitally Digest). It is the only fixed-length value that corresponds to a message or text that is generated by a one-way hash encryption function that acts on the message. If the message changes on the way, the recipient can tell whether the message has been changed by comparing the newly generated digest of the received message with the original digest.       The message digest therefore guarantees the integrity of the message. The message digest uses a one-way hash function to encrypt the plaintext "digest" into a string of 128bit cipher text, which is also known as digital fingerprint (Finger print), it has a fixed length, and different plaintext abstracts into ciphertext, the results are always different, and the same plaintext its summary must be consistent. This sequence of abstracts can be used to verify whether the plaintext is a "true" fingerprint.

This is a technique used in conjunction with message authentication codes to ensure message integrity. The main use of one-way hash function algorithm, can be used to verify the integrity of the message, and by hashing the password directly in the form of text, and so on, the current widely used algorithms have MD4, MD5, SHA-1, the message digest in Java is simple: The following is a simple example

/**
*messagedigesttest.java
*/
Import Java.security.MessageDigest;
/**
* A single message digest algorithm that does not use a password. Can be used to hide a clear text message (such as: password) to save
*/
public class messagedigesttest{
public static void Main (string[] args) throws exception{


String str= "123";
Byte[] Plaintext=str.getbytes ("UTF8");

Use getinstance ("algorithm") to get the message digest, which uses the SHA-1 160-bit algorithm
MessageDigest messagedigest=messagedigest.getinstance ("SHA-1");

SYSTEM.OUT.PRINTLN ("/n" +messagedigest.getprovider (). GetInfo ());
Getting Started with algorithms
Messagedigest.update (plaintext);
System.out.println ("/ndigest:");
Output algorithm Operation results
System.out.println (New String (Messagedigest.digest (), "UTF8"));
}


(You can also use the message authentication code for the encryption implementation, JAVAX.CRYPTO.MAC provides a solution, interested people can refer to the relevant API documentation, this article is simply to explain what is a digest algorithm.) )

(2) Private public key and private key:

The public and private keys are commonly known as asymmetric encryption, which is improved from the previous symmetric encryption (using user name and password). Explain the principle in e-mail.

The purpose of using public and private keys is to implement secure e-mail, which must be accomplished as follows:

1. The content I send to you must be encrypted and cannot be seen by others during the transmission of the message.

2. Must ensure that I sent the mail, not someone impersonating me.

To achieve such a goal, both people who must send the message have a public and private key.

Public key, is for everyone to use, you can be published by e-mail, can be downloaded through the website, the public key is actually used to encrypt/stamp use. The private key, is his own, must be very careful to save, preferably with a password, the private key is used to decrypt/seal, first of all the key ownership, the private key only personal ownership. The function of public key and private key is: the content encrypted with public key can only be decrypted with private key, and the content encrypted with private key can only be decrypted with public key.

For example, I want to send you an encrypted message. First, I have to have your public key, and you have to have my public key.

First of all, I use your public key to encrypt this message, so that the message is not seen by others, and ensure that the message is not modified during the transfer process. After you receive the email, you can decrypt it with your private key and you can see the content.

Second, I use my private key to encrypt this message, sent to your hand, you can use my public key decryption. Because the private key is only in my hand, this ensures that this email is sent to me.

When A->b data, a will use B's public key encryption, so as to ensure that only B can unlock, otherwise the general public can unlock the encrypted message, is to the confidentiality of information. Verification is the use of the mechanism of the signing of the seal, a transmission of information to everyone, will be the signature of their own private key, so that all the people who receive the message can use a's public key for verification, you can confirm that the message was sent by a.

I. Private key encryption and decryption example:

/**
*privatetest.java
*/
Import Javax.crypto.Cipher;
Import Javax.crypto.KeyGenerator;
Import Java.security.Key;

/**
* Private hierarchy encryption to ensure message confidentiality
*/
public class privatetest{
public static void Main (string[] args) throws exception{

        String str= "123";
Byte[] Plaintext=str.getbytes ("UTF8");   

//keygenerator form a key
System.out.println ("/nstart 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 hierarchy encryption class CIPHER,ECB is encrypted, pkcs5padding is the Fill method
Cipher cipher=cipher.getinstance ("aes/ecb/pkcs5padding" );
System.out.println ("/n" +cipher.getprovider (). GetInfo ());   

//Use private hierarchy Encryption
System.out.println ("/nstart encryption:");
Cipher.init (Cipher.encrypt_mode,key);
Byte[] ciphertext=cipher.dofinal (plaintext);
System.out.println ("Finish encryption:");
System.out.println (New String (Ciphertext, "UTF8"));

Use private hierarchy to decrypt

System.out.println ("/nstart decryption:");
Cipher.init (Cipher.decrypt_mode,key);
Byte[] newplaintext=cipher.dofinal (ciphertext);
System.out.println ("Finish decryption:");

System.out.println (New String (Newplaintext, "UTF8"));

}


II. Public key encryption, private key decryption example:

/**
*publictest.java
*/
Import Java.security.Key;
Import Javax.crypto.Cipher;
Import Java.security.KeyPairGenerator;
Import Java.security.KeyPair;
/**
* A simple public hierarchy encryption example, cipher class using keypairgenerator generated by the male hierarchy and private hierarchy
*/
public class publictest{
public static void Main (string[] args) throws exception{
String str= "123";
Byte[] Plaintext=str.getbytes ("UTF8");
form an RSA key
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 class that uses the male hierarchy encryption
Cipher cipher=cipher.getinstance ("rsa/ecb/pkcs1padding");
SYSTEM.OUT.PRINTLN ("/n" +cipher.getprovider (). GetInfo ());

SYSTEM.OUT.PRINTLN ("/nstart 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 hierarchy to decrypt
System.out.println ("/nstart 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"));
}
}

(3) digital signature:
I. Several security requirements for data transmission in e-commerce

1. Confidentiality of data: used to prevent illegal users from entering the system and the illegal use of legitimate users of system resources; Protect data exchange between systems by encrypting sensitive data files, preventing third parties, other than receivers, from intercepting data and not obtaining its contents even if it is obtained. such as in electronic transactions, to avoid the attack of hackers to make credit card information lost.

2. Data integrity: To prevent illegal users of the exchange of data for unintentional or malicious modification, insertion, prevent the exchange of data loss and so on.

3. Non-repudiation of data: verification of the source of data and information to ensure that the data is issued by a legitimate user, preventing the data sender from denying it after the data has been sent, and preventing the receiving party from denying that the data was received and tampering with the data.

The above requirements correspond to firewall, encryption, digital signature, identity authentication and other technologies, but the key is digital signature technology.

ii. Meaning of digital signatures

A digital signature is an alphanumeric string that is processed by a one-way function to process the transmitted message to authenticate the source of the message and verify that the message has changed.

Iii. How to implement digital signature

There are many ways to implement digital signature, the current digital signature is more public key encryption technology, such as the cryptography based on RSA Date Security Company, the standards, digital Signature Algorithm, pretty, PGP (good Privacy). The 1994 American Institute of Standards and Technology published the digital Signature Standard (DSS), which makes public key cryptography widely used. &127; non-symmetric encryption algorithm used in public key cryptography system.  
IIII. Example

**
*digitalsignaturetest.java
*/
Import Java.security.Signature;
Import Java.security.KeyPairGenerator;
Import Java.security.KeyPair;
Import java.security.SignatureException;

/**
* Digital signature, use RSA private key to sign the message digest, and then use the public hierarchy to verify the test
*/
public class digitalsignaturetest{
public static void Main (string[] args) throws exception{
String str= "123";
Byte[] Plaintext=str.getbytes ("UTF8");
form RSA public Key pair
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");
Use a private hierarchy 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 ("/nsignature:");
System.out.println (New String (signature, "UTF8"));

Using the male hierarchy verification
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 e) {
System.out.println ("Signature failed");
}
}

(4) Digital certificate

I. Concept: a digital form of identification, similar to a passport or driver's license. A digital certificate is a digital credential that provides information about the identity of the entity and other support information. A digital certificate is issued by an authoritative authority that becomes a certification authority (CA). Since the digital certificate is issued by a certificate authority, the Authority guarantees the validity of the certificate information. In addition, digital certificates are only valid for a specific period of time.

   A digital certificate contains the public key of the entity identified in the certificate (that is, your public key is in your certificate), because the certificate matches the public key to a specific individual, and the authenticity of the certificate is guaranteed by the issuing authority (that is, you can convince people that your certificate is true), A digital certificate provides a solution for how to find the user's public key and to know if it is valid.

Ii. principles of digital certificates

The digital certificate adopts the public key system, which uses a pair of matching keys to encrypt and decrypt. Each user sets a specific private key (private key) that is only known to me, decrypts and signs it, and sets a public key (public key) to be shared with a group of users to encrypt and verify the signature. When a confidential file is sent, the sender encrypts the data with the receiver's public key, and the receiver decrypts it with its own private key, so that the information can arrive at the destination safely and without error. Using digital means to ensure that the encryption process is an irreversible process, that is, only with a private key to decrypt. In the public key cryptosystem, the RSA system is commonly used.

The user can also use their own private key to the information processing, because the key is only for me, so that the others can not generate files, also formed a digital signature. With digital signatures, you can confirm the following two points:

(1) The guarantee information is sent by the signer's own signature, the signer can not deny or difficult to deny;

(2) guarantee that the information has not been modified since it was issued, and that the documents issued are real documents.
Iii.java Instance operations:

KeyStore: The Java platform provides you with a keystore that serves as a repository for keys and certificates. Physically, the KeyStore is the default file called. KeyStore (there is 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.  

Self-certification using the tool Keytool:

1. Create KeyStore keytool-genkey-v-alias yourkeyname-keyalg RSA default in your own home directory (Windows system is c:/documents and settings/< your username >. keystore file), create a self-signed certificate with an RSA algorithm that generates an alias of Feiuserkey, and if-keystore mm is used, create a keystore mm file in the current directory to hold the key and certificate.

2. View Certificate: Keytool-list Lists all certificates for the KeyStore

You can also enter Keytool-help to view Help under DOS.


(5) Signature of Jar

     We've already talked about how to create our own certificates, and now we can start to understand how to sign the jar file, which is equivalent to a ZIP file in Java, allows you to package multiple Java class files into a file with a. jar extension, and then digitally sign the jar file. To prove its origin and authenticity. The receiver of the JAR file can determine whether the code is trusted based on the signature of the sender and can be confident that the content has not been tampered with before it is received. Also in the deployment, you can assign access to machine resources based on the identity of the signer by placing access control statements in the policy file. In this way, some of the applet's security inspection access is carried out. The

uses the Jarsigner tool to sign the jar file:

Now suppose we have a Test.jar file (which can be generated using the JAR command-line tool):

Jarsigner Test.jar Yourke Yname (Here we created the certificate for this alias), details can be entered Jarsigner view Help

To verify its authenticity: jarsigner-verify Test.jar (note that the jar has been modified, but not reduced, If the new content is added, it is also prompted, but the decrease is not prompted.

Using applets:: <applet code= "Test.class" archive= "Test.jar" width= "height=" ></applet> The browser will then prompt you: Allow this session-deny-always allow-view certificates, etc.

(6) Secure Sockets Layer (SSL secure Sockets layer) and Transport Layer Security (TLS Transport layer safety)

I. Introduction:

Secure Sockets Layer (SSL): A proposed open standard developed by Netscape Communications to establish secure communication channels to prevent important information such as credit card numbers from being intercepted.

The Secure Sockets Layer is an encryption system that is used on the server to ensure that the data transferred between the client and the server remains secure and secret. For the server and client to use SSL for secure communication, the server must have two things:

Key pair (key pair)--a key pair includes a public key and a private key. These two keys are used to encrypt and decrypt messages to ensure the privacy and confidentiality of transmission over the Internet.

Certificate (Certificate)--The certificate is used for authentication or identity verification. The certificate can be a self-signed (self-signed) certificate, or it can be a certificate issued (issued). The self-visa book is a certificate created for your own private Web network. A certificate is issued to you by a certification authority (certificate AUTHORITY,CA) or by a certificate signer.

SSL uses a secure handshake to initialize a secure connection between the client and the server. During the handshake, the client and server agree on the key and encryption methods they will use for this session. The client uses the server certificate to authenticate the server. After the handshake, SSL is used to encrypt and decrypt all information in the request and server responses for HTTPS (a unique protocol for combining SSL and HTTP), including:

The URL that the client is requesting.

The content of the submitted form.

Access authorization information (such as user name and password).

All data sent between the client and the server.

II. Summary:

Secure Sockets Layer and Transport Layer Security are the protocols used to build secure communication channels between the client and the server. It is also used to authenticate the server to the client and (less commonly used) to authenticate the client to the server. The protocol is more common in browser applications, and the lock at the bottom of the browser window indicates that SSL/TLS is valid:

1) Send a certificate from the server to the client when using SSL/TLS (typically using the https://URL) to make a request to the site. The client authenticates the server with this certificate using the installed public CA certificate, and then checks to see if the IP name (machine name) matches the machine the client is connected to.

2) The client generates random information that can be used to generate a conversation's private key (called the session key), and then encrypts it with the server's public key and sends it to the server. The server decrypts the message with its own private key, and then uses that random information to derive the same private session key as the client. RSA Public key algorithms are typically used at this stage.

3) The client and the server communicate using private session keys and private key algorithms (usually RC4). Use the message authentication code of another key to ensure the integrity of the message.

The Javax.net.ssl.SSLServerSocketFactory class in Java provides a good Sslserversocker factory class, and readers familiar with socket programming can practice. When you have finished writing the server side, enter the https://hostname on the browser: The port will be calling through SSL/TLS. Note: When running the server, run with the system environment variable: javax.net.ssl.keystore= keystore (when creating a certificate, the name should be hostname, such as localhost) and javax.net.ssl.keystorepassword= Your password.

Secure learning in Java (including encryption, digital signatures, certificates and certifications)

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.