Java和C#交叉加密解密方法(DES)(一)

    看过网上许多这种Java和.net交叉加密解密的方法,杂七杂八的,让人看得很不明了,经过整理和调试后,决定把代码贴上来,一来提供给有需要的朋友作参考,二来给自己留下个脚印,以免以后有用得着的地方。我不知道这种加密解密的安全性可靠还是不可靠,但至少实现了Java和C#.net的交叉加密解密方法,代码如下:

Java类:

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;

public class DESCryptUtil {
	private static final String key = "20100728";
	
	// 解密数据
	public static String decrypt(String message) throws Exception {
		byte[] bytesrc = stringToBytes(message);
		Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
		DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
		IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));

		cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);

		byte[] retByte = cipher.doFinal(bytesrc);
		return new String(retByte, "UTF-8");
	}

	//加密数据
	public static byte[] encrypt(String message) throws Exception {
		Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");

		DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));

		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
		IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
		cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);

		return cipher.doFinal(message.getBytes("UTF-8"));
	}

	//String转Byte数组
	public static byte[] stringToBytes(String temp) {
		byte digest[] = new byte[temp.length() / 2];
		for (int i = 0; i < digest.length; i++) {
			String byteString = temp.substring(2 * i, 2 * i + 2);
			int byteValue = Integer.parseInt(byteString, 16);
			digest[i] = (byte) byteValue;
		}

		return digest;
	}
	
	//Byte数组转String
	public static String bytesToString(byte b[]) {
		StringBuffer hexString = new StringBuffer();
		for (int i = 0; i < b.length; i++) {
			String plainText = Integer.toHexString(0xff & b[i]);
			if (plainText.length() < 2)
				plainText = "0" + plainText;
			hexString.append(plainText);
		}

		return hexString.toString();
	}

 	public static void main(String[] args) throws Exception {
		String key = "20100728";
		String value = "阿\"飞";
		System.out.println("加密的数据:" + value);
		String a = bytesToString(encrypt(value)).toUpperCase();
		System.out.println("加密后的数据:" + a);	
		String b = decrypt(a);
		System.out.println("解密后的数据:" + b);
		System.out.println(b.length());
	}
}

你可能感兴趣的:(java,C++,c,.net,C#)