aes加密解密

Posted 岁月峥嵘走过

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了aes加密解密相关的知识,希望对你有一定的参考价值。

from Crypto import Random
from Crypto.Cipher import AES
import base64
from hashlib import md5

BLOCK_SIZE = 16



# https://blog.csdn.net/weixin_39912163/article/details/111422488
def pad(data):
    length = BLOCK_SIZE - (len(data) % BLOCK_SIZE)
    return data + (chr(length)*length).encode()

def unpad(data):
    return data[:-(data[-1] if type(data[-1]) == int else ord(data[-1]))]

def bytes_to_key(data, salt, output=48):
    # extended from https://gist.github.com/gsakkis/4546068
    assert len(salt) == 8, len(salt)
    data += salt
    key = md5(data).digest()
    final_key = key
    while len(final_key) < output:
        key = md5(key + data).digest()
        final_key += key
    return final_key[:output]

def encrypt(message, passphrase):
    salt = Random.new().read(8)
    key_iv = bytes_to_key(passphrase.encode(), salt, 32+16)
    key = key_iv[:32]
    iv = key_iv[32:]
    aes = AES.new(key, AES.MODE_CBC, iv)
    return base64.b64encode(b"Salted__" + salt + aes.encrypt(pad(message)))

def decrypt(encrypted, passphrase):
    encrypted = base64.b64decode(encrypted)
    assert encrypted[0:8] == b"Salted__"
    salt = encrypted[8:16]
    key_iv = bytes_to_key(passphrase.encode(), salt, 32+16)
    key = key_iv[:32]
    iv = key_iv[32:]
    aes = AES.new(key, AES.MODE_CBC, iv)
    return unpad(aes.decrypt(encrypted[16:]))


# password = "some password".encode()
# ct_b64 = "U2FsdGVkX1+ATH716DgsfPGjzmvhr+7+pzYfUzR+25u0D7Z5Lw04IJ+LmvPXJMpz"
# # ct_b64 = "U2FsdGVkX1+ATH716DgsfPGjzmvhr+7+pzYfUzR+25u0D7Z5Lw04IJ+LmvPXJMpz"
#
# pt = decrypt(ct_b64, password)
# print("pt", pt)
#
# print("pt", decrypt(encrypt(pt, password), password))


passphrase = "passphrase"

test = "U2FsdGVkX187CV++0s/Eoo6Y4O1mJqcbofVFvTfBU5g="

result = decrypt(test, passphrase).decode(\'utf-8\')

print(result)

a = encrypt("hello world".encode(),passphrase)

print(a.decode())


result = decrypt(a, passphrase).decode(\'utf-8\')

print(result)

import CryptoJS from \'crypto-js\';

const KEY = \'passphrase\'; // 此key需与后端一致


// 加密
function encrypt(data) {
  const encrypt = CryptoJS.AES.encrypt(data, KEY)
  return encrypt.toString();
}
  
  // 解密
function decrypt(data) {
  const decrypt = CryptoJS.AES.decrypt(data, KEY)
  return decrypt.toString(CryptoJS.enc.Utf8);
}

export { encrypt, decrypt};

以上是关于aes加密解密的主要内容,如果未能解决你的问题,请参考以下文章

QT:AES-256-CBC 根据 PHP 代码在 C++ 中加密/解密

更新实现代码对称加密与解密剖析:AES,高级加密标准(Advanced Encryption Standard,缩写AES)

AES加密解密代码

使用ffmpeg视频切片并加密

Android通过AES128加密解密字符串的代码

基于AES对称加密解密的代码块