论坛首页 Java企业应用论坛

关于DES在CBC模式下的加密问题

浏览 14469 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (7)
作者 正文
   发表时间:2008-01-02  

我现在手上有一份C#的DES加密代码,如下:

using System;  
using System.Security.Cryptography;  
using System.IO;  
using System.Text;  
using System.ComponentModel;

namespace cSharpInWSP
{
	/// <summary>
	/// 完成加密和解密的功能
	/// </summary>
	public class DES
	{
		/// <summary>
		/// 构造器
		/// </summary>
		public DES()
		{
			//
			// TODO: 在此处添加构造函数逻辑
			//
		}

		//默认密钥初始化向量
		private static byte[] DESIV = {0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF};

		/// <summary>
		/// DES加密字符串
		/// </summary>
		/// <param name="encriptString">待加密的字符串</param>
		/// <param name="encKey">加密密钥,要求为8字节</param>
		/// <returns>加密成功返回加密后的字符串,失败返回源串</returns>
		public static string Encrypt(string encriptString, string encKey)
		{
			if (encKey.Trim().Length != 8)
				encKey = "87654321";

			try
			{
				byte[] bKey = Encoding.GetEncoding("GB2312").GetBytes(encKey.Substring(0, 8));
				byte[] bIV = DESIV;
				byte[] bEncContent = Encoding.GetEncoding("GB2312").GetBytes(encriptString);
				DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();
				MemoryStream mStream = new MemoryStream();
				//用指定的 Key 和初始化向量 (IV) 创建对称数据加密标准 (DES) 加密器对象
				CryptoStream cStream = new CryptoStream(mStream,dCSP.CreateEncryptor(bKey, bIV), CryptoStreamMode.Write);
				cStream.Write(bEncContent, 0, bEncContent.Length);
				cStream.FlushFinalBlock();
				return Convert.ToBase64String(mStream.ToArray());
				// return Encoding.GetEncoding("GB2312").GetString(mStream.ToArray());
			}
			catch
			{
				return encriptString;
			}
		}
		/// <summary>
		/// DES解密字符串
		/// </summary>
		/// <param name="decryptString">待解密的字符串</param>
		/// <param name="decryptKey">解密密钥,要求为8字节,和加密密钥相同</param>
		/// <returns>解密成功返回解密后的字符串,失败返源串</returns>
		public static string Decrypt(string decryptString, string decryptKey)
		{
			if (decryptKey.Trim().Length != 8)
				decryptKey = "87654321";
			try 
			{	
				byte[] bKey = Encoding.GetEncoding("GB2312").GetBytes(decryptKey);
				byte[] bIV = DESIV;
				byte[] bDecContent = Convert.FromBase64String(decryptString);
				DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();
				MemoryStream mStream = new MemoryStream();
				CryptoStream cStream = new CryptoStream(mStream,DCSP.CreateDecryptor(bKey,bIV),CryptoStreamMode.Write);
				cStream.Write(bDecContent,0,bDecContent.Length);
				cStream.FlushFinalBlock();
				return Encoding.GetEncoding("GB2312").GetString(mStream.ToArray());
			} 
			catch 
			{
				return decryptString;
			}		
		}
	}
}

 现在想把它用java来实现,问题出在那个DESIV上,java里好像只允许用64位的DESIV,我的java代码如下:

package test;

/**  
 *   CryptionData.java  
 *   @version   1.0  
 *   @author   2005/4/20   Yao   (WICT)  
 */

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.*;
import sun.misc.*;

/**
 * DES encryption algorithm, providing the encryption and decryption algorithm
 * for byte array and string
 * 
 * @author : Yao (WICT)
 * @version 1.0
 */
public class CryptionData {
	// The length of Encryptionstring should be 8 bytes and not be
	// a weak key
	private String EncryptionString;

	// The initialization vector should be 8 bytes
	private final byte[] EncryptionIV = { 0x11, 0x22, 0x4F, 0x58, (byte) 0x88,
			0x10, 0x40, 0x38, 0x28, 0x25, 0x79, 0x51, (byte) 0xCB, (byte) 0xDD,
			0x55, 0x66, 0x77, 0x29, 0x74, (byte) 0x98, 0x30, 0x40, 0x36,
			(byte) 0xE2 };
	private final static String DES = "DES/CBC/PKCS5Padding";

