Use the DES algorithm to encrypt data in Java

Source: Internet
Author: User
Tags crypt

The JDK's javax. crypto package provides support for encryption and decryption of some common algorithms. This article describes how to use the DES algorithm to encrypt and decrypt data. Generally, the Data Encryption party uses the key to encrypt the data, and the data decryption party uses the same key to decrypt the data. This key is a binary file containing 8 bytes. the encryption and decryption party can be any development language.

You can use Java to generate a key and save it to a binary file as follows:

Public static void savebyteprivekey (string file ){

Try {
Keygenerator keygen = keygenerator. getinstance ("des ");

Secretkey key = keygen. generatekey (); // generate the Private Key

Fileoutputstream fop = new fileoutputstream (File );
FOP. Write (key. getencoded ());
FOP. Close ();
} Catch (exception E1 ){
E1.printstacktrace ();
}
}

Read the content from the key file to generate the key:

Public static secretkey getbyteprivekey (string file) throws exception {
File keyf = new file (File );
Long length = keyf. Length ();
Byte [] bytes = new byte [(INT) length];

Fileinputstream FCM = new fileinputstream (keyf );

// Read in the bytes
Int offset = 0;
Int numread = 0;

While (offset <bytes. Length & (numread = Fi. Read (bytes, offset, bytes. Length-offset)> = 0 ){
Offset + = numread;
}
Deskeyspec DKS = new deskeyspec (bytes );
Secretkeyfactory keyfactory = secretkeyfactory. getinstance ("des ");
Secretkey key = keyfactory. generatesecret (DKS );

Return key;
}

To encrypt a file, the operation on the file should be in the form of a stream. The encrypted data is a binary stream, which may not be mapped to any encoded string, therefore, the encrypted byte data should not be converted to a string during the operation. The code for encrypting a file into another file is as follows:

Public static void encryptfile (string plainfile, string encryptedfile, string Keyfile ){
Try {

Secretkey key = getbyteprivekey (Keyfile );
Cipher cipher = cipher. getinstance ("des ");
Cipher. INIT (Cipher. encrypt_mode, key );

Fileinputstream FCM = new fileinputstream (plainfile );
Fileoutputstream Fos = new fileoutputstream (encryptedfile );
Crypt (FCM, FOS, cipher );

FCM. Close ();
FOS. Close ();

} Catch (exception e ){
E. printstacktrace ();
}
}

Public static void crypt (inputstream in, outputstream out, cipher) throws ioexception,
Generalsecurityexception {
Int blocksize = cipher. getblocksize ();
Int outputsize = cipher. getoutputsize (blocksize );
System. Out. println ("blocksize" + blocksize + "outputsize" + outputsize );

Byte [] inbytes = new byte [blocksize];
Byte [] outbytes = new byte [outputsize];

Int inlength = 0;
Boolean more = true;
While (more ){
Inlength = in. Read (inbytes );
If (inlength = blocksize ){
Int outlength = cipher. Update (inbytes, 0, blocksize, outbytes );
Out. Write (outbytes, 0, outlength );
} Else {
More = false;
}
}
If (inlength> 0)
Outbytes = cipher. dofinal (inbytes, 0, inlength );
Else
Outbytes = cipher. dofinal ();
Out. Write (outbytes );
}

Similarly, in the decryption process, the data should also be in the stream mode:

Public static void decryptfile (string encryptedfile, string decryptedfile, string Keyfile ){
Try {

Secretkey key = getbyteprivekey (Keyfile );
Cipher cipher = cipher. getinstance ("des ");
Cipher. INIT (Cipher. decrypt_mode, key );

Fileinputstream FCM = new fileinputstream (encryptedfile );
Fileoutputstream Fos = new fileoutputstream (decryptedfile );
Crypt (FCM, FOS, cipher );

FCM. Close ();
FOS. Close ();

} Catch (exception e ){
E. printstacktrace ();
}

}

If you want to encrypt many strings and save them to a file, you should first save these strings to an intermediate file, and then read the intermediate file as a stream, encrypted File. I try

Encrypt a string and write it to the file. However, the decryption may fail.

The source code of the entire class is as follows:

Package com. Test. endecrypt;

Import java. Io. file;
Import java. Io. fileinputstream;
Import java. Io. fileoutputstream;
Import java. Io. ioexception;
Import java. Io. inputstream;
Import java. Io. outputstream;
Import java. Security. generalsecurityexception;
Import java. Security. nosuchalgorithmexception;

Import javax. crypto. cipher;
Import javax. crypto. keygenerator;
Import javax. crypto. secretkey;
Import javax. crypto. secretkeyfactory;
Import javax. crypto. spec. deskeyspec;

Public class descrypter {

Private Static string bytekeyfile = "D: // temp // bytekeyfile ";

Private Static string originalfile = "D: // temp // originalfile ";
Private Static string encryptedfile = "D: // temp // encryptedfile ";
Private Static string decryptedfile = "D: // temp // decryptedfile ";

Public static void main (string ARGs []) {

Savebyteprivekey (bytekeyfile );

Encryptfile (originalfile, encryptedfile, bytekeyfile );

Decryptfile (encryptedfile, decryptedfile, bytekeyfile );

String [] strings = {"the text to be encrypted", "aaaaaaaaaaa", "the text to be encrypted "};
Encryptstringstofile (strings, encryptedfile, bytekeyfile );
Decryptfile (encryptedfile, decryptedfile, bytekeyfile );
}

Public static void encryptfile (string plainfile, string encryptedfile, string Keyfile ){
Try {

Secretkey key = getbyteprivekey (Keyfile );
Cipher cipher = cipher. getinstance ("des ");
Cipher. INIT (Cipher. encrypt_mode, key );

Fileinputstream FCM = new fileinputstream (plainfile );
Fileoutputstream Fos = new fileoutputstream (encryptedfile );
Crypt (FCM, FOS, cipher );

FCM. Close ();
FOS. Close ();

} Catch (exception e ){
E. printstacktrace ();
}
}

Public static void encryptstringstofile (string [] strings, string encryptedfile, string Keyfile ){
Try {

Secretkey key = getbyteprivekey (Keyfile );
Cipher cipher = cipher. getinstance ("des ");
Cipher. INIT (Cipher. encrypt_mode, key );

Fileoutputstream Fos = new fileoutputstream (encryptedfile );
Crypt (strings, FOS, cipher );

FOS. Close ();

} Catch (exception e ){
E. printstacktrace ();
}

}

Public static void crypt (inputstream in, outputstream out, cipher) throws ioexception,
Generalsecurityexception {
Int blocksize = cipher. getblocksize ();
Int outputsize = cipher. getoutputsize (blocksize );
System. Out. println ("blocksize" + blocksize + "outputsize" + outputsize );

Byte [] inbytes = new byte [blocksize];
Byte [] outbytes = new byte [outputsize];

Int inlength = 0;
Boolean more = true;
While (more ){
Inlength = in. Read (inbytes );
If (inlength = blocksize ){
Int outlength = cipher. Update (inbytes, 0, blocksize, outbytes );
Out. Write (outbytes, 0, outlength );
} Else {
More = false;
}
}
If (inlength> 0)
Outbytes = cipher. dofinal (inbytes, 0, inlength );
Else
Outbytes = cipher. dofinal ();
Out. Write (outbytes );
}

Public static void crypt (string strings [], outputstream out, cipher) throws ioexception,
Generalsecurityexception {
For (string STR: strings ){
Byte [] encryptedbytes = encrypt (STR + "\ r \ n", "utf8", cipher );
Out. Write (encryptedbytes );
}

}

Public static byte [] encrypt (string in, string strencode, cipher) throws ioexception,
Generalsecurityexception {
Byte [] originalbytes = in. getbytes (strencode );
Byte [] encryptedbytes = cipher. dofinal (originalbytes );

Return encryptedbytes;
}

Public static void decryptfile (string encryptedfile, string decryptedfile, string Keyfile ){
Try {

Secretkey key = getbyteprivekey (Keyfile );
Cipher cipher = cipher. getinstance ("des ");
Cipher. INIT (Cipher. decrypt_mode, key );

Fileinputstream FCM = new fileinputstream (encryptedfile );
Fileoutputstream Fos = new fileoutputstream (decryptedfile );
Crypt (FCM, FOS, cipher );

FCM. Close ();
FOS. Close ();

} Catch (exception e ){
E. printstacktrace ();
}

}

Public static secretkey createsecretkey (string algorithm ){
// Declare the keygenerator object
Keygenerator keygen;
// Declare the key object
Secretkey secret ey = NULL;
Try {
// Return the keygenerator object that generates the secret key of the specified algorithm
Keygen = keygenerator. getinstance (algorithm );
// Generate a key
Required ey = keygen. generatekey ();
} Catch (nosuchalgorithmexception e ){
E. printstacktrace ();
}
// Return the key
Return another ey;
}

// Write the key to the file: generate a private key object and save it in the file
Public static void savebyteprivekey (string file ){

Try {
Keygenerator keygen = keygenerator. getinstance ("des ");

Secretkey key = keygen. generatekey (); // generate the Private Key

Fileoutputstream fop = new fileoutputstream (File );
FOP. Write (key. getencoded ());
FOP. Close ();
} Catch (exception E1 ){
E1.printstacktrace ();
}
}
Public static secretkey getbyteprivekey (string file) throws exception {
File keyf = new file (File );
Long length = keyf. Length ();
Byte [] bytes = new byte [(INT) length];

Fileinputstream FCM = new fileinputstream (keyf );

// Read in the bytes
Int offset = 0;
Int numread = 0;

While (offset <bytes. Length & (numread = Fi. Read (bytes, offset, bytes. Length-offset)> = 0 ){
Offset + = numread;
}
Deskeyspec DKS = new deskeyspec (bytes );
Secretkeyfactory keyfactory = secretkeyfactory. getinstance ("des ");
Secretkey key = keyfactory. generatesecret (DKS );

Return key;
}

}

Related Article

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.