Core applications of Java cryptographic extension (JCE) Framework

Source: Internet
Author: User

 

This article briefly introduces the core applications of the JCE framework!

Javax. crypto. CipherThis type provides the password function for encryption and decryption. It forms the core of the Java cryptographic extension (JCE) framework. To create a cipher object, the application callsgetInstanceMethod andConversionTo It. You can also specify the provider name (optional ).

ConversionIs a string that describes the operations (or a group of Operations) performed on a given input to generate an output ). The conversion always includes the name of the encryption algorithm (for example,Des), There may be a feedback mode and filling solution later.

Package thtf.com.cn. client;

Import java. Io. bytearrayoutputstream;
Import java. Io. fileinputstream;
Import java. Io. fileoutputstream;
Import java. Io. ioexception;
Import java. Io. inputstream;
Import java. Io. objectinputstream;
Import java. Io. objectoutputstream;
Import java. Io. outputstream;
Import java. Security. Key;
Import java. Security. securerandom;
Import java. Security. spec. algorithmparameterspec;
Import java. util. arraylist;
Import java. util. collection;
Import java. util. iterator;
Import java. util. properties;

Import javax. crypto. cipher;
Import javax. crypto. cipherinputstream;
Import javax. crypto. cipheroutputstream;
Import javax. crypto. keygenerator;
Import javax. crypto. secretkey;
Import javax. crypto. spec. ivparameterspec;

Import sun. Misc. base64decoder;
Import sun. Misc. base64encoder;

// JCE Application
Public class mainencrypt {

Static string Keyfile = "C:/key. xml ";

Static Properties property = getproperties ();

Cipher ecipher;

Cipher dcipher;

Private final string jdbcproperties_path = "socket_jdbc.properties ";

/**
* Generate a key.
*
*/
Public static void savepolicey (){
Try {

Keyfile = property. getproperty ("Keyfile ");
Securerandom sr = new securerandom ();
// Generate a keygenerator object for the selected DES algorithm
Keygenerator kg = keygenerator. getinstance ("des ");
Kg. INIT (SR );
Fileoutputstream Fos = new fileoutputstream (Keyfile );
Objectoutputstream OOS = new objectoutputstream (FOS );
// Generate the key
Secretkey key = kg. generatekey ();
Oos. writeobject (key );
Oos. Close ();
} Catch (exception e ){
E. printstacktrace ();
}
}

/**
* Obtain the key.
*
* @ Return
*/
Public static secretkey getkey (){
Secretkey Kp = NULL;
Try {
Keyfile = property. getproperty ("Keyfile ");
// String filename = "CONF/producer ey. xml ";
// Inputstream is =
// Desutil. Class. getclassloader (). getresourceasstream (Keyfile );
Inputstream is = new fileinputstream (Keyfile );
Objectinputstream OOS = new objectinputstream (is );
Kp = (secretkey) OOS. readobject ();
Oos. Close ();
} Catch (exception e ){
E. printstacktrace ();
}
Return KP;
}

/**
* Obtain the key based on the string.
*
* @ Param strkey
* Plaintext key
*/
Public void getkey (string strkey ){
Try {
Keygenerator _ generator = keygenerator. getinstance ("des ");
_ Generator. INIT (New securerandom (strkey. getbytes ()));
Key key = _ generator. generatekey ();
_ Generator = NULL;
} Catch (exception e ){
E. printstacktrace ();
}
}

Public static properties getproperties (){
Properties property = new properties ();
// Inputstream in = classloader
//. Getsystemresourceasstream ("socket_jdbc.properties ");
Inputstream in = mainencrypt. Class. getclassloader ()
. Getresourceasstream ("socket_jdbc.properties ");

Try {
Property. Load (in );
} Catch (ioexception e ){
E. printstacktrace ();
}
Return property;
}

Public mainencrypt (){

// Secretkey key = keyutil. getkey ();
Secretkey key = getkey ();
Byte [] IV = new byte [] {(byte) 0x8e, 0x12, 0x39, (byte) 0x9c, 0x07,
0x72, 0x6f, 0x5a };
Algorithmparameterspec paramspec = new ivparameterspec (IV );
Try {
Ecipher = cipher. getinstance ("des/CBC/pkcs5padding ");
Dcipher = cipher. getinstance ("des/CBC/pkcs5padding ");

// CBC requires an initialization Vector
Ecipher. INIT (Cipher. encrypt_mode, key, paramspec );
Dcipher. INIT (Cipher. decrypt_mode, key, paramspec );
} Catch (Java. Security. invalidalgorithmparameterexception e ){
} Catch (javax. crypto. nosuchpaddingexception e ){
} Catch (Java. Security. nosuchalgorithmexception e ){
} Catch (Java. Security. invalidkeyexception e ){
}
}

Public byte [] getbytes (inputstream is) throws exception {
Byte [] DATA = NULL;

Collection chunks = new arraylist ();
Byte [] buffer = new byte [1024*1000];
Int READ =-1;
Int size = 0;

While (read = is. Read (buffer ))! =-1 ){
If (read> 0 ){
Byte [] chunk = new byte [read];
System. arraycopy (buffer, 0, Chunk, 0, read );
Chunks. Add (chunk );
Size + = Chunk. length;
}
}

If (size> 0 ){
Bytearrayoutputstream Bos = NULL;
Try {
Bos = new bytearrayoutputstream (size );
For (iterator itr = chunks. iterator (); itr. hasnext ();){
Byte [] chunk = (byte []) itr. Next ();
Bos. Write (chunk );
}
Data = Bos. tobytearray ();
} Finally {
If (Bos! = NULL ){
Bos. Close ();
}
}
}
Return data;
}

