先看java代码
Java代码
- public static String encrypt(String message, String key) 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 toHexString(cipher.doFinal(message.getBytes("UTF-8")));
- }
- public static String decrypt(String message, String key) 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[] 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();
- }
java写的已经很明显使用的是CBC/PKCS补码方式
在看PHP
Php代码
- function encrypt($str) {
- //加密,返回大写十六进制字符串
- $size = mcrypt_get_block_size (MCRYPT_DES, MCRYPT_MODE_[color=red]CBC[/color] );
- $str = $this->pkcs5Pad ( $str, $size );
- return strtoupper( bin2hex( mcrypt_cbc(MCRYPT_DES, $this->key, $str, MCRYPT_ENCRYPT, $this->iv ) ) );
- }
- function decrypt($str) {
- //解密
- $strBin = $this->hex2bin( strtolower( $str ) );
- $str = mcrypt_cbc( MCRYPT_DES, $this->key, $strBin, MCRYPT_DECRYPT, $this->iv );
- $str = $this->pkcs5Unpad( $str );
- return $str;
- }
- function hex2bin($hexData) {
- $binData = "";
- for($i = 0; $i < strlen ( $hexData ); $i += 2) {
- $binData .= chr ( hexdec ( substr ( $hexData, $i, 2 ) ) );
- }
- return $binData;
- }
- function pkcs5Pad($text, $blocksize) {
- $pad = $blocksize - (strlen ( $text ) % $blocksize);
- return $text . str_repeat ( chr ( $pad ), $pad );
- }
- function pkcs5Unpad($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 );
- }
java/php DES/CBC/PKCS5Padding加密解密算法实现过程
时间: 2024-10-10 22:16:27