Java encryption and digital certificates

Source: Internet
Author: User
Tags sha1 asymmetric encryption

Encryption and digital certificates


    • Encryption and digital certificates
    • Concept
      • Digital summary
      • Key encryption Technology
        • Private key (symmetric encryption)
        • Public key (Asymmetric encryption)
      • Digital signatures
      • Digital certificates
      • Standard
    • Tools
      • Keytool
    • Sample code
      • Encrypted decryption
        • KeyStore Preparation
        • Code
      • Signature Verification
        • Code


ConceptDigital summary

Digital Digest is the use of a single hash function will need to encrypt the plaintext "digest" into a string of fixed length (128-bit) ciphertext, this string of ciphertext is also known as digital fingerprint, hash value or digest value, it has a fixed length, and different plaintext abstracts into ciphertext, the results are always different, And the same plain text must be consistent in its abstract.

At present, the abstract algorithm is MD5, SHA1, SHA256 and so on. Where the MD5 series algorithm has been cracked, generally no longer recommended to use.
Md5:message-digest algorithm 5;
Sha1:secure Hash algorithm;

Key encryption Technology

Take the key to lock the door for example, the key we can be seen as a key, the door lock process can be regarded as the encryption process, lock the process used in the principle is the encryption algorithm

Private key (symmetric encryption)

Using the encryption method of single-key cryptosystem, the same key can be used as the encryption and decryption of information, which is called symmetric encryption, also known as single-key encryption. Its biggest advantage is the fast encryption/decryption speed, which is suitable for encrypting large data volumes, but key management is difficult.

Public key (Asymmetric encryption)

The encryption and decryption operations are performed separately using different keys, one public release, the public key, and the other by the user's own secret, which is the private key. The sender of the information is encrypted with a public key, and the recipient of the message is decrypted with a private key. The public key mechanism is flexible, but the encryption and decryption speed is much slower than symmetric key encryption.

Typical applications for asymmetric encryption are digital signatures, encryption keys.

Digital signatures

A digital signature is some data that is attached to a data unit, or a password transformation made to a data unit. This data or transformation allows the receiver of the data unit to confirm the source and data unit integrity of the data unit and to protect the data from forgery by the person (for example, the recipient).

Signature Process: When sending a delivery, the sender uses a hash function to generate a message digest from the message text, and then encrypts the digest with its own private key, and the encrypted digest is sent to the receiver as the message's digital signature and message.

verification Process: The receiver first uses the same hash function as the sender to calculate the message digest from the original message received, and then use the sender's public key to decrypt the message appended to the digital signature, if the two abstracts are the same, then the receiver can confirm that the digital signature is the sender.

Digital signature has two functions: one is to make sure that the message is actually signed by the sender, and the second is that the digital signature can determine the integrity of the message.

Digital signature is the application of asymmetric key encryption technology and digital Digest technology.

the following is the Ohm Society series book "Comic Code"

Digital certificates

Digital certificates provide a way to verify the identity of a communication entity on the Internet, which acts like a driver's license or an identity card in everyday life. It is issued by an authoritative CA that can be used on the Internet to identify each other. The simplest certificate contains a public key, a name, and a digital signature for the certificate authority, and in addition, the digital certificate is valid for a specific period of time.
A digital certificate is a file that is digitally signed by the certificate Authority that contains the public key owner information and the public key.

Standard

The digital certificate standard developed by the International Telecommunication Union (ITU-T).

Extension Files :

    • . CER,. CRT-typically used in binary der file format (same as. der), but also used for BASE64 encoded files (e.g.. Pem), saving the public key of the certificate
    • . P7B-the same as. p7c
    • . The P7C-PKCS#7 certificate format, which contains only the certificate and CRL list information, does not have a private key.
    • . PFX-Same as. P12
    • . The p12-pkcs#12 file, which contains the certificate (public key) and the private key (protected by a password), has a complete certificate chain letter
    • Certificate private key format supported by the Keytools Certificate tool for. Jks-java
ToolsKeytool

Keytool is a key and certificate management tool that stores keys and certificates in a so-called key warehouse.

    1. Key entity: Key (secret key) or private key and paired public key (with asymmetric encryption)
    2. Trusted certificate Entity (trusted certificate entries): Contains only the public key

Keytool Common commands:

