Java加密和C#解密=>DES方法

Java加密代码:

import javax.crypto.*;
import javax.crypto.*;
import java.io.UnsupportedEncodingException;
import java.security.spec.*;
import javax.crypto.spec.*;

public class DES {

    public DES()
    {
    }

     public String encrypt(String str) {

        byte[] enc = null;
        try {
          enc = desEncrypt(str, "abcdefgh");
        }
        catch (Exception ex) {
        }
       
         return new sun.misc.BASE64Encoder().encode(enc);
     }
     
     public static byte[] desEncrypt(String message, String key) 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"));
         }
}


C#加密代码:

    /// <param name="pToDecrypt">要解密的以Base64</param>
        /// <param name="sKey">密钥,且必须为8位。</param>
        /// <returns>已解密的字符串。</returns>
        public string Decrypt(string pToDecrypt, string sKey)
        {
            byte[] inputByteArray = Convert.FromBase64String(pToDecrypt);
            using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
            {
                des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
                des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(inputByteArray, 0, inputByteArray.Length);
                    cs.FlushFinalBlock();
                    cs.Close();
                }
                string str = Encoding.UTF8.GetString(ms.ToArray());
                ms.Close();
                return str;
            }
        } 


特别注意关键key=》字符串长度必须为8位数字

posted on 2014-05-16 17:27  ~紫鱼~  阅读(397)  评论(0编辑  收藏  举报