Introduction to DES encryption
Des is a symmetric encryption algorithm, the so-called symmetric encryption algorithm is: Encryption and decryption using the same key algorithm. DES encryption algorithm from IBM's research, and later was formally adopted by the United States Government, and then began to spread widely, but in recent years less used, because Des uses 56-bit key, modern computing ability, within 24 hours can be cracked. However, in some simple applications, we can still use DES encryption algorithm, this article simply explained the Java implementation of DES.
Java implementation
Encryption
Code has a detailed explanation, not much nonsense.
Note: In the DES encryption and decryption process, the key length must be a multiple of 8
Copy Code code as follows:
Public byte[] Descrypto (byte[] datasource, String password) {
try{
SecureRandom random = new SecureRandom ();
Deskeyspec Deskey = new Deskeyspec (Password.getbytes ());
Create a key factory and then use it to convert Deskeyspec into
Secretkeyfactory keyfactory = secretkeyfactory.getinstance ("DES");
Secretkey SecureKey = Keyfactory.generatesecret (Deskey);
The Cipher object actually completes the encryption operation
Cipher Cipher = cipher.getinstance ("DES");
Initializing a Cipher object with a secret key
Cipher.init (Cipher.encrypt_mode, SecureKey, Random);
Now, get the data and encrypt it.
Formally perform cryptographic operations
Return Cipher.dofinal (DataSource);
}catch (Throwable e) {
E.printstacktrace ();
}
return null;
}
Decryption
Code has detailed comments, not much nonsense
Copy Code code as follows:
Private byte[] Decrypt (byte[] src, String password) throws Exception {
The DES algorithm requires a trustworthy random number source
SecureRandom random = new SecureRandom ();
Create a Deskeyspec object
Deskeyspec Deskey = new Deskeyspec (Password.getbytes ());
Create a key factory
Secretkeyfactory keyfactory = secretkeyfactory.getinstance ("DES");
Converts a Deskeyspec object to a Secretkey object
Secretkey SecureKey = Keyfactory.generatesecret (Deskey);
The Cipher object actually completes the decryption operation
Cipher Cipher = cipher.getinstance ("DES");
Initializing a Cipher object with a secret key
Cipher.init (Cipher.decrypt_mode, SecureKey, Random);
Real Start decryption operation
return cipher.dofinal (SRC);
}
test Scenario
For example, we can encrypt and decrypt a string using functions such as the above, or you can encrypt and decrypt a file, such as:
Copy Code code as follows:
Content to be encrypted
String str = "Test content";
Password, if the length is 8 multiples
String password = "12345678";
Byte[] result = Descrypto.descrypto (str.getbytes (), password);
SYSTEM.OUT.PRINTLN ("Encrypted content is:" +new String (Result));
Directly decrypt the above content
try {
byte[] Decryresult = des.decrypt (result, password);
SYSTEM.OUT.PRINTLN ("Encrypted content:" +new String (Decryresult));
catch (Exception E1) {
E1.printstacktrace ();
}