/**
* Encrypted string plaintext input and string ciphertext output
*
* @ Param strming
* @ Return
*/
Public String getencstring (string strming ){
If (strming = NULL ){
Strming = "";
}
Byte [] bytemi = NULL;
Byte [] byteming = NULL;
String strmi = "";
Base64encoder base64en = new base64encoder ();
Try {
Byteming = strming. getbytes ("utf8 ");
Bytemi = This. getenccode (byteming );
Strmi = base64en. encode (bytemi );
} Catch (exception e ){
E. printstacktrace ();
} Finally {
Base64en = NULL;
Byteming = NULL;
Bytemi = NULL;
}
Return strmi;
}

/**
* Decryption is input in string ciphertext and output in string plaintext.
*
* @ Param strmi
* @ Return
*/
Public String getdesstring (string strmi ){
// Byte [] bytemi = NULL;
// String strming = "";
// Bytearrayoutputstream baos = new bytearrayoutputstream ();
//
// Try {
// Bytemi = strmi. getbytes ("utf8 ");
//
// This. decrypt (New bytearrayinputstream (bytemi), baos );
// Strming = new string (baos. tobytearray ());
//} Catch (exception e ){
// E. printstacktrace ();
//} Finally {
//}
// Return strming;
Base64decoder base64de = new base64decoder ();
Byte [] byteming = NULL;
Byte [] bytemi = NULL;
String strming = "";
Try {
Bytemi = base64de. decodebuffer (strmi );
Byteming = This. getdescode (bytemi );
Strming = new string (byteming, "utf8 ");
} Catch (exception e ){
E. printstacktrace ();
} Finally {
Base64de = NULL;
Byteming = NULL;
Bytemi = NULL;
}
Return strming;
}

/**
* Encryption is input in byte [] plaintext, and byte [] ciphertext is output.
*
* @ Param bytes
* @ Return
*/
Public byte [] getenccode (byte [] bytes ){
Byte [] bytefina = NULL;
Cipher cipher;
Try {
// Cipher = cipher. getinstance ("des ");
// Cipher. INIT (Cipher. encrypt_mode, key ,);
// Bytefina = cipher. dofinal (bytes );
Bytefina = ecipher. dofinal (bytes );
} Catch (exception e ){
E. printstacktrace ();
} Finally {
Cipher = NULL;
}
Return bytefina;
}

/**
* Decryption is input in byte [] ciphertext and output in byte [] plaintext
*
* @ Param byted
* @ Return
*/
Public byte [] getdescode (byte [] byted ){
Cipher cipher;
Byte [] bytefina = NULL;
Try {
// Cipher = cipher. getinstance ("des ");
// Cipher. INIT (Cipher. decrypt_mode, key );
// Bytefina = cipher. dofinal (byted );
Bytefina = dcipher. dofinal (byted );
} Catch (exception e ){
E. printstacktrace ();
} Finally {
Cipher = NULL;
}
Return bytefina;

}

// Buffer used to transport the bytes from one stream to another
Byte [] Buf = new byte [1, 1024];

Public void encrypt (inputstream in, outputstream out ){
Try {
// Bytes written to out will be encrypted
Out = new cipheroutputstream (Out, ecipher );

// Read in the cleartext bytes and write to out to encrypt
Int numread = 0;
While (numread = in. Read (BUF)> = 0 ){
Out. Write (BUF, 0, numread );
}

// Close the stream outside.
// Out. Close ();
} Catch (Java. Io. ioexception e ){
}
}

Public void decrypt (inputstream in, outputstream out ){
Try {
// Bytes read from in will be decrypted
In = new cipherinputstream (in, dcipher );

// Read in the decrypted bytes and write the cleartext to out
Int numread = 0;
While (numread = in. Read (BUF)> = 0 ){
Out. Write (BUF, 0, numread );
}
// Out. Flush ();
// Close the stream outside.
// Out. Close ();
} Catch (Java. Io. ioexception e ){
}
}

/**
* @ Param ARGs
*/
Public static void main (string [] ARGs ){
// Todo auto-generated method stub

Try {

Mainencrypt encrypter = new mainencrypt ();

// Encrypt
// Encrypter. Encrypt (New fileinputstream ("C:/photo.jpg "),
// New fileoutputstream ("C:/photo_enc.jpg "));
// Decrypt
Encrypter. decrypt (New fileinputstream ("C:/photo_enc.jpg "),
New fileoutputstream ("C:/photo_des.jpg "));

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

}

}
 

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.