AES加密的使用笔记(ECB和GCM加密模式-前端)

AES加密的官方简介

AES是高级加密标准,在密码学中又称Rijndael加密法,是美国联邦政府采用的一种区块加密标准。这个标准用来替代原先的DES,目前已经被全世界广泛使用,同时AES已经成为对称密钥加密中最流行的算法之一。AES支持三种长度的密钥:128位,192位,256位。

和后端做加密对接重点关注的点

  1. 确认加密方式, key(密钥长度必须为16,24,32位),iv值(用于增加加密算法安全性,使用随机数),工作模式,以及是16进制加密还是Base64的。
  2. 确认以后可以让后端提供一个他加密后的密文,自己反向写一个解密方法,成功解出,然后再写一个对应的加密方式,将密文交给后端成功解除,即对应。

备注: 关于IV的官方说法, IV是初始化向量(initialization vector)的缩写,是在密码学中用于增强加密算法安全性的一种辅助参数。IV是一个固定长度的输入值,一般要求是随机数或拟随机数,使用随机数产生的初始化向量才能达到语义安全,并让攻击者难以对同一把密钥的密文进行破解。在区块加密中,使用了初始化向量的加密模式被称为区块加密模式。

关于加密模式的介绍很多,这里就不介绍了,主要记录自己用过的两种加密方法,并且附上对应的解密方法。

ECB模式

这里使用crypto-js插件。根据自己的项目情况,使用npm 或yarn等去下载依赖包,

npm下载命令格式

npm install 依赖包名称

yarn下载命令格式

yarn add 依赖包名称

加密方法如下,我的是vue项目

import CryptoJS from "crypto-js/crypto-js";

// 默认的 KEY 与 iv 使用AES-128-CBC加密模式,key需要为16位,key和iv可以相同
//ciphertext 16进制加密,不加此方法就是Base64加密


// AES加密 :字符串 key 返回base64
export function Encrypt(word, keyStr, ivStr) {
 const KEY = CryptoJS.enc.Utf8.parse("密钥");
  //密钥
  let key = KEY;
  if (keyStr) {
    key = CryptoJS.enc.Utf8.parse(keyStr);
  }

  let srcs = CryptoJS.enc.Utf8.parse(word);
  //密文
  var encrypted = CryptoJS.AES.encrypt(srcs, key, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  });
  return CryptoJS.enc.Base64.stringify(encrypted.ciphertext);
}

解密方法

export function Decrypt(word, keyStr,ivstr){
   const KEY = CryptoJS.enc.Utf8.parse("密钥");
   var base64  = CryptoJS.enc.Base64.parse(txt.replace(/\s+/g,""));
   var srcs = CryptoJS.enc.Base64.stringify(base64);
        var decryptedData = CryptoJS.AES.decrypt(srcs, KEY, {
         mode: CryptoJS.mode.ECB,
         padding: CryptoJS.pad.Pkcs7
      });
    return  decryptedData.toString(CryptoJS.enc.Utf8);
}

GCM模式

使用的是node-forge插件,下载方式和上面说的一样,就不介绍了,如果不确定的可以自行去npm或者yarn官网去搜

加密算法

import forge from "node-forge";

const keyStr = "密钥"; //这里我用的是base64所以没有对密钥进行转换,直接赋值,如果是16进制需要转换一下。

export function Encrypt(word) {
  var iv = forge.random.getBytesSync(12); // 生成随机iv 12字节
  var cipher = forge.cipher.createCipher("AES-GCM", keyStr); // 生成AES-GCM模式的cipher对象 并传入密钥
  cipher.start({
    iv: iv
  });
  cipher.update(forge.util.createBuffer(forge.util.encodeUtf8(word)));
  cipher.finish();
  var encrypted = cipher.output;
  var tag = cipher.mode.tag;
  return window.btoa(iv + encrypted.data + tag.data);
}

解密

const   KEY = "密钥"
export function Decrypt(word) {
  datamsg = window.atob(txt)
  const iv = datamsg.slice(0, 12)
  const tag = datamsg.slice(-16)
  const data = datamsg.slice(12, datamsg.length - 16)
  var decipher = forge.cipher.createDecipher('AES-GCM', KEY)
  decipher.start({
    iv: iv,
    tag: tag
  })
  decipher.update(forge.util.createBuffer(data))
  const pass = decipher.finish()
  return  decipher.output.toString()
}

另外自己简单写了一个纯JS的加解密小工具,方便自测的时候套用各种加解密方式,代码如下,不是标准答案,需要根据自己的加密方式算法等去进行js部分的替换调整。

<!DOCTYPE html>
<html>
<head>
	<title>加密小工具</title>
</head>
<body>
  <textarea name="jiami" rows="10" cols="40" id="content"></textarea>
  <br>
  <button onclick="jiami()">加密</button>
  <button onclick="jiemi()">解密</button>
  <p>结果: <label id='result'></label></p>
