JAVA版PKCS5填充模式3DES加解密类

DESCoder.java:

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package des;
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
*
* @author FarmerLuo
*/
public class DESCoder {
    private static BASE64Encoder base64 = new BASE64Encoder();
    private static byte[] myIV = { 50, 51, 52, 53, 54, 55, 56, 57 };
    //private static String strkey = "W9qPIzjaVGKUp7CKRk/qpCkg/SCMkQRu"; // 字节数必须是8的倍数
    private static String strkey = "01234567890123456789012345678912";
    public static String desEncrypt(String input) throws Exception
    {

        BASE64Decoder base64d = new BASE64Decoder();
        DESedeKeySpec p8ksp = null;
        p8ksp = new DESedeKeySpec(base64d.decodeBuffer(strkey));
        Key key = null;
        key = SecretKeyFactory.getInstance("DESede").generateSecret(p8ksp);

        byte[] plainBytes = (byte[])null;
        Cipher cipher = null;
        byte[] cipherText = (byte[])null;

        plainBytes = input.getBytes("UTF8");
        cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
        SecretKeySpec myKey = new SecretKeySpec(key.getEncoded(), "DESede");
        IvParameterSpec ivspec = new IvParameterSpec(myIV);
        cipher.init(1, myKey, ivspec);
        cipherText = cipher.doFinal(plainBytes);
        return removeBR(base64.encode(cipherText));

    }

    public static String desDecrypt(String cipherText) throws Exception
    {

        BASE64Decoder base64d = new BASE64Decoder();
        DESedeKeySpec p8ksp = null;
        p8ksp = new DESedeKeySpec(base64d.decodeBuffer(strkey));
        Key key = null;
        key = SecretKeyFactory.getInstance("DESede").generateSecret(p8ksp);

        Cipher cipher = null;
        byte[] inPut = base64d.decodeBuffer(cipherText);
        cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
        SecretKeySpec myKey = new SecretKeySpec(key.getEncoded(), "DESede");
        IvParameterSpec ivspec = new IvParameterSpec(myIV);
        cipher.init(2, myKey, ivspec);
        byte[] output = cipher.doFinal(inPut);
        return new String(output, "UTF8");

    }

    private static String removeBR(String str) {
        StringBuffer sf = new StringBuffer(str);

        for (int i = 0; i < sf.length(); ++i)
        {
          if (sf.charAt(i) == ‘n’)
          {
            sf = sf.deleteCharAt(i);
          }
        }
        for (int i = 0; i < sf.length(); ++i)
          if (sf.charAt(i) == ‘r’)
          {
            sf = sf.deleteCharAt(i);
          }

        return sf.toString();
      }
}

Main.java:

package des;

/**
*
* @author FarmerLuo
*/
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        try {
            String desstr = DESCoder.desEncrypt("12354");
            String pstr = DESCoder.desDecrypt(desstr);
            System.out.println("plainText:12354");
            System.out.println("Encode:"+desstr);
            System.out.println("Decode:"+pstr);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

运行结果:

run:
plainText:12354
Encode:pzilYggKgBU=
Decode:12354
成功生成(总时间:1 秒)

PHP版3DES加解密类更新成PKCS5填充模式

以前写的3DES加解密类是配合java程序做的,用的是no-pading模式,这次在以前的基础上做了修改,改成了pkcs5填充模式。

以前的类:
http://hi.baidu.com/farmerluo/blog/item/6154a7effd4dd011fdfa3c8b.html

<?php

/**
*
* PHP版3DES加解密类
*
* 可与java的3DES(DESede)加密方式兼容
*
* @Author: Luo Hui (farmer.luo at gmail.com)
*
* @version: v0.2 2010.04.16
*
* @changelogs:
* V0.2 : 由之前的no-pading方式改为pkcs5方式
* V0.1 : 2008.12.04
*
*/

class Crypt3Des
{  
    public $key    = "01234567890123456789012345678912";
    public $iv    = "23456789"; //like java: private static byte[] myIV = { 50, 51, 52, 53, 54, 55, 56, 57 };
  
    //加密
    public function encrypt($input)
    {
   $size = mcrypt_get_block_size(‘tripledes’, ‘cbc’);
   $input = $this->pkcs5_pad($input, $size); //pkcs5填充方式
        $key = base64_decode($this->key);
        $td = mcrypt_module_open( MCRYPT_3DES, ”, MCRYPT_MODE_CBC, ”);
        //使用MCRYPT_3DES算法,cbc模式
        mcrypt_generic_init($td, $key, $this->iv);
        //初始处理
        $data = mcrypt_generic($td, $input);
        //加密
        mcrypt_generic_deinit($td);
        //结束
        mcrypt_module_close($td);
        $data = $this->removeBR(base64_encode($data));
        return $data;
    }
  
    //解密
    public function decrypt($encrypted)
    {
        $encrypted = base64_decode($encrypted);
        $key = base64_decode($this->key);
        $td = mcrypt_module_open( MCRYPT_3DES,”,MCRYPT_MODE_CBC,”);
        //使用MCRYPT_3DES算法,cbc模式
        mcrypt_generic_init($td, $key, $this->iv);
        //初始处理
        $decrypted = mdecrypt_generic($td, $encrypted);
        //解密
        mcrypt_generic_deinit($td);
        //结束
        mcrypt_module_close($td);
   $decrypted = $this->pkcs5_unpad($decrypted); //pkcs5填充方式
        return $decrypted;
    }
  
    //删除回车和换行
    public function removeBR( $str )
    {
        $len = strlen( $str );
        $newstr = "";
        $str = str_split($str);
        for ($i = 0; $i < $len; $i++ )
        {
            if ($str[$i] != ‘n’ and $str[$i] != ‘r’)
            {
                $newstr .= $str[$i];
            }
        }
  
        return $newstr;
    }

public function pkcs5_pad($text, $blocksize)
{
   $pad = $blocksize – (strlen($text) % $blocksize);
   return $text . str_repeat(chr($pad), $pad);
}

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

}

//test
$input = "12354";
echo "plainText:" . $input."<br/>";
$crypt = new Crypt3Des();
echo "Encode:".$crypt->encrypt($input)."<br/>";
echo "Decode:".$crypt->decrypt($crypt->encrypt($input));
?>

运行结果:

plainText:12354
Encode:pzilYggKgBU=
Decode:12354