DES加密


數據加密標准DES加密算法是一種對稱加密算法,DES 使用一個 56 位的密鑰以及附加的 8 位奇偶校驗位,產生最大 64 位的分組大小。這是一個迭代的分組密碼,使用稱為 Feistel 的技術,其中將加密的文本塊分成兩半。使用子密鑰對其中一半應用循環功能,然后將輸出與另一半進行“異或”運算;接着交換這兩半,這一過程會繼續下去,但最后一個循環不交換。DES 使用 16 個循環,使用異或,置換,代換,移位操作四種基本運算。

 

特點:數據加密標准,速度較快,適用於加密大量數據的場合; 

 

DES加密在C#中使用

class Program
    {
        public static void Main()
        {
            string text = "測試asdY^&*NN!__s some plaintext!";
            Console.WriteLine("加密前的明文:" + text);
            string cyphertext = Encrypt("測試asdY^&*NN!__s some plaintext!", "19491001");//密碼必須8位
            Console.WriteLine("解密后的明文:" + Decrypt(cyphertext, "19491001"));
            Console.ReadLine();
        }

        public static string Encrypt(string text, string key)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            byte[] inputByteArray = Encoding.GetEncoding("UTF-8").GetBytes(text);

            byte[] a = ASCIIEncoding.ASCII.GetBytes(key);
            des.Key = ASCIIEncoding.ASCII.GetBytes(key);
            des.IV = ASCIIEncoding.ASCII.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);//將第一個參數轉換為十六進制數,長度為2,不足前面補0
            }
            return ret.ToString();
        }

        public static string Decrypt(string cyphertext, string key)
        {
            if (string.IsNullOrEmpty(cyphertext))
                return string.Empty;
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();

            byte[] inputByteArray = new byte[cyphertext.Length / 2];
            for (int x = 0; x < cyphertext.Length / 2; x++)
            {
                int i = (Convert.ToInt32(cyphertext.Substring(x * 2, 2), 16));
                inputByteArray[x] = (byte)i;
            }

            des.Key = ASCIIEncoding.ASCII.GetBytes(key);
            des.IV = ASCIIEncoding.ASCII.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.GetEncoding("UTF-8").GetString(ms.ToArray());
        }
    }

 

java的DES加解密, 可以和C#互操作

package temptest;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.crypto.*;
import javax.crypto.spec.*;

import sun.misc.BASE64Decoder;

public class desencryptiontest {
    public static void main(String[] args) {
        String text = "測試asdY^&*NN!__s some plaintext!";
        System.out.println("加密前的明文:" + text);

        String cryperText = "";
        try {
            cryperText = toHexString(encrypt(text));
            System.out.println("加密前的明文:" + cryperText);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        try {
            System.out.println("解密后的明文:" + decrypt(cryperText));
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            System.in.read();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private static byte[] desKey;
    private static String key = "19491001";

    public static String decrypt(String message) throws Exception {

        byte[] bytesrc = convertHexString(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);
    }

    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"));
    }

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

        return digest;
    }

    public static String toHexString(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();
    }

}

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM