"Go" Java DES ECB mode symmetric encryption decryption

Source: Internet
Author: User
Tags md5 encryption

The recent need to use DES encryption data, to require des encrypted data for symmetric encryption, after research, found some problems:


1.DES symmetric ECB mode encrypted data, length must be a multiple of 8

2. Encrypted data, first transcoding after encryption (because the encrypted data I am transcoding), or decryption is garbled format

Here is the source code:

This is the cryptographic tool class:

 PackageCom.palmfu.sql;ImportJava.security.Key;ImportJavax.crypto.Cipher;ImportJavax.crypto.spec.SecretKeySpec;/*** * DES ECB symmetric encryption decryption *@authorSpring Sky * email:[email protected] * qq:840950105 **/ Public classDesecbutil {/*** Encrypt data *@paramencryptstring Note: The data length can only be a multiple of 8 *@paramEncryptkey *@return     * @throwsException*/     Public StaticString Encryptdes (String encryptstring, String encryptkey)throwsException {secretkeyspec key=NewSecretkeyspec (GetKey (Encryptkey), "DES"); Cipher Cipher= Cipher.getinstance ("des/ecb/nopadding");        Cipher.init (Cipher.encrypt_mode, key); byte[] EncryptedData =cipher.dofinal (Encryptstring.getbytes ()); returnconvertutil.bytestohexstring (EncryptedData); }        /*** Customize a key *@paramstring*/     Public Static byte[] GetKey (String keyrule) {key key=NULL; byte[] Keybyte =keyrule.getbytes (); //creates an empty eight-bit array, which by default is 0        byte[] Bytetemp =New byte[8]; //converts a user-specified rule to a eight-bit array         for(inti = 0; I < bytetemp.length && I < keybyte.length; i++) {Bytetemp[i]=Keybyte[i]; } Key=NewSecretkeyspec (bytetemp, "DES"); returnkey.getencoded (); }        /*** * Decrypt data *@paramdecryptstring *@paramDecryptkey *@return     * @throwsException*/     Public StaticString Decryptdes (String decryptstring, String decryptkey)throwsException {secretkeyspec key=NewSecretkeyspec (GetKey (Decryptkey), "DES"); Cipher Cipher= Cipher.getinstance ("des/ecb/nopadding");        Cipher.init (Cipher.decrypt_mode, key); byteDecrypteddata[] =cipher.dofinal (Convertutil.hexstringtobyte (decryptstring)); return NewString (Decrypteddata); }         Public Static voidMain (string[] args)throwsException {String cleartext= "SPRINGSK";//the length of the data here must be a multiple of 8.String key = "12345678"; System.out.println ("PlainText:" \ +cleartext+ "\ n key:" +key); String Encrypttext=encryptdes (cleartext, key); System.out.println ("After encryption:" +encrypttext); String Decrypttext=decryptdes (Encrypttext, key); System.out.println ("After decryption:" +decrypttext); }}

Transcoding Tool Class (contains MD5 encryption)

Package com.palmfu.sql;

Import Java.io.ByteArrayInputStream;
Import Java.io.ByteArrayOutputStream;
Import java.io.IOException;
Import Java.io.ObjectInputStream;
Import Java.io.ObjectOutputStream;
Import java.io.Serializable;
Import Java.security.MessageDigest;
Import java.security.NoSuchAlgorithmException;

/***
* transcoding MD5 Tool class
* @author Spring Sky
* Email:[email protected]
* qq:840950105
*
*/
Public final class Convertutil {

Public final static char[] BToA = "0123456789abcdef". ToCharArray ();

Private Convertutil () {

}

/**
* Convert 16 binary string to byte array
*
* @param hex
* @return
*/
public static byte[] Hexstringtobyte (String hex) {
int len = (hex.length ()/2);
Byte[] result = new Byte[len];
char[] Achar = Hex.tochararray ();
for (int i = 0; i < len; i++) {
int pos = i * 2;
Result[i] = (byte) (ToByte (Achar[pos]) << 4 | tobyte (Achar[pos + 1]));
}
return result;
}

private static byte ToByte (char c) {
byte B = (byte) "0123456789ABCDEF". IndexOf (c);
return b;
}

/**
* Convert byte arrays to 16 binary strings
*
* @param Barray
* @return
*/
public static final String bytestohexstring (byte[] barray) {
if (Barray = = null)
{
Return "";
}
StringBuffer sb = new StringBuffer (barray.length);
String stemp;
for (int i = 0; i < barray.length; i++) {
Stemp = integer.tohexstring (0xFF & Barray[i]);
if (Stemp.length () < 2)
Sb.append (0);
Sb.append (Stemp.touppercase ());
}
return sb.tostring ();
}

/**
* Convert byte arrays to objects
*
* @param bytes
* @return
* @throws IOException
* @throws ClassNotFoundException
*/
public static final Object bytestoobject (byte[] bytes) throws IOException,
classnotfoundexception {
Bytearrayinputstream in = new Bytearrayinputstream (bytes);
ObjectInputStream oi = new ObjectInputStream (in);
Object o = Oi.readobject ();
Oi.close ();
return o;
}

/**
* Convert serializable objects to byte arrays
*
* @param s
* @return
* @throws IOException
*/
public static final byte[] Objecttobytes (Serializable s) throws IOException {
Bytearrayoutputstream out = new Bytearrayoutputstream ();
ObjectOutputStream ot = new ObjectOutputStream (out);
Ot.writeobject (s);
Ot.flush ();
Ot.close ();
return Out.tobytearray ();
}

public static final String objecttohexstring (Serializable s)
Throws IOException {
Return Bytestohexstring (Objecttobytes (s));
}

public static final Object hexstringtoobject (String hex)
Throws IOException, ClassNotFoundException {
Return Bytestoobject (Hexstringtobyte (hex));
}

/**
* Function: BCD code to 10 binary string (Arab data)
* @ input parameter: BCD code
* @ Output Result: 10 binary string
*/
public static String bcd2str (byte[] bytes) {
StringBuffer temp = new StringBuffer (Bytes.length * 2);

for (int i = 0; i < bytes.length; i++) {
Temp.append ((Byte) ((Bytes[i & 0xf0) >>> 4));
Temp.append ((Byte) (Bytes[i] & 0x0f));
}
Return temp.tostring (). substring (0, 1). Equalsignorecase ("0")? Temp
. toString (). SUBSTRING (1): temp.tostring ();
}

/**
* @ Function function: 10 binary to BCD code
* @ input parameter: 10 binary string
* @ Output Result: BCD code
*/
public static byte[] STR2BCD (String ASC) {
int len = Asc.length ();
int mod = len% 2;

if (mod! = 0) {
ASC = "0" + ASC;
Len = Asc.length ();
}

byte abt[] = new Byte[len];
if (Len >= 2) {
len = LEN/2;
}

byte bbt[] = new Byte[len];
abt = Asc.getbytes ();
Int J, K;

for (int p = 0; p < asc.length ()/2; p++) {
if ((ABT[2 * p] >= ' 0 ') && (ABT[2 * p] <= ' 9 ')) {
j = abt[2 * p]-' 0 ';
} else if ((ABT[2 * p] >= ' a ') && (ABT[2 * p] <= ' z ')) {
j = abt[2 * p]-' a ' + 0x0a;
} else {
j = abt[2 * p]-' A ' + 0x0a;
}

if ((ABT[2 * p + 1] >= ' 0 ') && (ABT[2 * p + 1] <= ' 9 ')) {
k = abt[2 * p + 1]-' 0 ';
} else if ((ABT[2 * p + 1] >= ' a ') && (ABT[2 * p + 1] <= ' z ')) {
k = abt[2 * p + 1]-' a ' + 0x0a;
} else {
k = abt[2 * p + 1]-' A ' + 0x0a;
}

int a = (J << 4) + K;
byte B = (byte) A;
BBT[P] = b;
}
return BBT;
}

public static String bcd2asc (byte[] bytes) {
StringBuffer temp = new StringBuffer (Bytes.length * 2);

for (int i = 0; i < bytes.length; i++) {
int h = ((Bytes[i] & 0xf0) >>> 4);
int L = (bytes[i] & 0x0f);
Temp.append (Btoa[h]). Append (Btoa[l]);
}
return temp.tostring ();
}

/**
* Two-character array xor
*/
public static byte[] Bytearrxor (byte[] arr1, byte[] arr2, int len) {
byte[] Dest = new Byte[len];

if ((Arr1.length < len) | | (Arr2.length < Len)) {
return null;
}

for (int i = 0;i < len;i++) {
Dest[i] = (byte) (Arr1[i] ^ arr2[i]);
}

return dest;
}


/**
* MD5 Encrypted string, returns the encrypted 16 binary string
* @param origin
* @return
*/
public static string Md5encodetohex (string origin) {
Return Bytestohexstring (Md5encode (origin));
}

/**
* MD5 Encrypted string, returns the encrypted byte array
*
* @param origin
* @return
*/
public static byte[] Md5encode (String origin) {
Return Md5encode (Origin.getbytes ());
}

/**
* MD5 encrypted byte array, returns the encrypted byte array
*
* @param bytes
* @return
*/
public static byte[] Md5encode (byte[] bytes) {
MessageDigest MD = NULL;
try {
MD = Messagedigest.getinstance ("MD5");
Return Md.digest (bytes);
} catch (NoSuchAlgorithmException e) {
E.printstacktrace ();
return new byte[0];
}

}
}

The above des ECB mode encryption and decryption has been tested on the Android Java platform, there is no problem, and has been and PHP background interoperability, please rest assured that use! If you have any questions, please contact me!
Reprint please keep the copyright of Spring sky!

The original address: http://blog.csdn.net/springsky_/article/details/8086037 reproduced only to stay for their own study, the copyright belongs to the author!
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.