Des encryption and decryption->java implementation

Source: Internet
Author: User
Tags decrypt

Des cryptographic decryption involves the Java class cipher

This class provides password functionality for encryption and decryption. It forms the core of the Java cryptographic Extension (JCE) framework .
To create a Cipher object, the application calls Cipher's GetInstance method and passes the name of the requested transformation to it. Optionally, you can specify the name of the provider.
A transform is a string that describes an operation (or a set of actions) performed on a given input to produce some kind of output. The conversion always includes the name of the cryptographic algorithm (for example, DES), followed by a feedback pattern and a fill scheme.
Conversions have the following form:
"Algorithm/pattern/fill" or "algorithm"
(in the latter case, the usage pattern and the fill scheme are specific to the provider's default value). For example, the following is a valid conversion:
Cipher C = cipher.getinstance ("des/cbc/pkcs5padding");
Using patterns such as CFB and OFB, Cipher blocks can encrypt data that is smaller than the actual block size of the Cipher. When requesting such a pattern, you can specify the number of bits to process at a time (optional): Add this number to the schema name, as shown in the "Des/cfb8/nopadding" and "des/ofb32/pkcs5padding" transformations. If the number is not specified, the provider-specific default value is used. (for example, the SUNJCE provider uses the default 64-bit for DES). Therefore, by using a 8-bit pattern such as CFB8 or OFB8, the Cipher block can be converted to a byte-oriented Cipher stream.


Secretkeyfactory

This class represents a factory for secret keys.
The key factory is used to convert the key (the Opaque encryption key of type key) to the key specification (the transparent representation of the underlying key material) and vice versa. Secret key Factory operates on Secret (symmetric) keys only.
The key factory is a duplex mode, which allows you to construct an opaque key object based on a given key specification (keying material), or to obtain the underlying key material for the key object in the appropriate format.
Application developers should refer to their provider documentation to find out the key specifications supported by the Generatesecret and Getkeyspec methods. For example, the DES secret key factory provided by the "SUNJCE" provider supports DESKEYSPEC as a transparent representation of the DES Key, and the secret key factory of the provider's Triple des Key supports desedekeyspec as the Triple des key. Transparent representation.

KeySpec

Public Interface Keyspec the (transparent) specification of the key content that makes up the encryption key.
If the key is stored on a hardware device, its specification can contain information that helps identify the key on the device.
A key can be specified using an algorithm-specific method or an encoding format independent of the algorithm (for example, ASN.1). For example, the DSA private key can be specified by its components x, p, Q, and G (see DSAPRIVATEKEYSPEC) or with its DER encoding (see PKCS8ENCODEDKEYSPEC).
This interface does not contain any methods or constants. It is used only to group all key specifications and provides type safety for them. All key specifications must implement this interface.

You can see the deskeyspec in the implementation class.

Secretkey

Public Interface Secretkeyextends key Secret (symmetric) keys.
This interface does not contain methods or constants. Its sole purpose is to group secret keys (and provide type safety for them).
The provider implementation of this interface must overwrite the Equals and Hashcode methods that inherit from Java.lang.Object so that the secret key comparison is based on the underlying key material rather than on the reference.
Implement the key for this interface in its encoded format (see GETFORMAT) to return the string raw and return the original key bytes as the result of the Getencoded method call. (The GetFormat and getencoded methods inherit from the Java.security.Key parent interface.) )
The secret key can be obtained using the following methods.

SecretKey secretKey = secretKeyFactory.generateSecret(keySpec);然后利用cipher的init方法即可初始化cipher对象,进而可以进行加密和解密操作。

Cipher.init (Cipher.encrypt_mode, Secretkey,new securerandom ());

Implementing Class Desencrypttools
 PackageCom.david.des;ImportJava.security.SecureRandom;ImportJava.security.spec.KeySpec;ImportJavax.crypto.Cipher;ImportJavax.crypto.SecretKey;ImportJavax.crypto.SecretKeyFactory;ImportJavax.crypto.spec.DESKeySpec;/** * Project Name: Ciphertest * Class Name: Aesencrypttools * Class Description: Des encryption and decryption algorithm * Creator: David * created: May 2, 2016 8:00: * Copyright (c) david-All rights reserved */ Public Final  class desencrypttools {    //encryption is considered des    Private Static FinalString algorithm ="DES";//Conversion format    Private Static FinalString transformation ="Des/ecb/pkcs5padding";//Use 8 byte 64-bit key to encrypt SRC    @SuppressWarnings("Unused") Public Static byte[]Encrypt(byte[] SRC,byte[]key) {Try{//EncryptionCipher Cipher = cipher.getinstance (transformation);            Secretkeyfactory secretkeyfactory = secretkeyfactory.getinstance (algorithm); KeySpec KeySpec =NewDeskeyspec (key);            Secretkey Secretkey = Secretkeyfactory.generatesecret (KeySpec); Cipher.init (Cipher.encrypt_mode, Secretkey,NewSecureRandom ());byte[] enmsgbytes = cipher.dofinal (src);returnEnmsgbytes; }Catch(Exception e)        {E.printstacktrace (); }return NULL; }//Use 8 byte 64-bit key to decrypt SRC    @SuppressWarnings("Unused") Public Static byte[]Decrypt(byte[] encryptbytes,byte[]key) {Try{//Decryption            //cipher decipher = cipher.getinstance ("des/cbc/pkcs5padding");Cipher decipher = cipher.getinstance (transformation);            Secretkeyfactory dedecretkeyfactory = secretkeyfactory.getinstance (algorithm); KeySpec Dekeyspec =NewDeskeyspec (key);            Secretkey Desecretkey = Dedecretkeyfactory.generatesecret (Dekeyspec); Decipher.init (Cipher.decrypt_mode, Desecretkey,NewSecureRandom ());byte[] demsgbytes = Decipher.dofinal (encryptbytes);returnDemsgbytes; }Catch(Exception e)        {E.printstacktrace (); }return NULL; }}
Test class
Package com.david.des; Public classdesmaintest {Private StaticString key ="12345678"; Public Static void Main(string[] args) throws exception{String msg ="Hello World." Hello, DES "; System. out. println ("before encryption:"+MSG);byte[] encryptbytes = Desencrypttools.encrypt (Msg.getbytes (), key.getbytes ()); System. out. println ("after encryption:"+NewString (encryptbytes));byte[] demsgbytes = Desencrypttools.decrypt (Encryptbytes,key.getbytes ()); System. out. println ("After decryption:"+NewString (demsgbytes)); }}
Test results

Summarize

Learn a bit of DES encryption and decryption algorithm!

Des encryption and decryption->java implementation

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.