command? Description
-genkey Generate key
-alias Specify a key alias
-keystore Specify the name of the KeyStore
-storepass Specify the password for the KeyStore
-validity Specify the certificate validity period
-keyalg Specifies the algorithm for the key, using the default DSA
-keysize Specify the key length
-keypass Specifies the password of the alias corresponding to the key ( the password for the private key )
-dname Specify certificate owner Information
-list Displaying certificate information in the KeyStore
-V Show certificate Details in KeyStore
-file Specify the path name of the certificate
-delete Delete an entry in the KeyStore
-printcert View the exported certificate information
-keypasswd Modify the specified entry password in the KeyStore
-export Export the certificate specified by the alias to a file
-import Import a signed digital certificate into the KeyStore

To modify a key alias:

Keytool-changealias-alias origalias -destalias newalias -keystore x.keystore
Enter KeyStore Password: keystore passphrase
Enter <ORIGALIAS> key password: Key cipher

Export Certificate
The private key entity in KeyStore does not contain a public key, which can be exported to a certificate and then obtained from the certificate:

Keytool-export-alias alias -keystore keystore -file PATH
Enter KeyStore Password: keystore passphrase

Sample codeEncrypted decryptionKeyStore Preparation

Use the Keytool tool to generate a key entity:

Keytool-genkey-alias Origalias-keystore X.keystore

Then you need to export the key entity to a certificate that contains the corresponding public key:

Keytool-export-alias Origalias-keystore X.keystore-file Origalias.cer

Code

public class Demo {private static string Storepath = "C:/users/hang/x.keystore";p rivate static string storepass = "123456" ;p rivate static string keyalias = "Origalias";p rivate static string keypass = "111111";p rivate static string certpath = "C :/users/hang/origalias.cer ";p rivate static string certpass =" 111111 ";p rivate static string signalg =" Sha256withrsa ";/* Throws exception: Keystoreexception, NoSuchAlgorithmException, Certificateexception, IOException, Nosuchproviderexception, Unrecoverablekeyexception, Nosuchpaddingexception, InvalidKeyException, Illegalblocksizeexception, Badpaddingexception, signatureexception*/public static void Main (string[] args) throws Exception {// The KeyStore instance is obtained according to the KeyStore type JKS keyStore keyStore = keystore.getinstance ("JKS", "SUN"); InputStream in = new FileInputStream (storepath ); Keystore.load (in, Storepass.tochararray ());//Remove the key pair from Keystone according to alias Privatekey Privatekey = Null;if ( Keystore.iskeyentry (Keyalias)) {Privatekey = (Privatekey) keystore.getkey (Keyalias, Keypass.tochararray ());} //Use the command to export the certificate of the key ' Keytool-export-alias origalias-keystore x.keystore-file origalias.jks '//Load certificate//certificate format X509 CERTIFICATEFAC    Tory certificatefactory = Certificatefactory.getinstance ("the");    Read the input stream of the certificate file InputStream certin = new FileInputStream (Certpath);    Certificate Certificate = certificatefactory.generatecertificate (certin);        Obtain the public key PublicKey PublicKey = Certificate.getpublickey () from the certificate;    SYSTEM.OUT.PRINTLN ("private key: \ r \ n" +privatekey);        SYSTEM.OUT.PRINTLN ("Public key: \ r \ n" +publickey); String Source = "The digital certificate standard developed by the International Telecommunication Union (ITU-T).    ";    Cipher Cipher = cipher.getinstance ("RSA");    Cipher.init (Cipher.encrypt_mode, Privatekey); Cipher.update ("Digital signature is the application of asymmetric key encryption technology and digital Digest technology.      \ r \ n ". GetBytes (" UTF-8 "));        byte[] Cipherbyte = cipher.dofinal (Source.getbytes ("UTF-8"));    Cipher.init (Cipher.decrypt_mode, PublicKey);    byte[] Decrpytbyte = cipher.dofinal (cipherbyte);    System.out.println (New String (Decrpytbyte, "UTF-8")); }}



Signature VerificationCode

The public and private keys in the above code are used in signature verification

Signature Signature = signature.getinstance (SIGNALG); signature.initsign (Privatekey); Signature.update ("Digital signature is Asymmetric key encryption technology and the application of Digital Digest technology. \ r \ n ". GetBytes (" UTF-8 ")) Signature.update (Source.getbytes (" UTF-8 ")); byte[] Signbyte = Signature.sign ();    Signature.initverify (certificate),//certificate and PublicKey can be signed signature.update ("Digital signature asymmetric key encryption technology and digital Digest technology application. \ r \ n ". GetBytes (" UTF-8 ")) Signature.update (Source.getbytes (" UTF-8 ")); Boolean verified = Signature.verify (signbyte) ; SYSTEM.OUT.PRINTLN (verified); * *




Java encryption and digital certificates

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.