aardio 官方社区

 找回密码
 注册会员

QQ登录

只需一步,快速开始

搜索
查看: 16394|回复: 5

DES加密算法不同编程语言通用写法(aardio,php,c#,java等

[复制链接]

166

主题

2154

回帖

1万

积分

管理员

积分
13056
发表于 2015-12-1 21:24:46 | 显示全部楼层 |阅读模式
不同编程语言中DES加解密结果要保持一致要注意以下一些要点:
1、工作模式CBC,填充模式PKCS5,不同语言要保持一致。
2、向量要一致,默认使用'\x12\x34\x56\x78\x90\xAB\xCD\xEF'
3、密钥要一致,DES密钥为8位,3DES可以使用24位密钥
4、使用的文本编码要一致,同一个字符串,使用UTF8或GBK编码在内存中存储的实际数据可能是不一样的。在aardio中使用 string.fromto进行转换。
5、如果加密后返回的密文用了BASE64或16进制编码,那么在解密时同样也先做对应的逆向解码。

首先看aardio加解密

  1. import console;  
  2. import crypt.des;

  3. var des = crypt.des();
  4. des.setPassword("abcd1234" )

  5. //加密
  6. var sstr = des.encrypt("测试字符串");

  7. //解密
  8. var str = des.decrypt(sstr);

  9. console.log( str, sstr )
  10. console.pause(true);
复制代码
PHP版本:

  1. <?
  2. class CryptDes
  3. {
  4.     public $key = "";
  5.     public $iv = "\x12\x34\x56\x78\x90\xAB\xCD\xEF";
  6.     public function init_crypt($key)
  7.     {
  8.         $this->key = $key;
  9.     }
  10.     public function encrypt($str)
  11.     {
  12.         $size = mcrypt_get_block_size(MCRYPT_DES, MCRYPT_MODE_CBC);
  13.         $str = $this->pkcs5Pad($str, $size);
  14.         $hexString = bin2hex(mcrypt_cbc(MCRYPT_DES, $this->key, $str, MCRYPT_ENCRYPT, $this->iv));
  15.         return strtoupper($hexString);
  16.     }
  17.     public function decrypt($str)
  18.     {
  19.         $strBin = $this->hex2bin(strtolower($str));
  20.         $str = mcrypt_cbc(MCRYPT_DES, $this->key, $strBin, MCRYPT_DECRYPT, $this->iv);
  21.         $str = $this->pkcs5Unpad($str);
  22.         return $str;
  23.     }
  24.     public function hex2bin($hexData)
  25.     {
  26.         $binData = '';
  27.         for ($i = 0; $i < strlen($hexData); $i += 2) {
  28.             $binData .= chr(hexdec(substr($hexData, $i, 2)));
  29.         }
  30.         return $binData;
  31.     }
  32.     public function pkcs5Pad($text, $blocksize)
  33.     {
  34.         $pad = $blocksize - strlen($text) % $blocksize;
  35.         return $text . str_repeat(chr($pad), $pad);
  36.     }
  37.     public function pkcs5Unpad($text)
  38.     {
  39.         $pad = ord($text[strlen($text) - 1]);
  40.         if ($pad > strlen($text)) {
  41.             return false;
  42.         }
  43.         if (strspn($text, chr($pad), strlen($text) - $pad) != $pad) {
  44.             return false;
  45.         }
  46.         return substr($text, 0, -1 * $pad);
  47.     }
  48. }
  49. $des = new CryptDes();
  50. $des->init_crypt("abcd1234");
  51. $sstr = $des->encrypt("def测试"); //加密
  52. $str = $des->decrypt($sstr); //解密
  53. echo $sstr;
  54. ?>
复制代码

注意上面的PHP版本将加密结果转换为了16进制字符,

在aardio中使用  string.unhex() 函数转回来, 注意aardio10使用UTF8编码,上面的PHP文件也应该存为UTF8编码,如果PHP使用GBK编码,那么相应的在aardio中也要做GBK编码转换。
import console;

import crypt.des;
var des = crypt.des();
des.setPassword(
"abcd1234" )

var phpsstr = "077E5E400A140170";//服务端返回的加密数据
phpsstr = string.unhex( phpsstr,"" ); //十六进制解码

var str = des.decrypt(phpsstr) ; //DES解码
str = string.fromto(str,0,65001) //PHP页面使用了UTF8,用这句转回来

console.log( str )
console.pause()

166

主题

2154

回帖

1万

积分

管理员

积分
13056
 楼主| 发表于 2015-12-2 13:40:25 | 显示全部楼层

JAVA版本( 参考帖子:http://bbs.aardio.com/forum.php?mod=viewthread&tid=10939 ):

  1. import java.io.BufferedReader;
  2. import java.io.BufferedWriter;
  3. import java.io.FileWriter;
  4. import java.io.InputStreamReader;
  5. import java.io.PrintWriter;
  6. import java.security.Key;
  7. import java.security.SecureRandom;
  8. import javax.crypto.Cipher;
  9. import javax.crypto.KeyGenerator;
  10. import javax.crypto.spec.IvParameterSpec;
  11. import javax.crypto.spec.SecretKeySpec;
  12. import sun.misc.BASE64Decoder;
  13. import sun.misc.BASE64Encoder;

  14. public class Encrypt {

  15.     SecretKeySpec key;

  16.     public Encrypt(String str) {
  17.         setKey(str);// 生成密匙
  18.     }

  19.     public Encrypt() {
  20.         setKey("ABCDEFGH");
  21.     }

  22.     // 根据参数生成KEY
  23.     public void setKey(String strKey) {
  24.         this.key = new SecretKeySpec(strKey.getBytes(), "DES");  ;
  25.     }

  26.     //加密String明文输入,String密文输出
  27.     public String getEncString(String strMing) {
  28.         byte[] byteMi = null;
  29.         byte[] byteMing = null;
  30.         String strMi = "";
  31.         BASE64Encoder base64en = new BASE64Encoder();
  32.         try {
  33.             byteMing = strMing.getBytes("UTF8");
  34.             byteMi = this.getEncCode(byteMing);
  35.             strMi = base64en.encode(byteMi);
  36.         } catch (Exception e) {
  37.             throw new RuntimeException(
  38.                     "DES加解密异常: " + e);
  39.         } finally {
  40.             base64en = null;
  41.             byteMing = null;
  42.             byteMi = null;
  43.         }
  44.         return strMi;
  45.     }

  46.     // 解密 以String密文输入,String明文输出
  47.     public String getDesString(String strMi) {
  48.         BASE64Decoder base64De = new BASE64Decoder();
  49.         byte[] byteMing = null;
  50.         byte[] byteMi = null;
  51.         String strMing = "";
  52.         try {
  53.             byteMi = base64De.decodeBuffer(strMi);
  54.             byteMing = this.getDesCode(byteMi);
  55.             strMing = new String(byteMing, "UTF8");
  56.         } catch (Exception e) {
  57.             throw new RuntimeException(
  58.                     "DES加解密异常: " + e);
  59.         } finally {
  60.             base64De = null;
  61.             byteMing = null;
  62.             byteMi = null;
  63.         }
  64.         return strMing;
  65.     }

  66.     // 加密以byte[]明文输入,byte[]密文输出

  67.     private static byte[] iv = {0x12,0x34,0x56,0x78,(byte)0x90,(byte)0xAB,(byte)0xCD,(byte)0xEF};
  68.     private byte[] getEncCode(byte[] byteS) {
  69.         IvParameterSpec zeroIv = new IvParameterSpec(iv);
  70.         byte[] byteFina = null;
  71.         Cipher cipher;
  72.         try {
  73.             cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
  74.             cipher.init(Cipher.ENCRYPT_MODE, this.key, zeroIv);
  75.             byteFina = cipher.doFinal(byteS);
  76.         } catch (Exception e) {
  77.             throw new RuntimeException(
  78.                     "DES加解密异常: " + e);
  79.         } finally {
  80.             cipher = null;
  81.         }
  82.         return byteFina;
  83.     }

  84.     //解密以byte[]密文输入,以byte[]明文输出

  85.     private byte[] getDesCode(byte[] byteD) {
  86.         IvParameterSpec zeroIv = new IvParameterSpec(iv);
  87.         byte[] byteFina = null;
  88.         Cipher cipher;
  89.         try {
  90.             cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
  91.             cipher.init(Cipher.DECRYPT_MODE, this.key, zeroIv);
  92.             byteFina = cipher.doFinal(byteD);
  93.         } catch (Exception e) {
  94.             throw new RuntimeException(
  95.                     "DES加解密异常: " + e);
  96.         } finally {
  97.             cipher = null;
  98.         }
  99.         return byteFina;
  100.     }

  101.     public static void main(String args[]) {
  102.         Encrypt des = new Encrypt();
  103.         try {
  104.             BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
  105.             System.out.print("请输入明文: >");

  106.             String str1 = in.readLine().trim();
  107.             PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(str1)));
  108.             String str2 = des.getEncString(str1);
  109.             String deStr = des.getDesString(str2);
  110.             System.out.println("密文:" + str2);
  111.             System.out.println("明文:" + deStr);

  112.             out.println("密文:" + str2);
  113.             out.println("明文:" + deStr);
  114.             out.close();
  115.         }catch(Exception e) {
  116.             System.out.println(e);
  117.         }
  118.     }
  119. }
