Java common tool Class des and Base64 encryption and decryption class _java

Source: Internet
Author: User
Tags base64 decrypt generator sha1 encryption

One, des encryption and decryption

Package com.itjh.javaUtil;
Import java.io.UnsupportedEncodingException;
Import java.security.InvalidKeyException;
Import java.security.NoSuchAlgorithmException;
Import Java.security.SecureRandom;

Import java.security.spec.InvalidKeySpecException;
Import javax.crypto.BadPaddingException;
Import Javax.crypto.Cipher;
Import javax.crypto.IllegalBlockSizeException;
Import Javax.crypto.KeyGenerator;
Import javax.crypto.NoSuchPaddingException;
Import Javax.crypto.SecretKey;
Import Javax.crypto.SecretKeyFactory;

Import Javax.crypto.spec.DESKeySpec;
 /** * des encryption and decryption. * * @author Song Lijun * @date July 03, 2014/public class Desutil {/** security key/private String KeyData = "Abcdefghijklmno

	Pqrstwxyzabcdefghijklmnopqrstwxyz0123456789-_. ";
	 /** * Function: Construction * * @author Song Lijun * @date July 03, 2014/Public Desutil () {}/** * Features: Construction * * @author Song Lijun
	* @date July 03, 2014 * @param keyData * key/Public desutil (String key) {this.keydata = key;
	 /** * Features: Encryption (UTF-8)* * @author Song Lijun * @date July 03, 2014 * @param source String * @param charSet * encoded * @return String * @th  Rows Unsupportedencodingexception * Encoding exception/public string encrypt (String source) throws Unsupportedencodingexception
	{return encrypt (source, "UTF-8"); /** * * Features: Decryption (UTF-8) * * @author Song Lijun * @date July 03, 2014 * @param encrypteddata * Encrypted String * @retu RN String * @throws unsupportedencodingexception * Encoding exception/public string decrypt (String EncryptedData) throws U
	Nsupportedencodingexception {return decrypt (EncryptedData, "UTF-8"); /** * Features: Encryption * @author Song Lijun * @date July 03, 2014 * @param source * Source String * @param charSet * code * @r 
			Eturn String * @throws unsupportedencodingexception * Encoding exception/public string encrypt (string source, String charSet)
		Throws Unsupportedencodingexception {String encrypt = null;
		byte[] ret = Encrypt (Source.getbytes (charSet)); Encrypt = new String (Base64.encode (ret));
	return encrypt; /** * * Function: Decryption * * @author Song Lijun * @date July 03, 2014 * @param encrypteddata * Encrypted String * @param charse T * code * @return String * @throws unsupportedencodingexception * Encoding exception/public string decrypt (string encrypt
		Eddata, String charSet) throws Unsupportedencodingexception {string descrypteddata = null;
		byte[] ret = Descrypt (Base64.decode (Encrypteddata.tochararray ()));
		Descrypteddata = new String (ret, charSet);
	return descrypteddata; /** * Encrypted data encrypts raw data with generated key * * @param primarydata * RAW data * @return byte[] * @author Song Lijun * @date July 2014 0

		3rd * * Private byte[] Encrypt (byte[] primarydata) {/** obtain security key/byte rawkeydata[] = Getkey ();

		The/** des algorithm requires a trustworthy random number source/securerandom sr = new SecureRandom ();
		/** uses raw key data to create a Deskeyspec object/deskeyspec DKs = null;
		try {dks = new Deskeyspec (Keydata.getbytes ());
		catch (InvalidKeyException e) {e.printstacktrace (); /** Create a key factory * * SecreTkeyfactory keyfactory = null;
		try {keyfactory = secretkeyfactory.getinstance ("DES");
		catch (NoSuchAlgorithmException e) {e.printstacktrace ();
		/** convert Deskeyspec to a Secretkey object with a key factory * * Secretkey key = null;
		try {key = Keyfactory.generatesecret (DKS);
		catch (Invalidkeyspecexception e) {e.printstacktrace ();
		The/** Cipher object actually completes the cryptographic operation */Cipher Cipher = null;
		try {cipher = cipher.getinstance ("DES");
		catch (NoSuchAlgorithmException e) {e.printstacktrace ();
		catch (Nosuchpaddingexception e) {e.printstacktrace ();
		/** initialize cipher object with key/try {Cipher.init (Cipher.encrypt_mode, Key, SR);
		catch (InvalidKeyException e) {e.printstacktrace ();
		/** official execution of cryptographic operations */byte encrypteddata[] = null;
		try {EncryptedData = cipher.dofinal (Primarydata);
		catch (IllegalStateException e) {e.printstacktrace ();
		catch (Illegalblocksizeexception e) {e.printstacktrace (); catch (Badpaddingexception e) {e.printstAcktrace ();
	/** Return Encrypted data * * ENCRYPTEDDATA; /** * Data decrypted with key * * @param EncryptedData * Encrypted data * @return byte[] * @author Song Lijun * @date July 03, 2014 *

		/private byte[] Descrypt (byte[] encrypteddata) {/** des algorithm requires a trustworthy random number source/securerandom sr = new SecureRandom ();

		/** obtains the security key * */byte rawkeydata[] = Getkey ();
		/** uses raw key data to create a Deskeyspec object/deskeyspec DKs = null;
		try {dks = new Deskeyspec (Keydata.getbytes ());
		catch (InvalidKeyException e) {e.printstacktrace ();
		/** Create a key factory */secretkeyfactory keyfactory = null;
		try {keyfactory = secretkeyfactory.getinstance ("DES");
		catch (NoSuchAlgorithmException e) {e.printstacktrace ();
		/** convert Deskeyspec to a Secretkey object with a key factory * * Secretkey key = null;
		try {key = Keyfactory.generatesecret (DKS);
		catch (Invalidkeyspecexception e) {e.printstacktrace ();
		The/** Cipher object actually completes the cryptographic operation */Cipher Cipher = null;
		try {cipher = cipher.getinstance ("DES"); } CatCH (nosuchalgorithmexception e) {e.printstacktrace ();
		catch (Nosuchpaddingexception e) {e.printstacktrace ();
		/** initialize cipher object with key/try {Cipher.init (Cipher.decrypt_mode, Key, SR);
		catch (InvalidKeyException e) {e.printstacktrace ();
		/** Official decryption operation */byte decrypteddata[] = null;
		try {decrypteddata = cipher.dofinal (EncryptedData);
		catch (IllegalStateException e) {e.printstacktrace ();
		catch (Illegalblocksizeexception e) {e.printstacktrace ();
		catch (Badpaddingexception e) {e.printstacktrace ();
	return decrypteddata;
	 /** * Obtaining a security key this method is invalidated because each key generation is different, causing the decryption encryption key to be different, resulting in the given final block not * properly padded error.
		* * @return byte array * @author Song Lijun * @date July 03, 2014/Private byte[] Getkey () {/** des algorithm requires a trustworthy random number source.

		securerandom sr = new SecureRandom ();
		/** generates a key generator object for our selected des algorithm */keygenerator kg = null;
		try {kg = keygenerator.getinstance ("DES"); catch (nosuchalgorithmexceptIon e) {e.printstacktrace ();

		} kg.init (SR);

		/** Generate Key Tool class * * Secretkey key = Kg.generatekey ();

		/** generate key byte array */byte rawkeydata[] = key.getencoded ();
	return rawkeydata; }

}

Two, Base64 encryption and decryption

Package com.itjh.javaUtil;

Import java.io.*;
 /** * BASE64 encoding and decoding. * * @author Song Lijun * @date July 03, 2014/public class Base64 {public Base64 () {}/** * Feature: Encoded String * * @autho
		R Song Lijun * @date July 03, 2014 * @param data * Source String * @return string/public static string encode (string data) {
	return new String (Encode (Data.getbytes ())); /** * Function: Decoding String * * @author Song Lijun * @date July 03, 2014 * @param data * Source String * @return String */Public
	static string decode (string data) {return new string (Decode (Data.tochararray ())); /** * Function: Encoding byte[] * * @author Song Lijun * @date July 03, 2014 * @param data * source * @return char[] * * Public
		Static char[] Encode (byte[] data {char[] out = new char[((Data.length + 2)/3) * 4];
			for (int i = 0, index = 0 I < data.length i + = 3, index + + 4) {Boolean quad = false;

			Boolean trip = false;
			int val = (0xFF & (int) data[i]);
			Val <<= 8;
	if ((i + 1) < Data.length) {			Val |= (0xFF & (int) Data[i + 1]);
			Trip = true;
			} Val <<= 8;
				if ((i + 2) < Data.length) {val |= (0xFF & (int) Data[i + 2]);
			Quad = true; } Out[index + 3] = alphabet[(quad?)
			(Val & 0x3F): 64)];
			Val >>= 6; Out[index + 2] = alphabet[(trip?)
			(Val & 0x3F): 64)];
			Val >>= 6;
			Out[index + 1] = alphabet[val & 0x3F];
			Val >>= 6;
		Out[index + 0] = alphabet[val & 0x3F];
	} return out;  /** * Function: Decoding * * @author Song Lijun * @date July 03, 2014 * @param data * encoded character array * @return byte[] * * Public
		Static byte[] Decode (char[] Data {int templen = data.length; for (int ix = 0; ix < data.length; ix++) {if ((Data[ix) > 255) | | codes[data[ix]] < 0) {--templen;/IG
		Nore non-valid chars and padding}//Calculate required Length://--3 bytes for every 4 valid base64 chars --plus 2 bytes if there are 3 extra base64 chars,//or plus 1 byte if there arE 2 extra.
		int len = (TEMPLEN/4) * 3;
		if ((templen% 4) = = 3) {len + 2;

		} if ((templen% 4) = = 2) {len + + 1;

		} byte[] out = new Byte[len]; int shift = 0; # of excess bits stored in accum int accum = 0;

		Excess bits int index = 0; We through the entire array (not using the ' Templen ' value) for (int ix = 0; ix < data.length; ix++) {i NT value = (Data[ix] > 255)?

			-1:codes[data[ix]]; if (value >= 0) {//Skip over Non-code accum <<= 6;//bits shift up by 6 per time thru SHIFT + 6; Loop, with the new bits being put in accum |= value;
				At the bottom.  if (Shift >= 8) {//whenever there are 8 or more shifted in, shift = 8;//write them out (from the top, leaving
					Any out[index++] =//Excess in the bottom for next iteration. (byte)
				((Accum >> shift) & 0xff);
		}}//If there is still something wrong we just have to throw up now! if (index!= out.length){throw new Error ("miscalculated data length (wrote" + Index + "instead of" + Out.length + ")");
	} return out; /** * Function: Encoding file * * @author Song Lijun * @date July 03, 2014 * @param file * source file/public static void encode (Fi
		Le file) throws IOException {if (!file.exists ()) {system.exit (0);
			else {byte[] decoded = readbytes (file);
			char[] encoded = encode (decoded);
		WriteChars (file, encoded);
	} file = null;
	 /** * Function: Decode file. * * @author Song Lijun * @date July 03, 2014 * @param file * source file * @throws ioexception/public static void decode (
		File file) throws IOException {if (!file.exists ()) {system.exit (0);
			else {char[] encoded = readChars (file);
			Byte[] decoded = decode (encoded);
		Writebytes (file, decoded);
	} file = null; ////code characters for values 0..63//private static char[] Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLM

	Nopqrstuvwxyz0123456789+/= ". ToCharArray (); Lookup Table for converting base64 characters to value in range 0..63//private static byte[] codes = new byte[256];
			static {for (int i = 0; i < 256 i++) {Codes[i] =-1;
		Loggerutil.debug (i + "&" + Codes[i] + "");
			for (int i = ' a '; I <= ' Z '; i++) {Codes[i] = (byte) (i-' a ');
		Loggerutil.debug (i + "&" + Codes[i] + "");
			for (int i = ' a '; I <= ' z '; i++) {Codes[i] = (byte) (num + i-' a ');
		Loggerutil.debug (i + "&" + Codes[i] + "");
			for (int i = ' 0 '; I <= ' 9 '; i++) {Codes[i] = (byte) (+ I-' 0 ');
		Loggerutil.debug (i + "&" + Codes[i] + "");
		} codes[' + '] = 62;
	codes['/'] = 63; private static byte[] readbytes (file file) throws IOException {Bytearrayoutputstream BAOs = new Bytearrayoutputstre
		AM ();
		Byte[] B = null;
		InputStream FIS = null;
		InputStream is = null;
			try {fis = new FileInputStream (file);
			is = new Bufferedinputstream (FIS);
			int count = 0; byte[] buf = new byte[16384];
				while (count = Is.read (BUF))!=-1) {if (Count > 0) {baos.write (buf, 0, Count);

		} B = Baos.tobytearray ();
				Finally {try {if (FIS!= null) fis.close ();
				if (is!= null) is.close ();
			if (BAOs!= null) baos.close ();
			catch (Exception e) {System.out.println (e);
	} return B;
		private static char[] ReadChars (file file) throws IOException {Chararraywriter CAW = new Chararraywriter ();
		Reader FR = null;
		Reader in = null;
			try {fr = new FileReader (file);
			in = new BufferedReader (FR);
			int count = 0;
			char[] buf = new char[16384];
				while (count = In.read (BUF))!=-1) {if (Count > 0) {caw.write (buf, 0, Count);
				Finally {try {if (CAW!= null) caw.close ();
				if (in!= null) in.close ();
			if (FR!= null) fr.close ();
			catch (Exception e) {System.out.println (e);
	} return Caw.tochararray (); } private static voidWritebytes (file file, byte[] data) throws IOException {OutputStream fos = null;
		OutputStream OS = null;
			try {fos = new FileOutputStream (file);
			OS = new Bufferedoutputstream (FOS);

		Os.write (data);
				Finally {try {if (OS!= null) os.close ();
			if (FOS!= null) fos.close ();
			catch (Exception e) {System.out.println (e);
		}} private static void WriteChars (file file, char[] data) throws IOException {Writer fos = null;
		Writer OS = null;
			try {fos = new FileWriter (file);
			OS = new BufferedWriter (FOS);

		Os.write (data);
				Finally {try {if (OS!= null) os.close ();
			if (FOS!= null) fos.close ();
			catch (Exception e) {e.printstacktrace ();
	}}/////////////////////////////////////////////////////end of test code. // /////////////////////////////////////////////////

}

PS: About encryption technology, the site also provides the following encryption tools for your reference to use:

BASE64 encoding and decoding tool:http://tools.jb51.net/transcoding/base64

MD5 Online encryption tool: Http://tools.jb51.net/password/CreateMD5Password

Escape Encryption/decryption tool: http://tools.jb51.net/password/escapepwd

Online SHA1 encryption tool: Http://tools.jb51.net/password/sha1encode

short link (short URL) online generation tool: http://tools.jb51.net/password/dwzcreate

short link (short URL) online Restore tool: Http://tools.jb51.net/password/unshorturl

High Strength password generator: Http://tools.jb51.net/password/CreateStrongPassword

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.