TripleDES加解密Java、C#、php

TripleDES说明:
    TripleDES(3Des)和Des都是对称加密算法,TripleDes是Des加密算法的增强版本,这里主要说的是TripleDes加密算法的应用。
    工作中由于涉及到不同系统的对接,整理了Java、C#和php通用的算法代码,直接看代码:
Java版本:
package com.jaamy.common.util;
    
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
    
public class DefaultEncryptor {
        
    private static final String ALGORITHM = "DESede";
    
    //默认为 DESede/ECB/PKCS5Padding
    private static final String CIPHER_TRANSFORMAT = "DESede/ECB/PKCS5Padding";
    
    private static final String ENCODING = "UTF-8";
         
    public static String encryptToBase64(String plainText, String key) throws Exception {
        SecretKey deskey = new SecretKeySpec(key.getBytes(), ALGORITHM);
        Cipher c1 = Cipher.getInstance(CIPHER_TRANSFORMAT);
        c1.init(Cipher.ENCRYPT_MODE, deskey);
        byte[] result = c1.doFinal(plainText.getBytes(ENCODING));     
        return Base64.encodeBase64String(result);
     }
   
    public static String decryptFromBase64(String base64, String key) throws Exception {
        SecretKey deskey = new SecretKeySpec(key.getBytes(), ALGORITHM);
        Cipher c1 = Cipher.getInstance(CIPHER_TRANSFORMAT);
        c1.init(Cipher.DECRYPT_MODE, deskey);
        byte[] result = c1.doFinal(Base64.decodeBase64(base64));      
        return new String(result, ENCODING);
    }
}

C#代码:

using System;
using System.IO;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Web;
   
namespace DesEncryptor
{
    class DefaultEncryptor
    {
        #region DES 加密
        public static string encryptToBase64(string plainText, string key)
        {
            try
            {
                // Create a MemoryStream.
                MemoryStream mStream = new MemoryStream();
                TripleDESCryptoServiceProvider tripleDESCryptoServiceProvider = new TripleDESCryptoServiceProvider();
                tripleDESCryptoServiceProvider.Key = Encoding.ASCII.GetBytes(key);
                tripleDESCryptoServiceProvider.Padding = PaddingMode.PKCS7;//补位
                tripleDESCryptoServiceProvider.Mode = CipherMode.ECB;//CipherMode.CBC
                CryptoStream cStream = new CryptoStream(mStream,
                    tripleDESCryptoServiceProvider.CreateEncryptor(),
                    CryptoStreamMode.Write);
   
                // Convert the passed string to a byte array.
                byte[] toEncrypt = Encoding.UTF8.GetBytes(plainText);
   
                // Write the byte array to the crypto stream and flush it.
                cStream.Write(toEncrypt, 0, toEncrypt.Length);
                cStream.FlushFinalBlock();
   
                // Get an array of bytes from the
                // MemoryStream that holds the
                // encrypted data.
                byte[] ret = mStream.ToArray();
   
                // Close the streams.
                cStream.Close();
                mStream.Close();
   
                // Return the encrypted buffer.
                return Convert.ToBase64String(ret);
            }
            catch (CryptographicException e)
            {
                Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
                return null;
            }
        }
        #endregion
   
        #region DES解密
        public static string decryptFromBase64(string base64, string key)
        {
            try
            {
                byte[] inputByteArray = Convert.FromBase64String(base64);
                // Create a new MemoryStream using the passed
                // array of encrypted data.
                MemoryStream msDecrypt = new MemoryStream(inputByteArray);
   
                // Create a CryptoStream using the MemoryStream
                TripleDESCryptoServiceProvider tripleDESCryptoServiceProvider = new TripleDESCryptoServiceProvider();
                tripleDESCryptoServiceProvider.Key = ASCIIEncoding.ASCII.GetBytes(key);
                tripleDESCryptoServiceProvider.Padding = PaddingMode.PKCS7;//补位
                tripleDESCryptoServiceProvider.Mode = CipherMode.ECB;//CipherMode.CBC
                CryptoStream csDecrypt = new CryptoStream(msDecrypt,
                    tripleDESCryptoServiceProvider.CreateDecryptor(),
                    CryptoStreamMode.Read);
   
                // Create buffer to hold the decrypted data.
                byte[] fromEncrypt = new byte[inputByteArray.Length];
   
                // Read the decrypted data out of the crypto stream
                // and place it into the temporary buffer.
                csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);
   
                //Convert the buffer into a string and return it.
                return Encoding.UTF8.GetString(fromEncrypt).TrimEnd('\0');
            }
            catch (CryptographicException e)
            {
                Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
                return null;
            }
   
        }
        #endregion
    }
}

PHP代码:

<?php
class CryptDes {
                     
     function encrypt($input, $key){
         $size = mcrypt_get_block_size(MCRYPT_3DES,MCRYPT_MODE_ECB);
         $input = $this->pkcs5_pad($input, $size);
         $key = str_pad($key,24,'0');
         $td = mcrypt_module_open(MCRYPT_3DES, '', MCRYPT_MODE_ECB, '');
         $iv = @mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
         @mcrypt_generic_init($td, $key, $iv);
         $data = mcrypt_generic($td, $input);
         mcrypt_generic_deinit($td);
         mcrypt_module_close($td);
         $data = base64_encode($data);
         return $data;
     }
                 
     function decrypt($encrypted, $key){
         $encrypted = base64_decode($encrypted);
         $key = str_pad($key,24,'0');
         $td = mcrypt_module_open(MCRYPT_3DES,'',MCRYPT_MODE_ECB,'');
         $iv = @mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
         $ks = mcrypt_enc_get_key_size($td);
         @mcrypt_generic_init($td, $key, $iv);
         $decrypted = mdecrypt_generic($td, $encrypted);
         mcrypt_generic_deinit($td);
         mcrypt_module_close($td);
         $y=$this->pkcs5_unpad($decrypted);
         return $y;
     }
                 
     function pkcs5_pad ($text, $blocksize) {
         $pad = $blocksize - (strlen($text) % $blocksize);
         return $text . str_repeat(chr($pad), $pad);
     }
                 
     function pkcs5_unpad($text){
         $pad = ord($text{strlen($text)-1});
         if ($pad > strlen($text)) {
             return false;
         }
         if (strspn($text, chr($pad), strlen($text) - $pad) != $pad){
             return false;
         }
         return substr($text, 0, -1 * $pad);
     }
}
                 
$des = new CryptDes();
$encrypt_str = $des->encrypt("1111","012345678901234567890123");//加密字符串
echo $encrypt_str."\n";
echo $decrypt_str = $des->decrypt($encrypt_str,"012345678901234567890123");//解密字符串
?>

 

 

posted @ 2019-06-11 14:43  Aaronguo  阅读(878)  评论(0编辑  收藏  举报