复制代码

166

主题

2154

回帖

1万

积分

管理员

积分
13056
 楼主| 发表于 2015-12-2 13:40:58 | 显示全部楼层
C#版本( 参考帖子:http://bbs.aardio.com/forum.php?mod=viewthread&tid=11367 ):

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Security.Cryptography;
  5. using System.IO;

  6. namespace CSharpLibrary  
  7. {  
  8.     public class CSharpObject  
  9.     {
  10.         private static byte[] DES_IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
  11.         public static string Encrypt4Base64(string pToEncrypt, string sKey)
  12.         {
  13.             DESCryptoServiceProvider des = new DESCryptoServiceProvider();
  14.             des.Key = Encoding.GetEncoding("GBK").GetBytes(sKey);
  15.             des.IV = DES_IV;
  16.         
  17.             MemoryStream ms = new MemoryStream();
  18.             CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
  19.         
  20.             byte[] inputByteArray = Encoding.GetEncoding("GBK").GetBytes(pToEncrypt);
  21.             cs.Write(inputByteArray, 0, inputByteArray.Length);
  22.             cs.FlushFinalBlock();
  23.         
  24.             return Convert.ToBase64String(ms.ToArray());
  25.         }
  26.     }   
  27. }
复制代码

166

主题

2154

回帖

1万

积分

管理员

积分
13056
 楼主| 发表于 2017-11-16 00:23:55 | 显示全部楼层
AES加密算法多编程语言通用写法(aardio,php,c#,java等)
http://bbs.aardio.com/forum.php?mod=viewthread&tid=13818

1

主题

10

回帖

142

积分

一级会员

积分
142
发表于 2017-11-16 15:42:52 | 显示全部楼层

8

主题

110

回帖

904

积分

三级会员

积分
904
发表于 2017-11-16 16:43:29 | 显示全部楼层
这个不错,常用
您需要登录后才可以回帖 登录 | 注册会员

本版积分规则

手机版|未经许可严禁引用或转载本站文章|aardio.com|aardio 官方社区 ( 皖ICP备09012014号 )

GMT+8, 2025-2-13 06:55 , Processed in 0.062783 second(s), 25 queries .

Powered by Discuz! X3.5

Copyright © 2001-2024 Tencent Cloud.

快速回复 返回顶部 返回列表