自編寫C#和java互相解密加密方法

java代碼如下:

package com.ypsoft.base.utils;
/**
 * 創建於2008-11-7
 */ 

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
 
public class StringEncryptDecrypt {

	/**
	 * 加密字符串
	 * @param strIn String 待加密的字符串
	 * @param key String 密鑰
	 * @return String 加密後的字符串
	 * @throws Exception
	 */
	public static String encrypt(String strIn, String key) throws Exception {
		return byteArr2HexStr(encrypt(strIn.getBytes(), key));
	}
	
	/**
	 * 解密字符串
	 * @param strIn String 待解密的字符串
	 * @param key String 密鑰
	 * @return String 解密後的字符串
	 * @throws Exception
	 */
	public static String decrypt(String strIn, String key) throws Exception {
		return new String(decrypt(hexStr2ByteArr(strIn), key));
	}
	
	/**
	 * 將表示16進制值的字符串轉換爲byte數組, 和public static String byteArr2HexStr(byte[] arrB)
	 * 互爲可逆的轉換過程
	 * @param strIn
	 * @return
	 * @throws Exception
	 */
	public static byte[] hexStr2ByteArr(String strIn) throws Exception {
		byte[] arrB = strIn.getBytes();
		int iLen = arrB.length;
		// 兩個字符表示一個字節,所以字節數組長度是字符串長度除以2
		byte[] arrOut = new byte[iLen / 2];
		for (int i = 0; i < iLen; i = i + 2) {
			String strTmp = new String(arrB, i, 2);
			arrOut[i / 2] = (byte) Integer.parseInt(strTmp, 16);
		}
		return arrOut;
	}
	/**
	 * 將byte數組轉換爲表示16進制值的字符串 hexStr2ByteArr(String strIn) 互爲可逆的轉換過程
	 * @param arrB 需要轉換的byte數組
	 * @return 轉換後的字符串
	 * @throws Exception 本方法不處理任何異常,所有異常全部拋出
	 */
	public static String byteArr2HexStr(byte[] arrB) throws Exception {
		int iLen = arrB.length;
		// 每個byte用兩個字符才能表示,所以字符串的長度是數組長度的兩倍
		StringBuffer sb = new StringBuffer(iLen * 2);
		for (int i = 0; i < iLen; i++) {
			int intTmp = arrB[i];
			// 把負數轉換爲正數
			while (intTmp < 0) {
				intTmp = intTmp + 256;
			}
			// 小於0F的數需要在前面補0
			if (intTmp < 16) {
				sb.append("0");
			}
			sb.append(Integer.toString(intTmp, 16));
		}
		return sb.toString();
	}

	/**
	 * 加密字節數組
	 * @param arrB
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public static byte[] encrypt(byte[] arrB, String key) throws Exception {
		SecretKey deskey =new javax.crypto.spec.SecretKeySpec (key.getBytes() ,"DES" );
		Cipher encryptCipher = Cipher.getInstance("DES");
		encryptCipher.init(Cipher.ENCRYPT_MODE, deskey);
		return encryptCipher.doFinal(arrB);
	}
	/**
	 * 解密字節數組
	 * @param arrB
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public static byte[] decrypt(byte[] arrB, String key) throws Exception {
		SecretKey deskey =new javax.crypto.spec.SecretKeySpec (key.getBytes() ,"DES" );
		Cipher decryptCipher = Cipher.getInstance("DES");
		decryptCipher.init(Cipher.DECRYPT_MODE, deskey);
		return decryptCipher.doFinal(arrB);
	}
	 
}
package com.ypsoft.base.utils;
/**
 * 創建於2008-11-25
 */ 
import java.util.UUID;
 
public class PasswordEncodeDecode {
	/** 公鑰 */
	final static String PUBLIC_KEY = "xjhyrjgs";
	/**
	 * 對用戶密碼加密
	 * @param userName 用戶名
	 * @param password 用戶密碼
	 * @return String 加密後的密碼
	 * @throws Exception
	 */
	public static String passwordEncode(String userName, String password)
			throws Exception {
		String key = StringEncryptDecrypt.encrypt(userName, PUBLIC_KEY);
		System.out.println("第一次加密密匙"+key);
		if (key.length() > 8) {
			return StringEncryptDecrypt.encrypt(password, key.substring(0, 8));
		} else {
			return StringEncryptDecrypt.encrypt(password, key);
		}
	}
	/**
	 * 對用戶密碼解密
	 * @param userName 用戶名
	 * @param password 加密的用戶密碼
	 * @return String 解密的用戶密碼
	 * @throws Exception
	 */
	public static String passwordDecode(String userName, String password)
			throws Exception {
		String key = StringEncryptDecrypt.encrypt(userName, PUBLIC_KEY);
		if (key.length() > 8) {
			return StringEncryptDecrypt.decrypt(password, key.substring(0, 8));
		} else {
			return StringEncryptDecrypt.decrypt(password, key);
		}
	}
	 
}
package com.ypsoft.base.utils;

import java.util.Scanner;

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

import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
 
public class Test3DES {
	
