标签:std AES ECB ctx openssl outlen str key EVP
在 java 上进行 AES128/ECB/PKCS5Padding 加密解密是很简单的
public static String aesDecrypt(String str,String key) throws Exception{
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE,new SecretKeySpec(Base64.getDecoder().decode(key),"AES"));
byte[] bytes = Base64.getDecoder().decode(str.getBytes(StandardCharsets.UTF_8));
byte[] ret = cipher.doFinal(bytes);
return new String(ret,"UTF-8");
}
public static String aesEncrypt(String str,String key) throws Exception {
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE,new SecretKeySpec(Base64.getDecoder().decode(key),"AES"));
return Base64.getEncoder().encodeToString(cipher.doFinal(str.getBytes()));
}
AES 加解密使用的key本身是 16 字节(128位),但是key可能不是ascii里的可见字符,有时候我们把 key 进行 base64 编码之后,当作明文传输使用。真正把 key 用来加密解密的时候,需要先 base64 解码来得到原本的 key。
同样的,经过AES加密的信息也有可能不是每一个字节都是ascii可见字符,我们同样将加密后的密文进行base64编码之后再展示。
同样的操作,用 C/C++ 进行就复杂得多,C/C++ 自己本身没有对应的库,不过好在有很多开源的实现,这里用 openssl 作为演示
#include <openssl/evp.h>
#include <vector>
std::string AES128ECBEncrypt(const std::string& base64key, const std::string& str)
{
std::vector<unsigned char> key;
if (!Base64Decode(base64key, key))
return "";
EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new();
int encLen = 0;
int outlen = 0;
size_t outsize = ((str.size() / 16)+1) * 16;
std::vector<unsigned char> encData(outsize);
EVP_CipherInit_ex(ctx, EVP_aes_128_ecb(), NULL, key.data(), NULL, 1);
EVP_CipherUpdate(ctx, encData.data(), &outlen, (const unsigned char*)str.c_str(), (int)str.size());
encLen = outlen;
EVP_CipherFinal_ex(ctx, encData.data() + outlen, &outlen);
encLen += outlen;
EVP_CIPHER_CTX_free(ctx);
return std::move(Base64Encode(encData.data(), encLen));
}
std::string AES128ECBDecrypt(const std::string& base64Key, const std::string& base64str)
{
std::vector<unsigned char> buffer;
if (!Base64Decode(base64str, buffer))
{
return "";
}
std::vector<unsigned char> key;
if (!Base64Decode(base64Key, key))
{
return "";
}
EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new();
int encLen = 0;
int outlen = 0;
BUFFER encData(buffer.size());
EVP_CipherInit_ex(ctx, EVP_aes_128_ecb(), NULL, key.data(), NULL, 0);
EVP_CipherUpdate(ctx, encData.data(), &outlen, buffer.data(), (int)buffer.size());
encLen = outlen;
EVP_CipherFinal(ctx, encData.data() + outlen, &outlen);
encLen += outlen;
EVP_CIPHER_CTX_free(ctx);
return std::move(std::string((char*)encData.data(), encLen));
}
标签:std,AES,ECB,ctx,openssl,outlen,str,key,EVP 来源: https://www.cnblogs.com/SupperMary/p/16559826.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。