Current location - Quotes Website - Signature design - How to realize simple string encryption and decryption with JAVA?
How to realize simple string encryption and decryption with JAVA?
Java encrypted strings can use des encryption algorithm. Examples are as follows:

Packaging test;

Import java.io.fileinputstream;

Import java.io.fileoutputstream;

Import java.io.ioexception;

Import java.io.objectinputstream;

Import java.io.objectoutputstream;

Import java.security. *;

Import javax.crypto.cipher;

Import javax.crypto.keygenerator;

Import javax.crypto.secret key;

/**

* Encryption and decryption

*

* @ author shy.qiu

* @ from/qiushuyfm

*/

Public class password test {

/**

* MD5 encryption.

*

* @param info

* Information to be encrypted

* @ Returns a string encrypted string.

*/

Public string encryptToMD5 (string information) (

byte[]digesta = null;

Try {

//Get the message summary of md5.

message digest alga = message digest . getinstance(" MD5 ");

//Add information to summarize.

alga . update(info . getbytes());

//Get the summary

digesta = alga . digest();

} catch(nosuch algorithm exception e){

e . printstacktrace();

}

//Convert the summary into a string

string RS = byte 2 hex(digesta);

Return RS;

}

/**

* SHA encryption.

*

* @param info

* Information to be encrypted

* @ Returns a string encrypted string.

*/

Public string encryptToSHA (string information)

byte[]digesta = null;

Try {

//Get the message digest of SHA- 1

message digest alga = message digest . getinstance(" SHA- 1 ");

//Add information to summarize.

alga . update(info . getbytes());

//Get the summary

digesta = alga . digest();

} catch(nosuch algorithm exception e){

e . printstacktrace();

}

//Convert the summary into a string

string RS = byte 2 hex(digesta);

Return RS;

}

// //////////////////////////////////////////////////////////////////////////

/**

* create a key

*

* @param algorithm

* encryption algorithm, available DES, DESede, Blowfish.

* @return SecretKey secret (symmetric) key

*/

Public SecretKey keyCreate a SecretKey (string algorithm) (

//Declare the KeyGenerator object

KeyGenerator keygen

//Declare the key object

SecretKey deskey = null

Try {

//Returns the KeyGenerator object that generates the key for the specified algorithm.

Keygen = keygenerator.getinstance (algorithm);

//Generate a key

deskey = keygen . generate key();

} catch(nosuch algorithm exception e){

e . printstacktrace();

}

//Return the key

Return to deskey

}

/**

* DES encryption according to the key.

*

* @param key

* key

* @param info

* Information to be encrypted

* @ returns string encryption information.

*/