	/**
	 * Saving key for encryption and decryption
	 * 
	 * @param EncryptionString
	 *            String
	 */
	public CryptionData(String EncryptionString) {
		this.EncryptionString = EncryptionString;
	}

	/**
	 * Encrypt a byte array
	 * 
	 * @param SourceData
	 *            byte[]
	 * @throws Exception
	 * @return byte[]
	 */
	public byte[] EncryptionByteData(byte[] SourceData) throws Exception {
		byte[] retByte = null;

		// Create SecretKey object

		byte[] EncryptionByte = EncryptionString.getBytes();
		DESKeySpec dks = new DESKeySpec(EncryptionByte);
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		SecretKey securekey = keyFactory.generateSecret(dks);

		// Create IvParameterSpec object with initialization vector
		IvParameterSpec spec = new IvParameterSpec(EncryptionIV);

		// Create Cipter object
		Cipher cipher = Cipher.getInstance(DES);

		// Initialize Cipher object
		cipher.init(Cipher.ENCRYPT_MODE, securekey, spec);

		// Encrypting data
		retByte = cipher.doFinal(SourceData);
		return retByte;
	}

	/**
	 * Decrypt a byte array
	 * 
	 * @param SourceData
	 *            byte[]
	 * @throws Exception
	 * @return byte[]
	 */
	public byte[] DecryptionByteData(byte[] SourceData) throws Exception {
		byte[] retByte = null;

		// Create SecretKey object
		byte[] EncryptionByte = EncryptionString.getBytes();
		DESKeySpec dks = new DESKeySpec(EncryptionByte);
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		SecretKey securekey = keyFactory.generateSecret(dks);

		// Create IvParameterSpec object with initialization vector
		IvParameterSpec spec = new IvParameterSpec(EncryptionIV);

		// Create Cipter object
		Cipher cipher = Cipher.getInstance(DES);

		// Initialize Cipher object
		cipher.init(Cipher.DECRYPT_MODE, securekey, spec);

		// Decrypting data
		retByte = cipher.doFinal(SourceData);

		return retByte;
	}

	/**
	 * Encrypt a string
	 * 
	 * @param SourceData
	 *            String
	 * @throws Exception
	 * @return String
	 */
	public String EncryptionStringData(String SourceData) throws Exception {
		String retStr = null;
		byte[] retByte = null;

		// Transform SourceData to byte array
		byte[] sorData = SourceData.getBytes();

		// Encrypte data
		retByte = EncryptionByteData(sorData);

		// Encode encryption data
		BASE64Encoder be = new BASE64Encoder();
		retStr = be.encode(retByte);

		return retStr;
	}

	/**
	 * Decrypt a string
	 * 
	 * @param SourceData
	 *            String
	 * @throws Exception
	 * @return String
	 */
	public String DecryptionStringData(String SourceData) throws Exception {
		String retStr = null;
		byte[] retByte = null;

		// Decode encryption data
		BASE64Decoder bd = new BASE64Decoder();
		byte[] sorData = bd.decodeBuffer(SourceData);

		// Decrypting data
		retByte = DecryptionByteData(sorData);
		retStr = new String(retByte);

		return retStr;
	}

	public static void main(String[] args) throws Exception {
		CryptionData c = new CryptionData("12345678");
		System.out.println(c.EncryptionStringData("13764528738"));
	}
}

 一运行就会报:

Exception in thread "main" java.security.InvalidAlgorithmParameterException: Wrong IV length: must be 8 bytes long
	at com.sun.crypto.provider.SunJCE_f.a(DashoA13*..)
	at com.sun.crypto.provider.DESCipher.engineInit(DashoA13*..)
	at javax.crypto.Cipher.a(DashoA13*..)
	at javax.crypto.Cipher.a(DashoA13*..)
	at javax.crypto.Cipher.init(DashoA13*..)
	at javax.crypto.Cipher.init(DashoA13*..)
	at test.CryptionData.EncryptionByteData(CryptionData.java:69)
	at test.CryptionData.EncryptionStringData(CryptionData.java:124)
	at test.CryptionData.main(CryptionData.java:158)
 有那个高人谁能帮忙看一下啊~~

 

 

 

论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics