Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize aes encryption and decryption in PHP

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

How to implement aes encryption and decryption in PHP? in view of this problem, this article introduces the corresponding analysis and answer in detail, hoping to help more partners who want to solve this problem to find a more simple and easy way.

Aes encryption and decryption process

User data should be encrypted before transmission. This document is aes128 encryption (cbc mode). The summary algorithm is SHA-512.

Encryption:

Generate a 16-bit iv vector and use the iv and key to encrypt the original text

Stitching the encrypted real ciphertext with iv: iv+ real ciphertext

The ciphertext stitched with iv generates abstract information (128bits) with SHA-512 HMAC, and splices with the ciphertext: the ciphertext after HMAC+base64 to get the final ciphertext

Decryption:

Separate hmac and ciphertext, can carry out summary detection, can prevent timing attacks.

Get the original text with iv stitched together. Separate the iv and the real text

Use the key and iv to decode to get the original text

Encryption example php version

/ * encryption process * /

$str = "Hello World"

/ / 1. Use a 16-bit key

$key = '12345678901234ab'

/ / 2. Generate a custom 16-bit iv algorithm, which is directly specified in the example

/ / $iv = openssl_random_pseudo_bytes (16); / / 12345678ss1234ab

$iv= "12345678ss1234ab"

/ / 3. Encrypted IvdA7oP8BInWa5shY+LCyQ==

$secert_str = openssl_encrypt ($str, 'AES-128-CBC', $key, 0, $iv)

$secert_str = $iv. $secert_str; / / 4 Concatenate iv with ciphertext 12345678 ss1234abIvdA7oP8BInWa5shy

/ / 5.base64_encode considers language compatibility. This step is cancelled.

/ / 6. Generating Abstract 128bit hexadecimal 3b2106c05b46b603969c2b1bc7503c8233d209dcd204b098b33ba704507315480e03e499e0082e8842b60baa01f522d7c0342d75196d18d3514d37c58e31d733 with SHA-512

$hmac = hash_hmac ('sha512', $secert_str, $key, false)

/ / 7. Assemble the abstract to get the ciphertext

$secert_str = $hmac. $secert_str

Return urlencode ($secert_str)

Examples of decryption

$str=rawurldecode ($str)

$len = mb_strlen ($secert_str)

$ori_hmac = substr ($secert_str, 0128)

$data = substr ($secert_str, 128, $len)

/ / 2. Verification summary

$local_hmac = hash_hmac ('sha512', $data, $key, false)

$diff = 0

For ($I = 0; $I < 128; $iTunes +) {

$diff | = ord ($ori_hmac [$I]) ^ ord ($local_hmac [$I])

}

If ($diff! = = 0) {

Return FALSE

}

/ / 3. Separate iv

$len = mb_strlen ($data)

$iv = substr ($data, 0,16)

$data = substr ($data, 16, $len)

/ / 4. Decrypt and obtain the original text

$data = openssl_decrypt ($data, 'AES-128-CBC', $key, 0, $iv)

Java encryption and decryption class

Package main

Import javax.crypto.Cipher

Import javax.crypto.spec.IvParameterSpec

Import javax.crypto.spec.SecretKeySpec

Import javax.crypto.Mac

Import org.apache.commons.codec.binary.Base64

Import org.bouncycastle.util.encoders.Hex

Public class AESUtil {

/ * *

* aes/128/cbc encryption

* @ param sSrc plaintext

* @ param sKey key

* @ param sIv vector

* @ return

* @ throws Exception

, /

Public static String Encrypt (String sSrc, String sKey, String sIv) throws Exception {

If (sKey = = null) {

System.out.print ("Key is empty null")

Return null

}

/ / determine whether the Key is 16-bit

If (sKey.length ()! = 16) {

System.out.print ("Key length is not 16 bits")

Return null

}

/ / 1. Encrypt

Byte [] raw = sKey.getBytes ()

SecretKeySpec skeySpec = new SecretKeySpec (raw, "AES")

Cipher cipher = Cipher.getInstance ("AES/CBC/PKCS5Padding"); / / aes-cbc-pkcs5 (pkcs5 and pkcs7 are common)

IvParameterSpec iv = new IvParameterSpec (sIv.getBytes ()); / / using CBC mode, a vector iv is required to increase the strength of the encryption algorithm

Cipher.init (Cipher.ENCRYPT_MODE, skeySpec, iv)

Byte [] encrypted = cipher.doFinal (sSrc.getBytes ("UTF-8"))

String encryptedString = new String (Base64.encodeBase64 (encrypted))

/ / 2. Splicing iv

EncryptedString = sIv + encryptedString

/ / 3.sha512

String hmac = encodeHmacSHA512 (encryptedString, sKey)

/ / 4. Stitching summary

EncryptedString = hmac+encryptedString

/ / 5.urlencode

EncryptedString = URLEncoder.encode (encryptedString)

Return encryptedString

}

/ / decrypt

/ * *

*

* @ param sSrc ciphertext

* @ param sKey key

* @ return

* @ throws Exception

, /

Public static String Decrypt (String sSrc, String sKey) throws Exception {

Try {

/ / 0.urldecode

SSrc=URLDecoder.decode (sSrc)

/ / 1. Separation summary

System.out.println (sSrc)

String hmac=sSrc.substring (0128)

String data=sSrc.substring (128 SSRC. length ())

/ / 2. Verification summary

/ / 3. Separate iv

String sIv=data.substring (0pr 16)

String str=data.substring (16 data. Length ())

/ / 4. Decryption

Byte [] raw = sKey.getBytes ("UTF-8")

SecretKeySpec skeySpec = new SecretKeySpec (raw, "AES")

Cipher cipher = Cipher.getInstance ("AES/CBC/PKCS5Padding")

IvParameterSpec iv = new IvParameterSpec (sIv.getBytes ())

Cipher.init (Cipher.DECRYPT_MODE, skeySpec, iv)

Byte [] encrypted1 = Base64.decodeBase64 (str.getBytes ())

Try {

Byte [] original = cipher.doFinal (encrypted1)

String originalString = new String (original)

Return originalString

} catch (Exception e) {

System.out.println (e.toString ())

Return null

}

} catch (Exception ex) {

System.out.println (ex.toString ())

Return null

}

}

/ * *

* HmacSHA512 message digest

*

* @ param data data to be digested

* @ param key key

* @ return

, /

Public static String encodeHmacSHA512 (String data, String key) throws Exception {

Byte [] bytesKey = key.getBytes ()

SecretKeySpec secretKey = new SecretKeySpec (bytesKey, "HmacSHA512")

Mac mac = Mac.getInstance (secretKey.getAlgorithm ())

Mac.init (secretKey)

Final byte [] macData = mac.doFinal (data.getBytes ())

Byte [] hex = new Hex () .encode (macData)

String result = new String (hex, "ISO-8859-1")

Return result

}

}

Java instance

Import main.AESUtil

Public class Main {

Public static void main (String [] args) {

/ / key

String cKey = "12345678901234ab"

/ / string that needs to be encrypted

String cSrc = "Hello World"

/ / iv 16-bit algorithm is directly specified in the custom instance.

String sIv = "12345678ss1234ab"

String enString

String deString

Try {

EnString = AESUtil.Encrypt (cSrc, cKey, sIv)

System.out.println ("encrypted string is:" + enString)

DeString = AESUtil.Decrypt ("3b2106c05b46b603969c2b1bc7503c8233d209dcd204b098b33ba704507315480e0399e0082e8842b60baa01f522d7c0342d75196d18d3514d37c58e31d733345678ss1234abIvdA7P8BInWa5YY LCyQcertificates =", cKey)

System.out.println ("the decrypted string is:" + deString)

} catch (Exception e) {

E.printStackTrace ()

}

}

}

This is the answer to the question about how to implement aes encryption and decryption in PHP. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel to learn more about it.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report