码迷,mamicode.com
首页 > 编程语言 > 详细

des加解密(java和.net)

时间:2017-10-17 15:44:56      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:mba   ini   编码方式   logs   string   转换   ring   actor   odi   

加密方法说明:

1.根据约定秘钥,采用Des加密算法进行加密生成字节数组;

2.将加密后生成的字节数组采用BASE64算法编码;

解密方法说明:

1.采用BASE64算法对密文进行解码生成字节数组;

2.根据约定的秘钥,对生成的字节数组进行采用Des解密;

 

 

java代码:

 

package com.ab.mediation.util;

 

import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

import java.io.InputStreamReader;

 

import java.security.SecureRandom;

import javax.crypto.Cipher;

import javax.crypto.SecretKey;

import javax.crypto.SecretKeyFactory;

import javax.crypto.spec.DESKeySpec;

import sun.misc.BASE64Decoder;

import sun.misc.BASE64Encoder;

/**

 * 对外接口数据加密/解密类 

 * @author xin

 *

 */

public class DesUtil {

 

private final static String DES = "DES";

 

public static void main(String[] args) throws Exception {

String tDoc = "";// 请求报文

String encoding = "GBK";

// 将函数参数赋给本地参数

String path = "D:\\111111.xml";

// String path = "F:\\111111\\111111.xml";

String path1 = path;

// 初始化文件对象f

File f = new File(path1);

// 初始化读数据流对象reader

InputStreamReader reader = new InputStreamReader(new FileInputStream(

path1), encoding);

// 根据f文件长度初始化字符串数据c[]

char c[] = new char[(int) (f.length())];

// 取到字符串长度,并将文件f内容写入数组c

int length = reader.read(c);

// 逐字节将字符串数组c[],赋给变量tDoc

for (int i = 0; i < length; i++) {

tDoc = tDoc + c[i];

}

// System.out.println(tDoc);

 

String key = "111111111";

System.out.println(encrypt(tDoc, key));

System.out.println(decrypt(encrypt(tDoc, key), key));

 

}

 

/**

 * Description 根据键值进行加密

 * 

 * @param data

 * @param key

 *            加密键byte数组

 * @return

 * @throws Exception

 */

public static String encrypt(String data, String key) throws Exception {

byte[] bt = encrypt(data.getBytes(), key.getBytes());

String strs = new BASE64Encoder().encode(bt);

return strs;

}

 

/**

 * 指定字符编码方式并加密

 * @param data

 * @param key

 * @param encoding

 * @return

 * @throws Exception

 */

public static String encrypt(String data, String key, String encoding) throws Exception {

byte[] bt = encrypt(data.getBytes(encoding), key.getBytes());

String strs = new BASE64Encoder().encode(bt);

return strs;

}

 

/**

 * Description 根据键值进行解密

 * 

 * @param data

 * @param key

 *            加密键byte数组

 * @return

 * @throws IOException

 * @throws Exception

 */

public static String decrypt(String data, String key) throws IOException,

Exception {

if (data == null)

return null;

BASE64Decoder decoder = new BASE64Decoder();

byte[] buf = decoder.decodeBuffer(data);

byte[] bt = decrypt(buf, key.getBytes());

return new String(bt);

}

 

/**

 * 根据键值解密并返回指定编码方式字符串

 * @param data

 * @param key

 * @param encoding

 * @return

 * @throws IOException

 * @throws Exception

 */

public static String decrypt(String data, String key, String encoding) throws IOException,

Exception {

if (data == null)

return null;

BASE64Decoder decoder = new BASE64Decoder();

byte[] buf = decoder.decodeBuffer(data);

byte[] bt = decrypt(buf, key.getBytes());

return new String(bt, encoding);

}

 

/**

 * Description 根据键值进行加密

 * 

 * @param data

 * @param key

 *            加密键byte数组

 * @return

 * @throws Exception

 */

private static byte[] encrypt(byte[] data, byte[] key) throws Exception {

// 生成一个可信任的随机数源

SecureRandom sr = new SecureRandom();

 

// 从原始密钥数据创建DESKeySpec对象

DESKeySpec dks = new DESKeySpec(key);

 

// 创建一个密钥工厂,然后用它把DESKeySpec转换成SecretKey对象

SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);

SecretKey securekey = keyFactory.generateSecret(dks);

 

// Cipher对象实际完成加密操作

Cipher cipher = Cipher.getInstance(DES);

 

// 用密钥初始化Cipher对象

cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);

 

return cipher.doFinal(data);

}

 

/**

 * Description 根据键值进行解密

 * 

 * @param data

 * @param key

 *            加密键byte数组

 * @return

 * @throws Exception

 */

private static byte[] decrypt(byte[] data, byte[] key) throws Exception {

// 生成一个可信任的随机数源

SecureRandom sr = new SecureRandom();

 

// 从原始密钥数据创建DESKeySpec对象

DESKeySpec dks = new DESKeySpec(key);

 

// 创建一个密钥工厂,然后用它把DESKeySpec转换成SecretKey对象

SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);

SecretKey securekey = keyFactory.generateSecret(dks);

 

// Cipher对象实际完成解密操作

Cipher cipher = Cipher.getInstance(DES);

 

// 用密钥初始化Cipher对象

cipher.init(Cipher.DECRYPT_MODE, securekey, sr);

 

return cipher.doFinal(data);

}

}

 

 

 

 

 

 

 

对应的.net代码:

 

        public static string DesDecrypt(string str, string key)
        {
            DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
            key = key.Substring(0, 8);//截取前八位
            DES.Key = ASCIIEncoding.Default.GetBytes(key);
            DES.Mode = CipherMode.ECB;
            DES.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
            ICryptoTransform DESDecrypt = DES.CreateDecryptor();
            string result = "";
            try
            {
                byte[] Buffer = Convert.FromBase64String(str);
                result = Encoding.Default.GetString(DESDecrypt.TransformFinalBlock(Buffer, 0, Buffer.Length));
            }
            catch (CryptographicException e)
            {
                Console.WriteLine(" error : {0}", e.Message);
                return null;
            }
            return result;

        }

        public static string DesEncrypt(string str, string key)
        {
            string res = "";
            key = key.Substring(0,8);//截取前八位
            try
            {
                DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
                DES.Key = Encoding.UTF8.GetBytes(key);
                DES.Mode = CipherMode.ECB;
                DES.Padding = PaddingMode.PKCS7;

                ICryptoTransform DESEncrypt = DES.CreateEncryptor();

                byte[] Buffer = Encoding.GetEncoding("GBK").GetBytes(str);
                res = Convert.ToBase64String(DESEncrypt.TransformFinalBlock(Buffer, 0, Buffer.Length));

            }
            catch (CryptographicException e)
            {
                Console.WriteLine(" error : {0}", e.Message);
                return null;
            }

            return res;
        }

 

des加解密(java和.net)

标签:mba   ini   编码方式   logs   string   转换   ring   actor   odi   

原文地址:http://www.cnblogs.com/request/p/7680668.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!