	public static void main(String[] args)throws Exception {
        System.out.println("+++++++++++++++++++++++ 測試使用3DES加密解密 ++++++++++++++++++++");  
        System.out.println();
        Scanner sc = new Scanner(System.in); 
        
        System.out.println("-------------> 開始進行加密操作 <-------------");
        System.out.println("請輸入用戶名:");
        
      String key1 = sc.nextLine();
    
        
        System.out.println("請輸入密碼:");
        String value1 = sc.nextLine(); 

        System.out.println();
        PasswordEncodeDecode pd=new PasswordEncodeDecode();
        System.out.println("數據加密成功,加密結果爲:" + pd.passwordEncode(key1, value1));
        System.out.println();
        System.out.println();
        while(true) {
            System.out.println("請選擇解密or退出?1[解密],2[退出]:");
            String select = sc.nextLine();
        	if("1".equals(select)){
            	System.out.println("-------------> 您選擇了【解密】操作  <-------------");
            	System.out.println("請輸入用戶名:");
                String key2 =  sc.nextLine();
                while(!key1.equals(key2)){
                	System.out.println("該key不存在,請重新輸入key值:");
                	key2 = sc.nextLine();
                }
                System.out.println("請輸入待解密的字符串:");
                String value2 = sc.nextLine();
                System.out.println();
                System.out.println("調用原始密鑰算解密結果爲:" + pd.passwordDecode(key2, value2));
                System.out.println();
            }else if("2".equals(select)){
            	break;
            }else{
            	System.out.println("指令錯誤!請重新輸入,1[解密],2[退出]:");
            }
        }
         
         System.out.println("----------測試使用3DES加密解密結束-----------"); 
	}  	    
}


.net代碼如下:

using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace UserLoginUI.Encrypt
{
    #region Version Info
    /*========================================================================
    * 【本類功能概述】
    * 
    * 作者:        時間:2015/5/12 10:59:12
    * 文件名:StringEncryptDecrypt
    * 版本:V1.0.1
    * 說明:字符串加密解密類
    * 修改者:          時間:              
    * 修改說明:
    * ========================================================================
    */
    #endregion
   public  class StringEncryptDecrypt
    {
        
        /// <summary>
        /// 字符串DES加密函數
        /// </summary>
        /// <param name="str">被加密字符串</param>
        /// <param name="key">密鑰</param>
        /// <returns>加密後字符串</returns>
        public static string Encode(string str, string key)
        {
            try
            {
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                byte[] inputByteArray = Encoding.Default.GetBytes(str);

                des.Mode = CipherMode.ECB;
                des.Key = ASCIIEncoding.Default.GetBytes(key);
                des.IV = ASCIIEncoding.Default.GetBytes(key);
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);

                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();

                StringBuilder ret = new StringBuilder();
                foreach (byte b in ms.ToArray())
                {
                    ret.AppendFormat("{0:X2}", b);
                }
                return ret.ToString().ToLower();
            }
            catch (Exception) { return "xxxx"; }
        }
       /// <summary>
        /// 字符串DES解密函數
       /// </summary>
        /// <param name="str">被解密字符串</param>
        /// <param name="key">密鑰</param>
        /// <returns>解密後字符串</returns>
        public static string Decode(string str, string key)
        {
            try
            {
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                des.Mode = CipherMode.ECB;
                byte[] inputByteArray = new byte[str.Length / 2];
                for (int x = 0; x < str.Length / 2; x++)
                {
                    int i = (Convert.ToInt32(str.Substring(x * 2, 2), 16));
                    inputByteArray[x] = (byte)i;
                }

                des.Key = ASCIIEncoding.Default.GetBytes(key);
                des.IV = ASCIIEncoding.Default.GetBytes(key);
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();

                StringBuilder ret = new StringBuilder();

                return System.Text.Encoding.Default.GetString(ms.ToArray());
            }
            catch (Exception) { return ""; }
        }
    }
}

using System;
using System.Collections.Generic;
using System.Text;

namespace UserLoginUI.Encrypt
{
    #region Version Info
    /*========================================================================
    * 【本類功能概述】
    * 
    * 作者:        時間:2015/5/12 10:59:03
    * 文件名:PasswordEncodeDecode
    * 版本:V1.0.1
    * 說明:用戶名、密碼加密、解密操作類
    * 修改者:          時間:              
    * 修改說明:
    * ========================================================================
    */
    #endregion
   public  class PasswordEncodeDecode
    {
        /// <summary>
        /// 公鑰
        /// </summary>
        static String PUBLIC_KEY = "xjhyrjgs";

        /// <summary>
        /// 對用戶密碼加密
        /// </summary>
        /// <param name="userName">用戶名</param>
        /// <param name="password">用戶密碼</param>
        /// <returns>加密後的密碼</returns>
        public static String passwordEncode(String userName, String password)
        {
            String key = StringEncryptDecrypt.Encode(userName, PUBLIC_KEY);
            if (key.Length > 8)
            {
                return StringEncryptDecrypt.Encode(password, key.Substring(0, 8).ToLower());
            }
            else
            {
                return StringEncryptDecrypt.Encode(password, key);
            }
        } 
        /// <summary>
        ///  對用戶密碼解密
        /// </summary>
        /// <param name="userName">用戶名</param>
        /// <param name="password">加密的用戶密碼</param>
        /// <returns>解密的用戶密碼</returns>
        public static String passwordDecode(String userName, String password)
        {
            String key = StringEncryptDecrypt.Encode(userName, PUBLIC_KEY);
            if (key.Length > 8)
            {
                return StringEncryptDecrypt.Decode(password, key.Substring(0, 8));
            }
            else
            {
                return StringEncryptDecrypt.Decode(password, key);
            } 
        }

    }
}

代碼我已經測試過,能夠使用,如果有什麼遺漏或者不對的地方,請大家批評指導。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章