</body>
<script src="https://cdn.jsdelivr.net/npm/node-forge@1.0.0/dist/forge.min.js"></script> //这里换成自己再用的加密方式的cdn,
<script type="text/javascript">
	function jiami() {
		var txt = document.getElementById('content').value
		var KEY = "密钥"
		// var srcs = CryptoJS.enc.Utf8.parse(txt.replace(/\s+/g,""));
		var iv =  forge.random.getBytesSync(12)  // 生成随机iv 12字节
         var cipher  = forge.cipher.createCipher('AES-GCM', KEY); // 生成AES-GCM模式的cipher对象 并传入密钥
          cipher.start({
           iv: iv
        });
        cipher.update(forge.util.createBuffer(forge.util.encodeUtf8(txt)));
        cipher.finish();
        var encrypted = cipher.output;
        var tag = cipher.mode.tag;
       // return btoa(iv+encrypted.data+tag.data)
       document.getElementById('result').innerHTML = btoa(iv+encrypted.data+tag.data)
	};

	function jiemi(){
		var txt = document.getElementById('content').value
		var KEY = "密钥"
		 datamsg = window.atob(txt)
          const iv = datamsg.slice(0, 12)
          const tag = datamsg.slice(-16)
          const data = datamsg.slice(12, datamsg.length - 16)
          var decipher = forge.cipher.createDecipher('AES-GCM', KEY)
          decipher.start({
           iv: iv,
           tag: tag
       })
        decipher.update(forge.util.createBuffer(data))
        const pass = decipher.finish()
       if (pass) {
         document.getElementById('result').innerHTML =  decipher.output.toString()
        }

	}

</script>
</html>
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
首先,你需要在iOS项目中添加OpenSSL库并导入头文件。可以使用CocoaPods来安装OpenSSL,也可以手动下载并添加到项目中。 在使用OpenSSL加密之前,需要先初始化库: ``` #include <openssl/evp.h> EVP_CIPHER_CTX *ctx; ctx = EVP_CIPHER_CTX_new(); ``` 接下来,我们可以使用EVP接口实现AES-GCM加密。以下是一个示例代码: ``` #include <openssl/rand.h> void aes_gcm_encrypt(unsigned char *plaintext, int plaintext_len, unsigned char *aad, int aad_len, unsigned char *key, unsigned char *iv, int iv_len, unsigned char *ciphertext, unsigned char *tag) { EVP_CIPHER_CTX *ctx; int len; int ciphertext_len; // Create and initialise the context if (!(ctx = EVP_CIPHER_CTX_new())) handleErrors(); // Initialise the encryption operation. if (1 != EVP_EncryptInit_ex(ctx, EVP_aes_128_gcm(), NULL, NULL, NULL)) handleErrors(); // Set IV length if (1 != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, iv_len, NULL)) handleErrors(); // Set tag length if (1 != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, 16, NULL)) handleErrors(); // Initialise key and IV if (1 != EVP_EncryptInit_ex(ctx, NULL, NULL, key, iv)) handleErrors(); // Provide any non-AAD data if (aad_len > 0) { if (1 != EVP_EncryptUpdate(ctx, NULL, &len, aad, aad_len)) handleErrors(); } // Provide the message to be encrypted, and obtain the ciphertext if (1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len)) handleErrors(); ciphertext_len = len; // Finalise the encryption if (1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len)) handleErrors(); ciphertext_len += len; // Get the tag if (1 != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, 16, tag)) handleErrors(); // Clean up EVP_CIPHER_CTX_free(ctx); } ``` 在此示例中,我们使用EVP_aes_128_gcm()进行AES-GCM加密。我们还提供了一个AAD(Additional Authenticated Data)参数,它是与加密数据一起传输的附加信息。最后,我们获得了加密后的密文和GCM标签。 下面是一个使用ECB模式进行加密的示例代码: ``` void aes_ecb_encrypt(unsigned char *plaintext, int plaintext_len, unsigned char *key, unsigned char *ciphertext) { EVP_CIPHER_CTX *ctx; int len; int ciphertext_len; // Create and initialise the context if (!(ctx = EVP_CIPHER_CTX_new())) handleErrors(); // Initialise the encryption operation. if (1 != EVP_EncryptInit_ex(ctx, EVP_aes_128_ecb(), NULL, key, NULL)) handleErrors(); // Provide the message to be encrypted, and obtain the ciphertext if (1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len)) handleErrors(); ciphertext_len = len; // Finalise the encryption if (1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len)) handleErrors(); ciphertext_len += len; // Clean up EVP_CIPHER_CTX_free(ctx); } ``` 在此示例中,我们使用EVP_aes_128_ecb()进行ECB加密。 这里的示例仅供参考,实际实现过程中需要根据具体情况进行调整。同时,为了保护数据安全,建议在使用OpenSSL时遵循最佳安全实践,例如使用随机生成的IV、密钥和盐值等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值