zoukankan      html  css  js  c++  java
  • 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();
        }
    
    }

     

     

     

  • 相关阅读:
    [Go] Slices vs Array
    [置顶] SpecDD系列:“完成” 的定义
    关于游戏开发的一点随笔
    提高效率 常用的几个xcode快捷键
    关于android 自己实现 back键 home键
    (组合数学3.1.1.1)POJ 1146 ID Codes(字典序法)
    [置顶] c# asp.net 修改webconfig文件 配置
    python数据类型和3个重要函数
    jdk环境变量配置
    VM虚拟机下在LINUX上安装ORACLE 11G单实例数据库
  • 原文地址:https://www.cnblogs.com/haoxinyue/p/2470661.html
Copyright © 2011-2022 走看看