Home Backend Development PHP Tutorial PHP、Java des加密解密实例_php实例

PHP、Java des加密解密实例_php实例

Jun 07, 2016 pm 05:13 PM
des java php encrypt and decode

des加密是对称加密中在互联网应用的比较多的一种加密方式,php 通过mcrypt扩展库来支持des加密,要在Php中使用des加密,需要先安装mcrypt扩展库

下面是加密解密的实例

复制代码 代码如下:

$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB); 
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND); 
$key = "This is a very secret key";//密钥 
$text = "Meet me at 11 o'clock behind the monument.";//需要加密的内容 
echo ($text) . "\n"; 
 
$crypttext =base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_ECB, $iv)); 
echo $crypttext . "\n";//加密后的内容 
 
echo mcrypt_decrypt(MCRYPT_RIJNDAEL_256,$key,base64_decode($crypttext),MCRYPT_MODE_ECB,$iv);//解密后的内容 

在AES加密算法中通常会用到MCRYPT_RIJNDAEL_128、MCRYPT_RIJNDAEL_192、MCRYPT_RIJNDAEL_256三种,后面的128、192、256代表的是秘钥(也就是加密的Key)是多少bit的,比如使用的是MCRYPT_RIJNDAEL_128,那么用这个算法加密时秘钥长度就是128bit的,比如 $key = 'fjjda0&9^$$#+*%$fada',是20个字符,那在实际加密的时候只用到前16个字符加密(16*8=128),不足128bit的php中会用'\0'来补齐。

有的时候做项目对接的时候,可能你用的是Php加密的,而对方用的是java写的,对接的过程中就发现机加密后的内容对方解密不了,这是因为Php跟java在实现这个算法的时候有差别,要想正确加密解密需要两边都做下处理:

PHP:

复制代码 代码如下:

class Security { 
    public static function encrypt($input, $key) { 
        $size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB); 
        $input = Security::pkcs5_pad($input, $size); 
        $td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', 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; 
    } 
  
    private static function pkcs5_pad ($text, $blocksize) { 
        $pad = $blocksize - (strlen($text) % $blocksize); 
        return $text . str_repeat(chr($pad), $pad); 
    } 
  
    public static function decrypt($sStr, $sKey) { 
        $decrypted= mcrypt_decrypt( 
        MCRYPT_RIJNDAEL_128, 
        $sKey, 
        base64_decode($sStr), 
        MCRYPT_MODE_ECB 
    ); 
  
        $dec_s = strlen($decrypted); 
        $padding = ord($decrypted[$dec_s-1]); 
        $decrypted = substr($decrypted, 0, -$padding); 
        return $decrypted; 
    }    

  
  
  
$key = "1234567891234567"; 
$data = "example"; 
  
$value = Security::encrypt($data , $key ); 
echo $value.'
'; 
echo Security::decrypt($value, $key ); 

Java:
复制代码 代码如下:

import javax.crypto.Cipher; 
import javax.crypto.spec.SecretKeySpec; 
  
import org.apache.commons.codec.binary.Base64; 
  
public class Security { 
    public static String encrypt(String input, String key){ 
        byte[] crypted = null; 
        try{ 
            SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES"); 
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); 
            cipher.init(Cipher.ENCRYPT_MODE, skey); 
            crypted = cipher.doFinal(input.getBytes()); 
        }catch(Exception e){ 
        System.out.println(e.toString()); 
    } 
    return new String(Base64.encodeBase64(crypted)); 

  
    public static String decrypt(String input, String key){ 
        byte[] output = null; 
        try{ 
            SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES"); 
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); 
            cipher.init(Cipher.DECRYPT_MODE, skey); 
            output = cipher.doFinal(Base64.decodeBase64(input)); 
            }catch(Exception e){ 
            System.out.println(e.toString()); 
        } 
        return new String(output); 
    } 
  
    public static void main(String[] args) { 
        String key = "1234567891234567"; 
        String data = "example"; 
         
        System.out.println(Security.encrypt(data, key)); 
         
        System.out.println(Security.decrypt(Security.encrypt(data, key), key)); 
         
             
    }    

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

Java Made Simple: A Beginner's Guide to Programming Power Java Made Simple: A Beginner's Guide to Programming Power Oct 11, 2024 pm 06:30 PM

Java Made Simple: A Beginner's Guide to Programming Power Introduction Java is a powerful programming language used in everything from mobile applications to enterprise-level systems. For beginners, Java's syntax is simple and easy to understand, making it an ideal choice for learning programming. Basic Syntax Java uses a class-based object-oriented programming paradigm. Classes are templates that organize related data and behavior together. Here is a simple Java class example: publicclassPerson{privateStringname;privateintage;

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

See all articles