Public string encrypto des(secret key, string information) (

//Define the encryption algorithm, which can be DES, DES, DESede, Blowfish.

String Algorithm = " DES

//Encrypted Random Number Generator (RNG), (no need to write)

SecureRandom Sr = new SecureRandom();

//Define the ciphertext to be generated.

Byte [] Password Byte = empty;

Try {

//Get the encryption/decryption program

Cipher c1= cipher.getinstance (algorithm);

//Initializes the Cipher object with the specified key and mode.

//Parameters: (encrypt _ mode, decrypt _ mode, wrap _ mode, unwrap _ mode)

C 1.init (password. ENCRYPT_MODE,key,Sr);

//encode the content to be encrypted,

cipher byte = c 1 . do final(info . getbytes());

Catch (exception e) {

e . printstacktrace();

}

//Returns the ciphertext in hexadecimal form.

Returns byte2hex (password byte);

}

/**

* DES decrypts according to the key.

*

* @param key

* key

* @param sInfo

* the ciphertext to be decrypted

* @return String returns the decrypted information.

*/

Common string decryptByDES(SecretKey key, string sinfo) (

//Define the encryption algorithm,

String Algorithm = " DES

//Encrypted Random Number Generator (RNG)

SecureRandom Sr = new SecureRandom();

Byte [] Password Byte = empty;

Try {

//Get the encryption/decryption program

Cipher c1= cipher.getinstance (algorithm);

//Initializes the Cipher object with the specified key and mode.

C 1.init (password. DECRYPT_MODE,key,Sr);

//Encode the content to be decrypted.

cipher byte = c 1 . do final(hex 2 byte(sInfo));

Catch (exception e) {

e . printstacktrace();

}

//Returns byte2hex (password byte);

Returns a new string (cipher byte);

}

// /////////////////////////////////////////////////////////////////////////////

/**

* Create a key group and put the public key and private key into the specified file.

*

* default in mykeys.bat file.

*/

public void createPairKey() {

Try {

//A key pair generator according to a specific algorithm.

KeyPairGenerator keygen = KeyPairGenerator . getinstance(" DSA ");

//Encrypted Random Number Generator (RNG)

SecureRandom random = new SecureRandom();

//Re-seed this random object.

random . setseed( 1000);

//Initializes the key pair generator to determine the key size using the given random source (and default parameter set).

Keygen.initialize(5 12, random); //keygen . initialize(5 12);

//Generate a key group

key pair keys = keygen . generatekeypair();

//Get the public key

public key pubkey = keys . getpublic();

//Get the private key

private key prikey = keys . get private();

//Write the public key and private key into the document.

doObjToFile("mykeys.bat ",new Object[] { prikey,pubkey });

} catch(nosuch algorithm exception e){

e . printstacktrace();

}

}

/**

* use the private key to sign the information, and put the signed information into the specified file.

*

* @param info

* Information that needs to be signed

* @param signal file

* Deposited documents

*/

public void sign to info(String info,String signfile) {

//Read the private key from the file

private key my prikey =(private key)getObjFromFile(" mykeys . bat ", 1);

//Read the public key from the file

public key my pubkey =(public key)getObjFromFile(" mykeys . bat ",2);

Try {

The signature object can be used to generate and verify digital signatures.

signature signet = signature . getinstance(" DSA ");

//Initialize the private key used to sign the signature.

signet . init sign(my prikey);

//Update the data to be signed or verified by bytes.

signet . update(info . getbytes());

//Sign or verify the signatures of all update bytes and return the signatures.

byte[]signed = signet . sign();

//Put the digital signature, public key and information into the file.

doObjToFile(signfile,new Object[] { signed,mypubkey,info });

Catch (exception e) {

e . printstacktrace();

}

}

/**

* Read the digital signature file and verify the legality of the information according to the public key, signature and information.

*

* @ Returns true verification success and false verification failure.

*/

Public boolean validateSign (string signature file) (

//Read the public key

public key my pubkey =(public key)getObjFromFile(sign file,2);

//Read the signature

byte[]signed =(byte[])getObjFromFile(sign file, 1);

//Read information

String info =(String)getObjFromFile(sign file,3);

Try {

//Initialize the signature object and verify it with the public key and signature.

signature signetcheck = signature . getinstance(" DSA ");

//Initializes the public key of the verification signature.

signetcheck . init verify(my pubkey);

//Update the data to be signed or verified with the specified byte array.

signetcheck . update(info . getbytes());

system . out . println(info);

//Verify the incoming signature

Returns signetcheck.verify (signed);

Catch (exception e) {

e . printstacktrace();

Returns false

}

}

/**

* Convert binary to 16 binary string.

*

* @param b

* Binary byte array

* @ Returns a string

*/

Common string byte2hex(byte[] b) {

String hs =

String stmp =

for(int n = 0; N<b. length; n++) {

stmp =(Java . lang . integer . tohexstring(b[n]& amp; 0x ff));

if (stmp.length() == 1) {

hs = hs+" 0 "+stmp;

} Otherwise {

hs = hs+stmp;

}

}

Returns hs.touppercase ();

}

/**

* Hexadecimal string is converted into binary.

*

* @param hex

* @ Return

*/

Public byte[] hex2byte (string hexadecimal) {

Byte[] ret = new byte [8];

byte[]tmp = hex . getbytes();

for(int I = 0; I<8; i++) {

ret[i] = uniteBytes(tmp[i * 2],tmp[I * 2+ 1]);

}

Return to ret

}

/**

* combine two ASCII characters into one byte; Such as "ef"-> 0xef

*

* @param src0

* bytes

* @param src 1

* bytes

* @ returns bytes

*/

Common static byte unit byte (byte src0, byte src 1) {

byte _ B0 = byte . decode(" 0x "+new String(new byte[]{ src 0 }))

. byte value();

_b0 = (bytes) (_ B0 < < lt4);

byte _ b 1 = byte . decode(" 0x "+new String(new byte[]{ src 1 }))

. byte value();

byte ret =(byte)(_ B0 ^ _ b 1);

Return to ret

}

/**

* Write the specified object to the specified file.

*

* @param file

* Specify the file to write.

* @param objs

* The object to be written.

*/

Public void doObjToFile (string file, Object[] objs) {

ObjectOutputStream oos = null

Try {

file output stream fos = new file output stream(file);

Oos = new object output stream (fos);

for(int I = 0; I & ltobjs.lengthi++) {

OOS . writeobject(objs[I]);

}

Catch (exception e) {

e . printstacktrace();

} Finally {

Try {

OOS . close();

} catch (IOException e) {

e . printstacktrace();

}

}

}

/**

* Returns the object at the specified location in the file.

*

* @param file

* Specify the file

* @param i

* Starting from 1

* @ Return

*/

Common object getObjFromFile(String file, int i) {

ObjectInputStream ois = null

Object obj = null

Try {

file inputstream fis = new file inputstream(file);

Ois = new objectinputstream (fis);

for(int j = 0; J< me; j++) {

obj = ois . read object();

}

Catch (exception e) {

e . printstacktrace();

} Finally {

Try {

ois . close();

} catch (IOException e) {

e . printstacktrace();

}

}

Return to obj

}

/**

* testing

*

* @param args

*/

Public static void main(String[] args) {

CryptTest jiami = new CryptTest();

//Execute MD5 encryption "Hello world!"

System.out.println("Hello across MD5: "+jiami.encryptomd5 ("hello "));

//Generate a key of DES algorithm.

secret key key = jiami . create SecretKey(" DES ");

//Encrypt the message "Hello world!" Use the key.

string str 1 = jiami . encrypto des(key,“Hello”);

System.out.println ("Encrypt information hello is with des"+str1);

//Decrypt with this key.

string str 2 = jiami . decryptbydes(key,str 1);

System.out.println ("after decryption:"+str 2);

//Create a public key and a private key.

jiami . createpairkey();

//Yes, hello world! Sign with a private key

jiami.signToInfo("Hello "," my sign . bat ");

//Verify the signature with the public key.

if(jiami . validate sign(" my sign . bat "){

System.out.println ("Success!" );

} Otherwise {

System.out.println("Fail!" );

}

}

}