AES加密算法源代码

合集下载

AES加密算法c语言实现代码

AES加密算法c语言实现代码
DES_ROL(temp,MOVE_TIMES[cnt]);/*循环左移*/ DES_PC2_Transform(temp,subKeys[cnt]);/*PC2置换,产生子密钥*/ } return 0; }
/*密钥置换1*/ int DES_PC1_Transform(ElemType key[64], ElemType tempbts[56]){ int cnt; for(cnt = 0; cnt < 56; cnt++){
AES加密算法c语言实现代码
/*将二进制位串转为长度为8的字符串*/ int Bit64ToChar8(ElemType bit[64],ElemType ch[8]){ int cnt; memset(ch,0,8); for(cnt = 0; cnt < 8; cnt++){
BitToByte(bit+(cnt<<3),ch+cnt); } return 0; }
/*扩充置换表E*/ int E_Table[48] = {31, 0, 1, 2, 3, 4, 3, 4, 5, 6, 7, 8, 7, 8,9,10,11,12, 11,12,13,14,15,16, 15,16,17,18,19,20, 19,20,21,22,23,24, 23,24,25,26,27,28, 27,28,29,30,31, 0};
/*对左移次数的规定*/ int MOVE_TIMES[16] = {1,1,2,2,2,2,2,2,1,2,2,2,2,2,2,1};
int ByteToBit(ElemType ch,ElemType bit[8]); int BitToByte(ElemType bit[8],ElemType *ch); int Char8ToBit64(ElemType ch[8],ElemType bit[64]); int Bit64ToChar8(ElemType bit[64],ElemType ch[8]); int DES_MakeSubKeys(ElemType key[64],ElemType subKeys[16][48]); int DES_PC1_Transform(ElemType key[64], ElemType tempbts[56]); int DES_PC2_Transform(ElemType key[56], ElemType tempbts[48]); int DES_ROL(ElemType data[56], int time); int DES_IP_Transform(ElemType data[64]); int DES_IP_1_Transform(ElemType data[64]); int DES_E_Transform(ElemType data[48]); int DES_P_Transform(ElemType data[32]); int DES_SBOX(ElemType data[48]); int DES_XOR(ElemType R[48], ElemType L[48],int count); int DES_Swap(ElemType left[32],ElemType right[32]); int DES_EncryptBlock(ElemType plainBlock[8], ElemType subKeys[16][48], ElemType cipherBlock[8]); int DES_DecryptBlock(ElemType cipherBlock[8], ElemType subKeys[16][48], ElemType plainBlock[8]); int DES_Encrypt(char *plainFile, char *keyStr,char *cipherFile); int DES_Decrypt(char *cipherFile, char *keyStr,char *plainFile);

AES加密算法源代码

AES加密算法源代码

AES加密算法源代码AES加密算法源代码//AES.h#define decrypt TRUE#define encrypt FALSE#define TYPE BOOLtypedef struct _AES{int Nb;int Nr;int Nk;unsigned long *Word;unsigned long *State;}AES;/*加密数据byte *input 明文byte *inSize 明文长byte *out 密文存放的地方byte *key 密钥keybyte *keySize 密钥长*/void Cipher(unsigned char* input,int inSize,unsigned char* out,unsigned char* key,int keySize);/*解密数据byte *input 密文int *inSize 密文长byte *out 明文存放的地方byte *key 密钥keyint *keySize 密钥长*/void InvCipher(unsigned char* input,int inSize,unsigned char* out, unsigned char* key,int keySize);/*生成加密用的参数AES结构int inSize 块大小byte* 密钥int 密钥长unsigned long 属性(标实类型) 返回AES结构指针*/AES *InitAES(AES *aes,int inSize,unsigned char* key,int keySize, TYPE type);生成加密用的参数AES结构int inSize 块大小byte* 密钥int 密钥长返回AES结构指针*/AES *InitAES(int inSize,unsigned char* key,int keySize, BOOL );/*加密时进行Nr轮运算AES * aes 运行时参数*/void CipherLoop(AES *aes);/*解密时进行Nr轮逆运算AES * aes 运行时参数*/void InvCipherLoop(AES *aes);/*释放AES结构和State和密钥库word */void freeAES(AES *aes);//AES.cpp#include "stdafx.h"#include#include#include "AES.h"unsigned char* SubWord(unsigned char* word);unsigned long* keyExpansion(unsigned char* key, int Nk, int Nr,int);/*加密数据byte *input 明文byte *inSize 明文长byte *out 密文存放的地方byte *key 密钥keybyte *keySize 密钥长*/void Cipher(unsigned char* input, int inSize, unsigned char* out, unsigned char* key, int keySize){AES aes ;InitAES(&aes,inSize,key,keySize,encrypt);memcpy(aes.State,input,inSize);CipherLoop(&aes);memcpy(out,aes.State,inSize);}解密数据byte *input 密文int *inSize 密文长byte *out 明文存放的地方byte *key 密钥keyint *keySize 密钥长*/void InvCipher(unsigned char* input, int inSize, unsigned char* out, unsigned char* key, int keySize){AES aes;InitAES(&aes,inSize,key,keySize,decrypt);memcpy(aes.State,input,inSize);InvCipherLoop(&aes);memcpy(aes.State,out,inSize);}/*生成加密用的参数AES结构int inSize 块大小byte* 密钥int 密钥长返回AES结构指针*/AES *InitAES(AES *aes,int inSize, unsigned char *key, int keySize, TYPE type){int Nb = inSize >>2,Nk = keySize >>2,Nr = Nb < Nk ? Nk:Nb+6;aes->Nb = Nb;aes->Nk = Nk;aes->Nr = Nr;aes->Word = keyExpansion(key,Nb,Nr,Nk);aes->State = new unsigned long[Nb+3];if(type)aes->State += 3;return aes;}/*生成加密用的参数AES结构int inSize 块大小byte* 密钥int 密钥长返回AES结构指针*/AES *InitAES(int inSize, unsigned char*key, int keySize,unsigned long type){return InitAES(new AES(),inSize,key,keySize,type); }/**/void CipherLoop(AES *aes){unsigned char temp[4];unsigned long *word8 = aes->Word,*State = aes->State;int Nb = aes->Nb,Nr = aes->Nr;int r;for (r = 0; r < Nb; ++r) {State[r] ^= word8[r];}for (int round =1; round { word8 += Nb;/*假设Nb=4;---------------------| s0 | s1 | s2 | s3 |---------------------| s4 | s5 | s6 | s7 |---------------------| s8 | s9 | sa | sb |---------------------| sc | sd | se | sf |---------------------| | | | |---------------------| | | | |---------------------| | | | |---------------------*/memcpy(State+Nb,State,12);/*Nb=4;---------------------| s0 | | | |---------------------| s4 | s5 | | |---------------------| s8 | s9 | sa | |---------------------| sc | sd | se | sf |---------------------| | s1 | s2 | s3 |---------------------| | | s6 | s7 |---------------------| | | | sb |---------------------*/for(r =0; r {/*temp = {Sbox[s0],Sbox[s5],Sbox[sa],Sbox[sf]};*/temp[0] = Sbox[*((unsigned char*)State)];temp[1] = Sbox[*((unsigned char*)(State+1)+1)];temp[2] = Sbox[*((unsigned char*)(State+2)+2)];temp[3] = Sbox[*((unsigned char*)(State+3)+3)];*((unsigned char*)State) = Log_02[temp[0]] ^ Log_03[temp[1]] ^ temp[2] ^ temp[3];*((unsigned char*)State+1) = Log_02[temp[1]] ^ Log_03[temp[2]] ^ temp[3] ^ temp[0];*((unsigned char*)State+2) = Log_02[temp[2]] ^ Log_03[temp[3]] ^ temp[0] ^ temp[1];*((unsigned char*)State+3) = Log_02[temp[3]] ^ Log_03[temp[0]] ^ temp[1] ^ temp[2];*State ^= word8[r];State++;}State -= Nb;}memcpy(State+Nb,State,12);word8 += Nb;for(r =0; r {*((unsigned char*)State) = Sbox[*(unsigned char*)State];*((unsigned char*)State+1) = Sbox[*((unsigned char*)(State+1)+1)];*((unsigned char*)State+2) = Sbox[*((unsigned char*)(State+2)+2)];*((unsigned char*)State+3) = Sbox[*((unsigned char*)(State+3)+3)];*State ^= word8[r];State++;}}/*解密时进行Nr轮逆运算AES * aes 运行时参数*/void InvCipherLoop(AES *aes){unsigned long *Word = aes->Word,*State = aes->State;int Nb = aes->Nb,Nr = aes->Nr;unsigned char temp[4];int r =0;Word += Nb*Nr;for (r = 0; r < Nb; ++r){State[r] ^= Word[r];}State -= 3;for (int round = Nr-1; round > 0; --round) {/*假设Nb=4;---------------------| | | | |---------------------| | | | || | | | |---------------------| s0 | s1 | s2 | s3 |---------------------| s4 | s5 | s6 | s7 |---------------------| s8 | s9 | sa | sb |---------------------| sc | sd | se | sf |---------------------*/memcpy(State,State+Nb,12); /*Nb=4;---------------------| | | | s7 |---------------------| | | sa | sb |---------------------| | sd | se | sf |---------------------| s0 | s1 | s2 | s3 |---------------------| s4 | s5 | s6 | |---------------------| s8 | s9 | | |---------------------| sc | | | |*/Word -= Nb;State += Nb+2;for(r = Nb-1; r >= 0; r--){/*temp = {iSbox[s0],iSbox[sd],iSbox[sa],iSbox[s7]};*/temp[0] = iSbox[*(byte*)State];temp[1] = iSbox[*((byte*)(State-1)+1)];temp[2] = iSbox[*((byte*)(State-2)+2)];temp[3] = iSbox[*((byte*)(State-3)+3)];*(unsigned long*)temp ^= Word[r];*(unsigned char*)State = Log_0e[temp[0]] ^ Log_0b[temp[1]] ^ Log_0d[temp[2]] ^ Log_09[temp[3]];*((unsigned char*)State+1) = Log_0e[temp[1]] ^ Log_0b[temp[2]] ^ Log_0d[temp[3]] ^ Log_09[temp[0]];*((unsigned char*)State+2) = Log_0e[temp[2]] ^ Log_0b[temp[3]] ^ Log_0d[temp[0]] ^ Log_09[temp[1]];*((unsigned char*)State+3) = Log_0e[temp[3]] ^ Log_0b[temp[0]] ^ Log_0d[temp[1]] ^ Log_09[temp[2]];State --;}State -= 2;}Word -= Nb;memcpy(State,State+Nb,12);State += Nb+2;for(r = Nb-1; r >= 0; r--){*(unsigned char*)State = iSbox[*(unsigned char*)State];*((unsigned char*)State+1) = iSbox[*((unsigned char*)(State-1)+1)];*((unsigned char*)State+2) = iSbox[*((unsigned char*)(State-2)+2)];*((unsigned char*)State+3) = iSbox[*((unsigned char*)(State-3)+3)];*State ^= Word[r];State --;}}/**--------------------------------------------*|k0|k1|k2|k3|k4|k5|k6|k7|k8|k9|.......|Nk*4|*--------------------------------------------*Nr轮密钥库*每个密钥列长度为Nb*---------------------*| k0 | k1 | k2 | k3 |*---------------------*| k4 | k5 | k6 | k7 |*---------------------*| k8 | k9 | ka | kb |*---------------------*| kc | kd | ke | kf |*---------------------*/unsigned long* keyExpansion(byte* key, int Nb, int Nr, int Nk) {unsigned long *w =new unsigned long[Nb * (Nr+1)]; // 4 columns of bytes corresponds to a wordmemcpy(w,key,Nk<<2);unsigned long temp;for (int c = Nk; c < Nb * (Nr+1); ++c){//把上一轮的最后一行放入temptemp = w[c-1];//判断是不是每一轮密钥的第一行if (c % Nk == 0){//左旋8位temp = (temp<<8)|(temp>>24);//查Sbox表SubWord((byte*)&temp);temp ^= Rcon[c/Nk];}else if ( Nk > 6 && (c % Nk == 4) ){SubWord((byte*)&temp);}//w[c-Nk] 为上一轮密钥的第一行w[c] = w[c-Nk] ^ temp;}return w;}unsigned char* SubWord(unsigned char* word) {word[0] = Sbox[ word[0] ];word[1] = Sbox[ word[1] ];word[2] = Sbox[ word[2] ];word[3] = Sbox[ word[3] ];return word;}/*释放AES结构和State和密钥库word*/void freeAES(AES *aes){// for(int i=0;iNb;i++)// {// printf("%d\n",i);// free(aes->State[i]);// free(aes->Word[i]);// }// printf("sdffd");}。

JAVA实现AES加密算法代码

JAVA实现AES加密算法代码

JAVA实现AES加密算法代码以下是一个简单的JAVA实现AES加密算法的代码:```javaimport javax.crypto.Cipher;import javax.crypto.spec.SecretKeySpec;import java.security.Key;public class AESprivate static final String ALGORITHM = "AES";private static final String TRANSFORMATION ="AES/ECB/PKCS5Padding";public static byte[] encrypt(String key, byte[] data) throws ExceptionKey secretKey = new SecretKeySpec(key.getBytes(, ALGORITHM);Cipher cipher = Cipher.getInstance(TRANSFORMATION);cipher.init(Cipher.ENCRYPT_MODE, secretKey);return cipher.doFinal(data);}public static byte[] decrypt(String key, byte[] encryptedData) throws ExceptionKey secretKey = new SecretKeySpec(key.getBytes(, ALGORITHM);Cipher cipher = Cipher.getInstance(TRANSFORMATION);cipher.init(Cipher.DECRYPT_MODE, secretKey);return cipher.doFinal(encryptedData);}public static void main(String[] args)tryString key = "ThisIsASecretKey";String data = "Hello World!";byte[] encryptedData = encrypt(key, data.getBytes();System.out.println("Encrypted Data: " + newString(encryptedData));byte[] decryptedData = decrypt(key, encryptedData);System.out.println("Decrypted Data: " + newString(decryptedData));} catch (Exception e)e.printStackTrace(;}}```这个代码包含了两个方法,一个是用于加密数据的`encrypt`方法,另一个是用于解密数据的`decrypt`方法。

易语言aes加密写法

易语言aes加密写法

易语言aes加密写法在易语言中,可以使用AES算法进行加密和解密。

以下是一个简单的示例代码,演示如何使用易语言进行AES加密和解密:复制代码'定义密钥key$ = "abcdefghijklmnopqrstuvwxyz123456"'加密明文$ = "Hello, World!"加密后的数据$ = AES_Encrypt(明文$, key$)'解密解密后的数据$ = AES_Decrypt(加密后的数据$, key$)'输出解密结果输出(解密后的数据$)'AES加密函数子程序 AES_Encrypt, 文本型参数明文$, 文本型参数密钥$局部变量加密数据$, 文本型加密数据$ = AES._EcbEncrypt(明文$, 密钥$)返回加密数据$子程序结束'AES解密函数子程序 AES_Decrypt, 文本型参数密文$, 文本型参数密钥$局部变量解密数据$, 文本型解密数据$ = AES._EcbDecrypt(密文$, 密钥$)返回解密数据$子程序结束在上面的代码中,首先定义了一个密钥key$,然后使用AES_Encrypt函数对明文进行加密,并将加密后的数据存储在加密后的数据$变量中。

接着,使用AES_Decrypt函数对加密后的数据进行解密,并将解密后的数据存储在解密后的数据$变量中。

最后,使用输出函数将解密后的结果输出到控制台。

需要注意的是,这只是一个简单的示例代码,实际使用中需要根据具体需求进行适当的修改和调整。

另外,易语言本身并没有直接提供AES算法的实现,需要使用第三方库或者自行实现。

AESECB加密算法C语言代码实现

AESECB加密算法C语言代码实现

AESECB加密算法C语言代码实现要实现AESECB加密算法的C语言代码,需要先了解AES算法的基本原理和步骤。

以下是一个使用C语言实现AESECB加密算法的示例代码:```c#include <stdio.h>#include <stdlib.h>#include <string.h>#include <openssl/aes.h>//定义密钥长度#define KEY_LENGTH 16//ECBAES加密函数void AESEncrypt_ECB(const unsigned char* plainText, int plainTextLength, unsigned char* cipherText,const unsigned char* key)//创建AES密钥结构体AES_KEY aesKey;//设置加密密码AES_set_encrypt_key(key, KEY_LENGTH * 8, &aesKey);//加密数据AES_ecb_encrypt(plainText, cipherText, &aesKey, AES_ENCRYPT);//ECBAES解密函数void AESDecrypt_ECB(const unsigned char* cipherText, int cipherTextLength, unsigned char* plainText,const unsigned char* key)//创建AES密钥结构体AES_KEY aesKey;//设置解密密码AES_set_decrypt_key(key, KEY_LENGTH * 8, &aesKey);//解密数据AES_ecb_encrypt(cipherText, plainText, &aesKey, AES_DECRYPT);int mai//指定原始明文和密钥unsigned char plainText[] = "Hello, World!";unsigned char key[] = "secretkey";//计算明文长度int plainTextLength = strlen(plainText);//计算加密后的数据长度int cipherTextLength = ((plainTextLength / KEY_LENGTH) + 1) * KEY_LENGTH;//分配加密后数据的内存unsigned char* cipherText = (unsignedchar*)malloc(cipherTextLength);//加密数据AESEncrypt_ECB(plainText, plainTextLength, cipherText, key);//打印加密后的结果printf("Cipher text: ");for (int i = 0; i < cipherTextLength; i++)printf("%02x ", cipherText[i]);}printf("\n");//分配解密后数据的内存unsigned char* decryptedText = (unsignedchar*)malloc(cipherTextLength);//解密数据AESDecrypt_ECB(cipherText, cipherTextLength, decryptedText, key);//打印解密后的结果printf("Decrypted text: %s\n", decryptedText);//释放已分配的内存free(cipherText);free(decryptedText);return 0;```上述代码使用了OpenSSL库提供的AES函数来实现ECB模式的AES加密和解密操作。

Python实现AES加密,解密的两种方法

Python实现AES加密,解密的两种方法

Python实现AES加密,解密的两种⽅法第⼀种import base64from Crypto.Cipher import AES# 密钥(key), 密斯偏移量(iv) CBC模式加密def AES_Encrypt(key, data):vi = '0102030405060708'pad = lambda s: s + (16 - len(s) % 16) * chr(16 - len(s) % 16)data = pad(data)# 字符串补位cipher = AES.new(key.encode('utf8'), AES.MODE_CBC, vi.encode('utf8'))encryptedbytes = cipher.encrypt(data.encode('utf8'))# 加密后得到的是bytes类型的数据encodestrs = base64.b64encode(encryptedbytes)# 使⽤Base64进⾏编码,返回byte字符串enctext = encodestrs.decode('utf8')# 对byte字符串按utf-8进⾏解码return enctextdef AES_Decrypt(key, data):vi = '0102030405060708'data = data.encode('utf8')encodebytes = base64.decodebytes(data)# 将加密数据转换位bytes类型数据cipher = AES.new(key.encode('utf8'), AES.MODE_CBC, vi.encode('utf8'))text_decrypted = cipher.decrypt(encodebytes)unpad = lambda s: s[0:-s[-1]]text_decrypted = unpad(text_decrypted)# 去补位text_decrypted = text_decrypted.decode('utf8')return text_decryptedkey = '0CoJUm6Qyw8W8jud' #⾃⼰密钥data = 'sdadsdsdsfd' #需要加密的内容AES_Encrypt(key, data)enctext = AES_Encrypt(key, data)print(enctext)text_decrypted = AES_Decrypt(key, enctext)print(text_decrypted)第⼆种#!/usr/bin/env python#encoding=‘utf-8'from Crypto.Cipher import AESfrom binascii import b2a_hex, a2b_hexfrom Crypto import Randomclass PrpCrypt(object):def __init__(self, key):self.key = key.encode('utf-8')self.mode = AES.MODE_CBCself.iv = Random.new().read(AES.block_size)# 加密函数,如果text不⾜16位就⽤空格补⾜为16位,# 如果⼤于16当时不是16的倍数,那就补⾜为16的倍数。

AES算法C源代码

AES算法C源代码

#include<string.h>#include<stdio.h>#include<math.h>#include<conio.h>#include<stdlib.h>#define Nb 4 //分组大小为4int Nr=0; //轮数定义为0,实际值在程序中获取int Nk=0;//密钥长度定义为0,实际值在程序中获取int Nc = 128;//Nc为密钥长度,只能为128,192或256// in:存储明文的数组// out:存储密文的数组// state:存储中间状态的数组unsigned char in[16],out[32],state[4][4]; unsigned char RoundKey[240];//存储轮密钥的数组unsigned char Key[32];//存储输入的密钥int getSBoxInvert(int num){//逆S盒子int rsbox[256] ={ 0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7,0xfb, 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb, 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e, 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25, 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92, 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84, 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06, 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73, 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e, 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b, 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4, 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f, 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef, 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61, 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6,0x7d };return rsbox[num];}int getSBoxValue(int num){//S盒子int sbox[256] = {//0 1 2 3 4 5 6 7 8 9 A B C D E F0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f,0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab,0x76,0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47,0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72,0xc0,0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7,0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31,0x15,0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05,0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2,0x75,0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84,0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8,0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2,0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb,0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a,0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e,0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16 };return sbox[num];}// The round constant word array, Rcon[i], contains the values given by// x to th e power (i-1) being powers of x (x is denoted as {02}) in the field GF(2^8)// Note that i starts at 1, not 0).int Rcon[255] = {0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a,0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39,0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a,0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8,0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef,0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc,0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b,0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3,0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94,0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20,0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35,0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f,0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04,0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63,0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d,0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd,0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb };//密钥扩展,生成Nb(Nr+1)的轮密钥,用于每轮的解密密钥void KeyExpansion(){int i,j;unsigned char temp[4],k;//第一个密钥为密钥本身for(i=0;i<Nk;i++){RoundKey[i*4]=Key[i*4];RoundKey[i*4+1]=Key[i*4+1];RoundKey[i*4+2]=Key[i*4+2];RoundKey[i*4+3]=Key[i*4+3];}// 其它密钥由第一个密钥进行扩展得到while (i < (Nb * (Nr+1))){for(j=0;j<4;j++){temp[j]=RoundKey[(i-1) * 4 + j];}if (i % Nk == 0){// 将四个字节进行左移一位,即[a0,a1,a2,a3]变为[a1,a2,a3,a0]{k = temp[0];temp[0] = temp[1];temp[1] = temp[2];temp[2] = temp[3];temp[3] = k;}// SubWord() is a function that takes a four-byte input word and// applies the S-box to each of the four bytes to produce an output word.{temp[0]=getSBoxValue(temp[0]); temp[1]=getSBoxValue(temp[1]);temp[2]=getSBoxValue(temp[2]); temp[3]=getSBoxValue(temp[3]); }temp[0] = temp[0] ^ Rcon[i/Nk];}else if (Nk > 6 && i % Nk == 4){{temp[0]=getSBoxValue(temp[0]); temp[1]=getSBoxValue(temp[1]); temp[2]=getSBoxValue(temp[2]); temp[3]=getSBoxValue(temp[3]); }}RoundKey[i*4+0] = RoundKey[(i-Nk)*4+0] ^ temp[0];RoundKey[i*4+1] = RoundKey[(i-Nk)*4+1] ^ temp[1];RoundKey[i*4+2] = RoundKey[(i-Nk)*4+2] ^ temp[2];RoundKey[i*4+3] = RoundKey[(i-Nk)*4+3] ^ temp[3];i++;}}// This function adds the round key to state. // The round key is added to the state by an XOR function.void AddRoundKey(int round){int i,j;for(i=0;i<4;i++){for(j=0;j<4;j++){state[j][i] ^= RoundKey[round * Nb * 4 + i * Nb + j];}}}// The SubBytes Function Substitutes the values in the// state matrix with values in an S-box.void InvSubBytes(){int i,j;for(i=0;i<4;i++){for(j=0;j<4;j++){state[i][j] = getSBoxInvert(state[i][j]);}}}// The ShiftRows() function shifts the rows in the state to the left.// Each row is shifted with different offset. // Offset = Row number. So the first row is not shifted.void InvShiftRows(){unsigned char temp;// Rotate first row 1 columns to right temp=state[1][3];state[1][3]=state[1][2];state[1][2]=state[1][1];state[1][1]=state[1][0];state[1][0]=temp;// Rotate second row 2 columns to right temp=state[2][0];state[2][0]=state[2][2];state[2][2]=temp;temp=state[2][1];state[2][1]=state[2][3];state[2][3]=temp;// Rotate third row 3 columns to righttemp=state[3][0];state[3][0]=state[3][1];state[3][1]=state[3][2];state[3][2]=state[3][3];state[3][3]=temp;}// xtime is a macro that finds the product of {02} and the argument to xtime modulo {1b}#define xtime(x) ((x<<1) ^ (((x>>7) & 1) * 0x1b))// Multiplty is a macro used to multiply numbersin the field GF(2^8)#define Multiply(x,y) (((y & 1) * x) ^ ((y>>1 & 1) * xtime(x)) ^ ((y>>2 & 1) * xtime(xtime(x))) ^ ((y>>3 & 1) * xtime(xtime(xtime(x)))) ^ ((y>>4 & 1) * xtime(xtime(xtime(xtime(x))))))// MixColumns function mixes the columns of the state matrix.// The method used to multiply may be difficult to understand for the inexperienced.// Please use the references to gain more information.void InvMixColumns(){int i;unsigned char a,b,c,d;for(i=0;i<4;i++){a = state[0][i];b = state[1][i];c = state[2][i];d = state[3][i];state[0][i] = Multiply(a, 0x0e) ^Multiply(b, 0x0b) ^ Multiply(c, 0x0d) ^ Multiply(d, 0x09);state[1][i] = Multiply(a, 0x09) ^ Multiply(b, 0x0e) ^ Multiply(c, 0x0b) ^ Multiply(d, 0x0d);state[2][i] = Multiply(a, 0x0d) ^ Multiply(b, 0x09) ^ Multiply(c, 0x0e) ^ Multiply(d, 0x0b);state[3][i] = Multiply(a, 0x0b) ^ Multiply(b, 0x0d) ^ Multiply(c, 0x09) ^ Multiply(d, 0x0e);}}// InvCipher is the main function that decrypts the CipherText.void InvCipher(){int i,j,round=0;//Copy the input CipherText to state array. for(i=0;i<4;i++){for(j=0;j<4;j++){state[j][i] = in[i*4 + j];}}// Add the First round key to the state before starting the rounds.AddRoundKey(Nr);// There will be Nr rounds.// The first Nr-1 rounds are identical.// These Nr-1 rounds are executed in the loop below.for(round=Nr-1;round>0;round--){InvShiftRows();InvSubBytes();AddRoundKey(round);InvMixColumns();}// The last round is given below.// The MixColumns function is not here in the last round.InvShiftRows();InvSubBytes();AddRoundKey(0);// The decryption process is over.// Copy the state array to output array.for(i=0;i<4;i++){for(j=0;j<4;j++){out[i*4+j]=state[j][i];}}}// The SubBytes Function Substitutes the values in the// state matrix with values in an S-box.void SubBytes(){int i,j;for(i=0;i<4;i++){for(j=0;j<4;j++){state[i][j] = getSBoxValue(state[i][j]);}}}// The ShiftRows() function shifts the rows in the state to the left.// Each row is shifted with different offset. // Offset = Row number. So the first row is not shifted.void ShiftRows(){unsigned char temp;// Rotate first row 1 columns to left temp=state[1][0];state[1][0]=state[1][1];state[1][1]=state[1][2];state[1][2]=state[1][3];state[1][3]=temp;// Rotate second row 2 columns to left temp=state[2][0];state[2][0]=state[2][2];state[2][2]=temp;temp=state[2][1];state[2][1]=state[2][3];state[2][3]=temp;// Rotate third row 3 columns to lefttemp=state[3][0];state[3][0]=state[3][3];state[3][3]=state[3][2];state[3][2]=state[3][1];state[3][1]=temp;}// xtime is a macro that finds the product of {02} and the argument to xtime modulo {1b}#define xtime(x) ((x<<1) ^ (((x>>7) & 1) * 0x1b))// MixColumns function mixes the columns of the state matrixvoid MixColumns(){int i;unsigned char Tmp,Tm,t;for(i=0;i<4;i++){t=state[0][i];Tmp = state[0][i] ^ state[1][i] ^ state[2][i] ^ state[3][i] ;Tm = state[0][i] ^ state[1][i] ; Tm = xtime(Tm); state[0][i] ^= Tm ^ Tmp ;Tm = state[1][i] ^ state[2][i] ; Tm = xtime(Tm); state[1][i] ^= Tm ^ Tmp ;Tm = state[2][i] ^ state[3][i] ; Tm = xtime(Tm); state[2][i] ^= Tm ^ Tmp ;Tm = state[3][i] ^ t ; Tm = xtime(Tm); state[3][i] ^= Tm ^ Tmp ;}}// Cipher is the main function that encrypts the PlainText.void Cipher(){int i,j,round=0;//Copy the input PlainText to state array. for(i=0;i<4;i++){for(j=0;j<4;j++){state[j][i] = in[i*4 + j];}}// Add the First round key to the state before starting the rounds.AddRoundKey(0);// There will be Nr rounds.// The first Nr-1 rounds are identical.// These Nr-1 rounds are executed in the loop below.for(round=1;round<Nr;round++){SubBytes();ShiftRows();MixColumns();AddRoundKey(round);}// The last round is given below.// The MixColumns function is not here in the last round.SubBytes();ShiftRows();AddRoundKey(Nr);// The encryption process is over.// Copy the state array to output array. for(i=0;i<4;i++){for(j=0;j<4;j++){out[i*4+j]=state[j][i];}}}char *encrypt(char *str, char *key){int i,j,Nl;double len;char *newstr;Nk = Nc / 32;Nr = Nk + 6;len= strlen(str);Nl = (int)ceil(len / 16);//printf("Nl:%d\n", Nl); newstr = (char *)malloc(Nl*32);memset(newstr,0,sizeof(newstr)); for(i=0;i<Nl;i++){for(j=0;j<Nk*4;j++){Key[j]=key[j];in[j]=str[i*16+j];}KeyExpansion();Cipher();memcpy(&newstr[i*32], out, 32); }return newstr;}char *decrypt(char *str, char *key) {int i,j,len,Nl;char *newstr;Nk = Nc / 32;Nr = Nk + 6;len= strlen(str);Nl = (int)ceil(len / 16);newstr = (char *)malloc(16*Nl);memset(newstr,0,sizeof(newstr)); for(i=0;i<Nl;i++){for(j=0;j<Nk*4;j++){Key[j]=key[j];in[j]=str[i*16+j];}KeyExpansion();InvCipher();memcpy(&newstr[i*32], out, 32); }return newstr;}int main(){ char str_1[128];//存明文char str_2[128];//存加密密钥char str_3[128];//存解密密钥char *str;char *str2;printf("请输入明文:\n");scanf("%s",str_1);printf("请输入加密密钥:\n");scanf("%s",str_2);str= encrypt(str_1, str_2);printf("进行加密后:%s\n\n", str);printf("请输入解密密钥:\n");scanf("%s",str_3);str2 = decrypt(str,str_3);printf("进行解密后:%s\n", str2); getch();return 0;}。

AES加密C语言实现代码

AES加密C语言实现代码

#define BPOLY 0x1b //!< Lower 8 bits of (x^8+x^4+x^3+x+1), ie. (x^4+x^3+x+1).#define BLOCKSIZE 16 //!< Block size in number of bytes.#define KEY_COUNT 3#if KEY_COUNT == 1#define KEYBITS 128 //!< Use AES128.#elif KEY_COUNT == 2#define KEYBITS 192 //!< Use AES196.#elif KEY_COUNT == 3#define KEYBITS 256 //!< Use AES256.#else#error Use 1, 2 or 3 keys!#endif#if KEYBITS == 128#define ROUNDS 10 //!< Number of rounds.#define KEYLENGTH 16 //!< Key length in number of bytes.#elif KEYBITS == 192#define ROUNDS 12 //!< Number of rounds.#define KEYLENGTH 24 //!< // Key length in number of bytes.#elif KEYBITS == 256#define ROUNDS 14 //!< Number of rounds.#define KEYLENGTH 32 //!< Key length in number of bytes.#else#error Key must be 128, 192 or 256 bits!#endif#define EXPANDED_KEY_SIZE (BLOCKSIZE * (ROUNDS+1)) //!< 176, 208 or 240 bytes.unsigned char AES_Key_Table[32] ={0xd0, 0x94, 0x3f, 0x8c, 0x29, 0x76, 0x15, 0xd8,0x20, 0x40, 0xe3, 0x27, 0x45, 0xd8, 0x48, 0xad,0xea, 0x8b, 0x2a, 0x73, 0x16, 0xe9, 0xb0, 0x49,0x45, 0xb3, 0x39, 0x28, 0x0a, 0xc3, 0x28, 0x3c,};unsigned char block1[256]; //!< Workspace 1.unsigned char block2[256]; //!< Worksapce 2.unsigned char tempbuf[256];unsigned char *powTbl; //!< Final location of exponentiation lookup table.unsigned char *logTbl; //!< Final location of logarithm lookup table. unsigned char *sBox; //!< Final location of s-box.unsigned char *sBoxInv; //!< Final location of inverse s-box. unsigned char *expandedKey; //!< Final location of expanded key.void CalcPowLog(unsigned char *powTbl, unsigned char *logTbl) {unsigned char i = 0;unsigned char t = 1;do {// Use 0x03 as root for exponentiation and logarithms.powTbl[i] = t;logTbl[t] = i;i++;// Muliply t by 3 in GF(2^8).t ^= (t << 1) ^ (t & 0x80 ? BPOLY : 0);}while( t != 1 ); // Cyclic properties ensure that i < 255.powTbl[255] = powTbl[0]; // 255 = '-0', 254 = -1, etc.}void CalcSBox( unsigned char * sBox ){unsigned char i, rot;unsigned char temp;unsigned char result;// Fill all entries of sBox[].i = 0;do {//Inverse in GF(2^8).if( i > 0 ){temp = powTbl[ 255 - logTbl[i] ];}else{temp = 0;}// Affine transformation in GF(2).result = temp ^ 0x63; // Start with adding a vector in GF(2).for( rot = 0; rot < 4; rot++ ){// Rotate left.temp = (temp<<1) | (temp>>7);// Add rotated byte in GF(2).result ^= temp;}// Put result in table.sBox[i] = result;} while( ++i != 0 );}void CalcSBoxInv( unsigned char * sBox, unsigned char * sBoxInv ) {unsigned char i = 0;unsigned char j = 0;// Iterate through all elements in sBoxInv using i.do {// Search through sBox using j.do {// Check if current j is the inverse of current i.if( sBox[ j ] == i ){// If so, set sBoxInc and indicate search finished.sBoxInv[ i ] = j;j = 255;}} while( ++j != 0 );} while( ++i != 0 );}void CycleLeft( unsigned char * row ){// Cycle 4 bytes in an array left once.unsigned char temp = row[0];row[0] = row[1];row[1] = row[2];row[2] = row[3];row[3] = temp;}void InvMixColumn( unsigned char * column ){unsigned char r0, r1, r2, r3;r0 = column[1] ^ column[2] ^ column[3];r1 = column[0] ^ column[2] ^ column[3];r2 = column[0] ^ column[1] ^ column[3];r3 = column[0] ^ column[1] ^ column[2];column[0] = (column[0] << 1) ^ (column[0] & 0x80 ? BPOLY : 0);column[1] = (column[1] << 1) ^ (column[1] & 0x80 ? BPOLY : 0);column[2] = (column[2] << 1) ^ (column[2] & 0x80 ? BPOLY : 0);column[3] = (column[3] << 1) ^ (column[3] & 0x80 ? BPOLY : 0);r0 ^= column[0] ^ column[1];r1 ^= column[1] ^ column[2];r2 ^= column[2] ^ column[3];r3 ^= column[0] ^ column[3];column[0] = (column[0] << 1) ^ (column[0] & 0x80 ? BPOLY : 0);column[1] = (column[1] << 1) ^ (column[1] & 0x80 ? BPOLY : 0);column[2] = (column[2] << 1) ^ (column[2] & 0x80 ? BPOLY : 0);column[3] = (column[3] << 1) ^ (column[3] & 0x80 ? BPOLY : 0);r0 ^= column[0] ^ column[2];r1 ^= column[1] ^ column[3];r2 ^= column[0] ^ column[2];r3 ^= column[1] ^ column[3];column[0] = (column[0] << 1) ^ (column[0] & 0x80 ? BPOLY : 0);column[1] = (column[1] << 1) ^ (column[1] & 0x80 ? BPOLY : 0);column[2] = (column[2] << 1) ^ (column[2] & 0x80 ? BPOLY : 0);column[3] = (column[3] << 1) ^ (column[3] & 0x80 ? BPOLY : 0);column[0] ^= column[1] ^ column[2] ^ column[3];r0 ^= column[0];r1 ^= column[0];r2 ^= column[0];r3 ^= column[0];column[0] = r0;column[1] = r1;column[2] = r2;column[3] = r3;}void SubBytes( unsigned char * bytes, unsigned char count ){do {*bytes = sBox[ *bytes ]; // Substitute every byte in state.bytes++;} while( --count );}void InvSubBytesAndXOR( unsigned char * bytes, unsigned char * key, unsigned char count ){do {// *bytes = sBoxInv[ *bytes ] ^ *key; // Inverse substitute every byte in state and add key.*bytes = block2[ *bytes ] ^ *key; // Use block2 directly. Increases speed.bytes++;key++;} while( --count );}void InvShiftRows( unsigned char * state ){unsigned char temp;// Note: State is arranged column by column.// Cycle second row right one time.temp = state[ 1 + 3*4 ];state[ 1 + 3*4 ] = state[ 1 + 2*4 ];state[ 1 + 2*4 ] = state[ 1 + 1*4 ];state[ 1 + 1*4 ] = state[ 1 + 0*4 ];state[ 1 + 0*4 ] = temp;// Cycle third row right two times.temp = state[ 2 + 0*4 ];state[ 2 + 0*4 ] = state[ 2 + 2*4 ];state[ 2 + 2*4 ] = temp;temp = state[ 2 + 1*4 ];state[ 2 + 1*4 ] = state[ 2 + 3*4 ];state[ 2 + 3*4 ] = temp;// Cycle fourth row right three times, ie. left once.temp = state[ 3 + 0*4 ];state[ 3 + 0*4 ] = state[ 3 + 1*4 ];state[ 3 + 1*4 ] = state[ 3 + 2*4 ];state[ 3 + 2*4 ] = state[ 3 + 3*4 ];state[ 3 + 3*4 ] = temp;}void InvMixColumns( unsigned char * state ){InvMixColumn( state + 0*4 );InvMixColumn( state + 1*4 );InvMixColumn( state + 2*4 );InvMixColumn( state + 3*4 );}void XORBytes( unsigned char * bytes1, unsigned char * bytes2, unsigned char count ) {do {*bytes1 ^= *bytes2; // Add in GF(2), ie. XOR.bytes1++;bytes2++;} while( --count );}void CopyBytes( unsigned char * to, unsigned char * from, unsigned char count ) {do {*to = *from;to++;from++;} while( --count );}void KeyExpansion( unsigned char * expandedKey ){unsigned char temp[4];unsigned char i;unsigned char Rcon[4] = { 0x01, 0x00, 0x00, 0x00 }; // Round constant.unsigned char * key = AES_Key_Table;// Copy key to start of expanded key.i = KEYLENGTH;do {*expandedKey = *key;expandedKey++;key++;} while( --i );// Prepare last 4 bytes of key in temp.expandedKey -= 4;temp[0] = *(expandedKey++);temp[1] = *(expandedKey++);temp[2] = *(expandedKey++);temp[3] = *(expandedKey++);// Expand key.i = KEYLENGTH;while( i < BLOCKSIZE*(ROUNDS+1) ){// Are we at the start of a multiple of the key size?if( (i % KEYLENGTH) == 0 ){CycleLeft( temp ); // Cycle left once.SubBytes( temp, 4 ); // Substitute each byte.XORBytes( temp, Rcon, 4 ); // Add constant in GF(2).*Rcon = (*Rcon << 1) ^ (*Rcon & 0x80 ? BPOLY : 0);}// Keysize larger than 24 bytes, ie. larger that 192 bits?#if KEYLENGTH > 24// Are we right past a block size?else if( (i % KEYLENGTH) == BLOCKSIZE ) {SubBytes( temp, 4 ); // Substitute each byte.}#endif// Add bytes in GF(2) one KEYLENGTH away.XORBytes( temp, expandedKey - KEYLENGTH, 4 );// Copy result to current 4 bytes.*(expandedKey++) = temp[ 0 ];*(expandedKey++) = temp[ 1 ];*(expandedKey++) = temp[ 2 ];*(expandedKey++) = temp[ 3 ];i += 4; // Next 4 bytes.}}void InvCipher( unsigned char * block, unsigned char * expandedKey ) {unsigned char round = ROUNDS-1;expandedKey += BLOCKSIZE * ROUNDS;XORBytes( block, expandedKey, 16 );expandedKey -= BLOCKSIZE;do {InvShiftRows( block );InvSubBytesAndXOR( block, expandedKey, 16 );expandedKey -= BLOCKSIZE;InvMixColumns( block );} while( --round );InvShiftRows( block );InvSubBytesAndXOR( block, expandedKey, 16 );}void aesDecInit(void){powTbl = block1;logTbl = block2;CalcPowLog( powTbl, logTbl );sBox = tempbuf;CalcSBox( sBox );expandedKey = block1;KeyExpansion( expandedKey );sBoxInv = block2; // Must be block2.CalcSBoxInv( sBox, sBoxInv );}void aesDecrypt( unsigned char * buffer, unsigned char * chainBlock ) {unsigned char temp[ BLOCKSIZE ];CopyBytes( temp, buffer, BLOCKSIZE );InvCipher( buffer, expandedKey );XORBytes( buffer, chainBlock, BLOCKSIZE );CopyBytes( chainBlock, temp, BLOCKSIZE );}unsigned char Multiply( unsigned char num, unsigned char factor ){unsigned char mask = 1;unsigned char result = 0;while( mask != 0 ){// Check bit of factor given by mask.if( mask & factor ){// Add current multiple of num in GF(2).result ^= num;}// Shift mask to indicate next bit.mask <<= 1;// Double num.num = (num << 1) ^ (num & 0x80 ? BPOLY : 0);}return result;}unsigned char DotProduct( unsigned char * vector1, unsigned char * vector2 ) {unsigned char result = 0;result ^= Multiply( *vector1++, *vector2++ );result ^= Multiply( *vector1++, *vector2++ );result ^= Multiply( *vector1++, *vector2++ );result ^= Multiply( *vector1 , *vector2 );return result;}void MixColumn( unsigned char * column ){unsigned char row[8] = {0x02, 0x03, 0x01, 0x01, 0x02, 0x03, 0x01, 0x01};// Prepare first row of matrix twice, to eliminate need for cycling.unsigned char result[4];// Take dot products of each matrix row and the column vector.result[0] = DotProduct( row+0, column );result[1] = DotProduct( row+3, column );result[2] = DotProduct( row+2, column );result[3] = DotProduct( row+1, column );// Copy temporary result to original column.column[0] = result[0];column[1] = result[1];column[2] = result[2];column[3] = result[3];}void MixColumns( unsigned char * state ){MixColumn( state + 0*4 );MixColumn( state + 1*4 );MixColumn( state + 2*4 );MixColumn( state + 3*4 );}void ShiftRows( unsigned char * state ){unsigned char temp;// Note: State is arranged column by column.// Cycle second row left one time.temp = state[ 1 + 0*4 ];state[ 1 + 0*4 ] = state[ 1 + 1*4 ];state[ 1 + 1*4 ] = state[ 1 + 2*4 ];state[ 1 + 2*4 ] = state[ 1 + 3*4 ];state[ 1 + 3*4 ] = temp;// Cycle third row left two times.temp = state[ 2 + 0*4 ];state[ 2 + 0*4 ] = state[ 2 + 2*4 ];state[ 2 + 2*4 ] = temp;temp = state[ 2 + 1*4 ];state[ 2 + 1*4 ] = state[ 2 + 3*4 ];state[ 2 + 3*4 ] = temp;// Cycle fourth row left three times, ie. right once.temp = state[ 3 + 3*4 ];state[ 3 + 3*4 ] = state[ 3 + 2*4 ];state[ 3 + 2*4 ] = state[ 3 + 1*4 ];state[ 3 + 1*4 ] = state[ 3 + 0*4 ];state[ 3 + 0*4 ] = temp;}void Cipher( unsigned char * block, unsigned char * expandedKey ) {unsigned char round = ROUNDS-1;XORBytes( block, expandedKey, 16 );expandedKey += BLOCKSIZE;do {SubBytes( block, 16 );ShiftRows( block );MixColumns( block );XORBytes( block, expandedKey, 16 );expandedKey += BLOCKSIZE;} while( --round );SubBytes( block, 16 );ShiftRows( block );XORBytes( block, expandedKey, 16 );}void aesEncInit(void){powTbl = block1;logTbl = tempbuf;CalcPowLog( powTbl, logTbl );sBox = block2;CalcSBox( sBox );expandedKey = block1;KeyExpansion( expandedKey );}void aesEncrypt( unsigned char * buffer, unsigned char * chainBlock ) {XORBytes( buffer, chainBlock, BLOCKSIZE );Cipher( buffer, expandedKey );CopyBytes( chainBlock, buffer, BLOCKSIZE );}#include <string.h>void AES_Test(void){unsigned char dat[16]="0123456789ABCDEF";unsigned char chainCipherBlock[16];unsigned char i;for(i=0;i<32;i++) AES_Key_Table[i]=i;//做运算之前先要设置好密钥,这里只是设置密钥的DEMO。

Python中如何使用AES算法进行加密和解密

Python中如何使用AES算法进行加密和解密

Python中如何使用AES算法进行加密和解密一、引言随着互联网的快速发展,财务交易、个人资料和敏感数据被传输在网络上的频率越来越高。

因此,保护数据的安全性和私密性成为了一项至关重要的任务。

加密技术是一种重要的手段,可以解决这个问题。

其中最受欢迎和应用广泛的加密算法是AES。

本文主要介绍Python中如何使用AES算法进行加密和解密的方法。

二、AES算法简介AES算法是高级加密标准(Advanced Encryption Standard)的缩写。

它是目前广泛使用的对称加密算法之一,是一种分组密码,加密和解密使用相同的秘钥(Key)进行。

AES算法的加密和解密都是基于密钥和明文的操作。

AES算法对明文进行加密时需要三个参数:明文、密钥和向量(IV),其中向量是用于增加随机性和异质性以增强密码体制的安全性的。

加密后,得到的密文只有通过使用相同的密钥和向量才能被解密。

因此,必须确保密钥和向量的安全性。

AES算法的强度与密钥长度有关,通常使用128、192或256位密钥。

三、Python中使用AES算法加密和解密的方法Python中使用AES算法加密和解密需要使用Crypto库,它是Python中专门提供密码学操作的库。

在使用之前,需要先安装Crypto 库:```pythonpip install pycrypto```在Crypto库中,有很多算法可以使用。

在这里,我们使用AES算法。

首先,需要导入Crypto库中的AES模块,如下所示:```pythonfrom Crypto.Cipher import AES```接下来,定义用于加密和解密的key和iv:```pythonkey = '0123456789abcdef'iv = 'fedcba9876543210'```key和iv都是以字符串形式定义的,长度分别为16个字符(128位)和16个字符(128位)。

aesencrypt函数

aesencrypt函数

aesencrypt函数AES(Advanced Encryption Standard)是一种对称加密算法,广泛用于保护信息的安全。

在编程中,你可以使用编程语言提供的库或模块来实现AES加密。

以下是一个通用的AES加密函数示例,使用Python和Crypto库:首先,确保你已经安装了Crypto库。

你可以使用以下命令安装:pip install pycryptodome然后,你可以使用以下示例代码创建一个AES加密函数:from Crypto.Cipher import AESfrom Crypto.Random import get_random_bytesfrom Crypto.Util.Padding import pad, unpadimport base64def aes_encrypt(data, key):# 生成16字节的随机初始化向量iv = get_random_bytes(16)# 创建AES加密对象cipher = AES.new(key, AES.MODE_CBC, iv)# 使用PKCS7填充对数据进行加密ciphertext = cipher.encrypt(pad(data.encode('utf-8'), AES.block_size))# 将加密后的数据和初始化向量进行Base64编码encrypted_data = base64.b64encode(iv + ciphertext).decode('utf-8')return encrypted_datadef aes_decrypt(encrypted_data, key):# 对Base64编码的数据进行解码encrypted_data = base64.b64decode(encrypted_data)# 提取初始化向量iv = encrypted_data[:16]# 创建AES解密对象cipher = AES.new(key, AES.MODE_CBC, iv)# 解密数据并去除填充decrypted_data = unpad(cipher.decrypt(encrypted_data[16:]),AES.block_size).decode('utf-8')return decrypted_data# 示例用法key = b'ThisIsASecretKey'data_to_encrypt = 'Hello, AES Encryption!'encrypted_data = aes_encrypt(data_to_encrypt, key)print('Encrypted Data:', encrypted_data)decrypted_data = aes_decrypt(encrypted_data, key)print('Decrypted Data:', decrypted_data)请注意,实际应用中,密钥的生成、存储和传递都需要谨慎处理,以确保系统的安全性。

AES加密算法(Delphi源码)

AES加密算法(Delphi源码)

AES加密算法(Delphi源码) AES加密算法源码unit ElAES;interfaceusesClasses, SysUtils;typeEAESError = class(Exception);PInteger = ^Integer;TAESBuffer = array [0..15] of byte;TAESKey128 = array [0..15] of byte;TAESKey192 = array [0..23] of byte;TAESKey256 = array [0..31] of byte; TAESExpandedKey128 = array [0..43] of longword; TAESExpandedKey192 = array [0..53] of longword; TAESExpandedKey256 = array [0..63] of longword; PAESBuffer =^TAESBuffer;PAESKey128 =^TAESKey128;PAESKey192 =^TAESKey192;PAESKey256 =^TAESKey256;PAESExpandedKey128 =^TAESExpandedKey128; PAESExpandedKey192 =^TAESExpandedKey192; PAESExpandedKey256 =^TAESExpandedKey256;// Key expansion routines for encryptionprocedure ExpandAESKeyForEncryption(const Key: TAESKey128;var ExpandedKey: TAESExpandedKey128); overload; procedure ExpandAESKeyForEncryption(const Key: TAESKey192;var ExpandedKey: TAESExpandedKey192); overload; procedure ExpandAESKeyForEncryption(const Key: TAESKey256;var ExpandedKey: TAESExpandedKey256); overload;// Block encryption routinesprocedure EncryptAES(const InBuf: TAESBuffer; const Key: TAESExpandedKey128;var OutBuf: TAESBuffer); overload;procedure EncryptAES(const InBuf: TAESBuffer; const Key: TAESExpandedKey192;var OutBuf: TAESBuffer); overload;procedure EncryptAES(const InBuf: TAESBuffer; const Key: TAESExpandedKey256;var OutBuf: TAESBuffer); overload;// Stream encryption routines (ECB mode)procedure EncryptAESStreamECB(Source: TStream; Count: cardinal;const Key: TAESKey128; Dest: TStream); overload;procedure EncryptAESStreamECB(Source: TStream; Count: cardinal;const ExpandedKey: TAESExpandedKey128; Dest: TStream); overload;procedure EncryptAESStreamECB(Source: TStream; Count: cardinal;const Key: TAESKey192; Dest: TStream); overload;procedure EncryptAESStreamECB(Source: TStream; Count: cardinal;const ExpandedKey: TAESExpandedKey192; Dest: TStream); overload;procedure EncryptAESStreamECB(Source: TStream; Count: cardinal;const Key: TAESKey256; Dest: TStream); overload;procedure EncryptAESStreamECB(Source: TStream; Count: cardinal;const ExpandedKey: TAESExpandedKey256; Dest: TStream); overload;// Stream encryption routines (CBC mode)procedure EncryptAESStreamCBC(Source: TStream; Count: cardinal;const Key: TAESKey128; const InitVector: TAESBuffer; Dest: TStream); overload; procedure EncryptAESStreamCBC(Source: TStream; Count: cardinal;const ExpandedKey: TAESExpandedKey128; const InitVector: TAESBuffer;Dest: TStream); overload;procedure EncryptAESStreamCBC(Source: TStream; Count: cardinal;const Key: TAESKey192; const InitVector: TAESBuffer; Dest: TStream); overload; procedure EncryptAESStreamCBC(Source: TStream; Count: cardinal;const ExpandedKey: TAESExpandedKey192; const InitVector: TAESBuffer;Dest: TStream); overload;procedure EncryptAESStreamCBC(Source: TStream; Count: cardinal;const Key: TAESKey256; const InitVector: TAESBuffer; Dest: TStream); overload; procedure EncryptAESStreamCBC(Source: TStream; Count: cardinal;const ExpandedKey: TAESExpandedKey256; const InitVector: TAESBuffer;Dest: TStream); overload;// Key transformation routines for decryptionprocedure ExpandAESKeyForDecryption(var ExpandedKey: TAESExpandedKey128); overload; procedure ExpandAESKeyForDecryption(const Key: TAESKey128;var ExpandedKey: TAESExpandedKey128); overload;procedure ExpandAESKeyForDecryption(var ExpandedKey: TAESExpandedKey192); overload; procedure ExpandAESKeyForDecryption(const Key: TAESKey192;var ExpandedKey: TAESExpandedKey192); overload;procedure ExpandAESKeyForDecryption(var ExpandedKey: TAESExpandedKey256); overload; procedure ExpandAESKeyForDecryption(const Key: TAESKey256;var ExpandedKey: TAESExpandedKey256); overload;// Block decryption routinesprocedure DecryptAES(const InBuf: TAESBuffer; const Key: TAESExpandedKey128;var OutBuf: TAESBuffer); overload;procedure DecryptAES(const InBuf: TAESBuffer; const Key: TAESExpandedKey192;var OutBuf: TAESBuffer); overload;procedure DecryptAES(const InBuf: TAESBuffer; const Key: TAESExpandedKey256;var OutBuf: TAESBuffer); overload;// Stream decryption routines (ECB mode)procedure DecryptAESStreamECB(Source: TStream; Count: cardinal;const Key: TAESKey128; Dest: TStream); overload;procedure DecryptAESStreamECB(Source: TStream; Count: cardinal;const ExpandedKey: TAESExpandedKey128; Dest: TStream); overload;procedure DecryptAESStreamECB(Source: TStream; Count: cardinal;const Key: TAESKey192; Dest: TStream); overload;procedure DecryptAESStreamECB(Source: TStream; Count: cardinal;const ExpandedKey: TAESExpandedKey192; Dest: TStream); overload;procedure DecryptAESStreamECB(Source: TStream; Count: cardinal;const Key: TAESKey256; Dest: TStream); overload;procedure DecryptAESStreamECB(Source: TStream; Count: cardinal;const ExpandedKey: TAESExpandedKey256; Dest: TStream); overload;// Stream decryption routines (CBC mode)procedure DecryptAESStreamCBC(Source: TStream; Count: cardinal;const Key: TAESKey128; const InitVector: TAESBuffer; Dest: TStream); overload; procedure DecryptAESStreamCBC(Source: TStream; Count: cardinal;const ExpandedKey: TAESExpandedKey128; const InitVector: TAESBuffer;Dest: TStream); overload;procedure DecryptAESStreamCBC(Source: TStream; Count: cardinal;const Key: TAESKey192; const InitVector: TAESBuffer; Dest: TStream); overload; procedure DecryptAESStreamCBC(Source: TStream; Count: cardinal;const ExpandedKey: TAESExpandedKey192; const InitVector: TAESBuffer;Dest: TStream); overload;procedure DecryptAESStreamCBC(Source: TStream; Count: cardinal;const Key: TAESKey256; const InitVector: TAESBuffer; Dest: TStream); overload; procedure DecryptAESStreamCBC(Source: TStream; Count: cardinal;const ExpandedKey: TAESExpandedKey256; const InitVector: TAESBuffer;Dest: TStream); overload;resourcestringSInvalidInBufSize = 'Invalid buffer size for decryption';SReadError = 'Stream read error';SWriteError = 'Stream write error';implementationtypePLongWord = ^LongWord;function Min(A, B: integer): integer;beginif A < B thenResult := AelseResult := B;end;constRcon: array [1..30] of longword = ($00000001, $00000002, $00000004, $00000008, $00000010, $00000020,$00000040, $00000080, $0000001B, $00000036, $0000006C, $000000D8,$000000AB, $0000004D, $0000009A, $0000002F, $0000005E, $000000BC,$00000063, $000000C6, $00000097, $00000035, $0000006A, $000000D4,$000000B3, $0000007D, $000000FA, $000000EF, $000000C5, $00000091 );ForwardTable: array [0..255] of longword = ($A56363C6, $847C7CF8, $997777EE, $8D7B7BF6, $0DF2F2FF, $BD6B6BD6, $B16F6FDE, $54C5C591,$50303060, $03010102, $A96767CE, $7D2B2B56, $19FEFEE7, $62D7D7B5, $E6ABAB4D, $9A7676EC,$45CACA8F, $9D82821F, $40C9C989, $877D7DFA, $15FAFAEF, $EB5959B2, $C947478E, $0BF0F0FB,$ECADAD41, $67D4D4B3, $FDA2A25F, $EAAFAF45, $BF9C9C23, $F7A4A453, $967272E4, $5BC0C09B,$C2B7B775, $1CFDFDE1, $AE93933D, $6A26264C, $5A36366C, $413F3F7E, $02F7F7F5, $4FCCCC83,$5C343468, $F4A5A551, $34E5E5D1, $08F1F1F9, $937171E2, $73D8D8AB, $53313162, $3F15152A,$0C040408, $52C7C795, $65232346, $5EC3C39D, $28181830, $A1969637, $0F05050A, $B59A9A2F,$0907070E, $36121224, $9B80801B, $3DE2E2DF, $26EBEBCD, $6927274E, $CDB2B27F, $9F7575EA,$1B090912, $9E83831D, $742C2C58, $2E1A1A34, $2D1B1B36, $B26E6EDC, $EE5A5AB4, $FBA0A05B,$F65252A4, $4D3B3B76, $61D6D6B7, $CEB3B37D, $7B292952, $3EE3E3DD, $712F2F5E, $97848413,$F55353A6, $68D1D1B9, $00000000, $2CEDEDC1, $60202040, $1FFCFCE3, $C8B1B179, $ED5B5BB6,$BE6A6AD4, $46CBCB8D, $D9BEBE67, $4B393972, $DE4A4A94, $D44C4C98, $E85858B0, $4ACFCF85,$6BD0D0BB, $2AEFEFC5, $E5AAAA4F, $16FBFBED, $C5434386, $D74D4D9A, $55333366, $94858511,$CF45458A, $10F9F9E9, $06020204, $817F7FFE, $F05050A0, $443C3C78, $BA9F9F25, $E3A8A84B,$F35151A2, $FEA3A35D, $C0404080, $8A8F8F05, $AD92923F, $BC9D9D21, $48383870, $04F5F5F1,$DFBCBC63, $C1B6B677, $75DADAAF, $63212142, $30101020, $1AFFFFE5, $0EF3F3FD, $6DD2D2BF,$4CCDCD81, $140C0C18, $35131326, $2FECECC3, $E15F5FBE, $A2979735, $CC444488, $3917172E,$57C4C493, $F2A7A755, $827E7EFC, $473D3D7A, $AC6464C8, $E75D5DBA, $2B191932, $957373E6,$A06060C0, $98818119, $D14F4F9E, $7FDCDCA3, $66222244, $7E2A2A54, $AB90903B, $8388880B,$CA46468C, $29EEEEC7, $D3B8B86B, $3C141428, $79DEDEA7, $E25E5EBC, $1D0B0B16, $76DBDBAD,$3BE0E0DB, $56323264, $4E3A3A74, $1E0A0A14, $DB494992, $0A06060C, $6C242448, $E45C5CB8,$5DC2C29F, $6ED3D3BD, $EFACAC43, $A66262C4, $A8919139, $A4959531, $37E4E4D3, $8B7979F2,$32E7E7D5, $43C8C88B, $5937376E, $B76D6DDA, $8C8D8D01, $64D5D5B1, $D24E4E9C, $E0A9A949,$B46C6CD8, $FA5656AC, $07F4F4F3, $25EAEACF, $AF6565CA, $8E7A7AF4, $E9AEAE47, $18080810,$D5BABA6F, $887878F0, $6F25254A, $722E2E5C, $241C1C38, $F1A6A657, $C7B4B473, $51C6C697,$23E8E8CB, $7CDDDDA1, $9C7474E8, $211F1F3E, $DD4B4B96, $DCBDBD61, $868B8B0D, $858A8A0F,$907070E0, $423E3E7C, $C4B5B571, $AA6666CC, $D8484890, $05030306, $01F6F6F7, $120E0E1C,$A36161C2, $5F35356A, $F95757AE, $D0B9B969, $91868617, $58C1C199, $271D1D3A, $B99E9E27,$38E1E1D9, $13F8F8EB, $B398982B, $33111122, $BB6969D2, $70D9D9A9, $898E8E07, $A7949433,$B69B9B2D, $221E1E3C, $92878715, $20E9E9C9, $49CECE87, $FF5555AA, $78282850, $7ADFDFA5,$8F8C8C03, $F8A1A159, $80898909, $170D0D1A, $DABFBF65, $31E6E6D7, $C6424284, $B86868D0,$C3414182, $B0999929, $772D2D5A, $110F0F1E, $CBB0B07B, $FC5454A8, $D6BBBB6D, $3A16162C);LastForwardTable: array [0..255] of longword = ($00000063, $0000007C, $00000077, $0000007B, $000000F2, $0000006B, $0000006F, $000000C5,$00000030, $00000001, $00000067, $0000002B, $000000FE, $000000D7, $000000AB, $00000076,$000000CA, $00000082, $000000C9, $0000007D, $000000FA, $00000059, $00000047, $000000F0,$000000AD, $000000D4, $000000A2, $000000AF, $0000009C, $000000A4, $00000072, $000000C0,$000000B7, $000000FD, $00000093, $00000026, $00000036, $0000003F, $000000F7, $000000CC,$00000034, $000000A5, $000000E5, $000000F1, $00000071, $000000D8, $00000031, $00000015,$00000004, $000000C7, $00000023, $000000C3, $00000018, $00000096, $00000005, $0000009A,$00000007, $00000012, $00000080, $000000E2, $000000EB, $00000027, $000000B2, $00000075,$00000009, $00000083, $0000002C, $0000001A, $0000001B, $0000006E, $0000005A, $000000A0,$00000052, $0000003B, $000000D6, $000000B3, $00000029, $000000E3, $0000002F, $00000084,$00000053, $000000D1, $00000000, $000000ED, $00000020, $000000FC, $000000B1, $0000005B,$0000006A, $000000CB, $000000BE, $00000039, $0000004A, $0000004C, $00000058, $000000CF,$000000D0, $000000EF, $000000AA, $000000FB, $00000043, $0000004D, $00000033,$00000085,$00000045, $000000F9, $00000002, $0000007F, $00000050, $0000003C, $0000009F, $000000A8,$00000051, $000000A3, $00000040, $0000008F, $00000092, $0000009D, $00000038, $000000F5,$000000BC, $000000B6, $000000DA, $00000021, $00000010, $000000FF, $000000F3, $000000D2,$000000CD, $0000000C, $00000013, $000000EC, $0000005F, $00000097, $00000044, $00000017,$000000C4, $000000A7, $0000007E, $0000003D, $00000064, $0000005D, $00000019, $00000073,$00000060, $00000081, $0000004F, $000000DC, $00000022, $0000002A, $00000090, $00000088,$00000046, $000000EE, $000000B8, $00000014, $000000DE, $0000005E, $0000000B, $000000DB,$000000E0, $00000032, $0000003A, $0000000A, $00000049, $00000006, $00000024, $0000005C,$000000C2, $000000D3, $000000AC, $00000062, $00000091, $00000095, $000000E4, $00000079,$000000E7, $000000C8, $00000037, $0000006D, $0000008D, $000000D5, $0000004E, $000000A9,$0000006C, $00000056, $000000F4, $000000EA, $00000065, $0000007A, $000000AE, $00000008,$000000BA, $00000078, $00000025, $0000002E, $0000001C, $000000A6, $000000B4, $000000C6,$000000E8, $000000DD, $00000074, $0000001F, $0000004B, $000000BD, $0000008B, $0000008A,$00000070, $0000003E, $000000B5, $00000066, $00000048, $00000003, $000000F6, $0000000E,$00000061, $00000035, $00000057, $000000B9, $00000086, $000000C1, $0000001D, $0000009E,$000000E1, $000000F8, $00000098, $00000011, $00000069, $000000D9, $0000008E, $00000094,$0000009B, $0000001E, $00000087, $000000E9, $000000CE, $00000055, $00000028, $000000DF,$0000008C, $000000A1, $00000089, $0000000D, $000000BF, $000000E6, $00000042, $00000068,$00000041, $00000099, $0000002D, $0000000F, $000000B0, $00000054, $000000BB, $00000016);InverseTable: array [0..255] of longword = ($50A7F451, $5365417E, $C3A4171A, $965E273A, $CB6BAB3B, $F1459D1F, $AB58FAAC, $9303E34B,$55FA3020, $F66D76AD, $9176CC88, $254C02F5, $FCD7E54F, $D7CB2AC5, $80443526, $8FA362B5,$495AB1DE, $671BBA25, $980EEA45, $E1C0FE5D, $02752FC3, $12F04C81, $A397468D, $C6F9D36B,$E75F8F03, $959C9215, $EB7A6DBF, $DA595295, $2D83BED4, $D3217458, $2969E049, $44C8C98E,$6A89C275, $78798EF4, $6B3E5899, $DD71B927, $B64FE1BE, $17AD88F0, $66AC20C9, $B43ACE7D,$184ADF63, $82311AE5, $60335197, $457F5362, $E07764B1, $84AE6BBB, $1CA081FE, $942B08F9,$58684870, $19FD458F, $876CDE94, $B7F87B52, $23D373AB, $E2024B72, $578F1FE3, $2AAB5566,$0728EBB2, $03C2B52F, $9A7BC586, $A50837D3, $F2872830, $B2A5BF23, $BA6A0302, $5C8216ED,$2B1CCF8A, $92B479A7, $F0F207F3, $A1E2694E, $CDF4DA65, $D5BE0506, $1F6234D1, $8AFEA6C4,$9D532E34, $A055F3A2, $32E18A05, $75EBF6A4, $39EC830B, $AAEF6040, $069F715E, $51106EBD,$F98A213E, $3D06DD96, $AE053EDD, $46BDE64D, $B58D5491, $055DC471, $6FD40604, $FF155060,$24FB9819, $97E9BDD6, $CC434089, $779ED967, $BD42E8B0, $888B8907, $385B19E7, $DBEEC879,$470A7CA1, $E90F427C, $C91E84F8, $00000000, $83868009, $48ED2B32, $AC70111E, $4E725A6C,$FBFF0EFD, $5638850F, $1ED5AE3D, $27392D36, $64D90F0A, $21A65C68, $D1545B9B, $3A2E3624,$B1670A0C, $0FE75793, $D296EEB4, $9E919B1B, $4FC5C080, $A220DC61, $694B775A, $161A121C,$0ABA93E2, $E52AA0C0, $43E0223C, $1D171B12, $0B0D090E, $ADC78BF2, $B9A8B62D, $C8A91E14,$8519F157, $4C0775AF, $BBDD99EE, $FD607FA3, $9F2601F7, $BCF5725C, $C53B6644, $347EFB5B,$7629438B, $DCC623CB, $68FCEDB6, $63F1E4B8, $CADC31D7, $10856342, $40229713, $2011C684,$7D244A85, $F83DBBD2, $1132F9AE, $6DA129C7, $4B2F9E1D, $F330B2DC, $EC52860D, $D0E3C177,$6C16B32B, $99B970A9, $FA489411, $2264E947, $C48CFCA8, $1A3FF0A0, $D82C7D56, $EF903322,$C74E4987, $C1D138D9, $FEA2CA8C, $360BD498, $CF81F5A6, $28DE7AA5, $268EB7DA, $A4BFAD3F,$E49D3A2C, $0D927850, $9BCC5F6A, $62467E54, $C2138DF6, $E8B8D890, $5EF7392E, $F5AFC382,$BE805D9F, $7C93D069, $A92DD56F, $B31225CF, $3B99ACC8, $A77D1810, $6E639CE8, $7BBB3BDB,$097826CD, $F418596E, $01B79AEC, $A89A4F83, $656E95E6, $7EE6FFAA, $08CFBC21, $E6E815EF,$D99BE7BA, $CE366F4A, $D4099FEA, $D67CB029, $AFB2A431, $31233F2A, $3094A5C6, $C066A235,$37BC4E74, $A6CA82FC, $B0D090E0, $15D8A733, $4A9804F1, $F7DAEC41, $0E50CD7F, $2FF69117,$8DD64D76, $4DB0EF43, $544DAACC, $DF0496E4, $E3B5D19E, $1B886A4C, $B81F2CC1, $7F516546,$04EA5E9D, $5D358C01, $737487FA, $2E410BFB, $5A1D67B3, $52D2DB92, $335610E9, $1347D66D,$8C61D79A, $7A0CA137, $8E14F859, $893C13EB, $EE27A9CE, $35C961B7, $EDE51CE1, $3CB1477A,$59DFD29C, $3F73F255, $79CE1418, $BF37C773, $EACDF753, $5BAAFD5F, $146F3DDF, $86DB4478,$81F3AFCA, $3EC468B9, $2C342438, $5F40A3C2, $72C31D16, $0C25E2BC, $8B493C28, $41950DFF,$7101A839, $DEB30C08, $9CE4B4D8, $90C15664, $6184CB7B, $70B632D5, $745C6C48, $4257B8D0);LastInverseTable: array [0..255] of longword = ($00000052, $00000009, $0000006A, $000000D5, $00000030, $00000036, $000000A5, $00000038,$000000BF, $00000040, $000000A3, $0000009E, $00000081, $000000F3, $000000D7, $000000FB,$0000007C, $000000E3, $00000039, $00000082, $0000009B, $0000002F, $000000FF, $00000087,$00000034, $0000008E, $00000043, $00000044, $000000C4, $000000DE, $000000E9, $000000CB,$00000054, $0000007B, $00000094, $00000032, $000000A6, $000000C2, $00000023, $0000003D,$000000EE, $0000004C, $00000095, $0000000B, $00000042, $000000FA, $000000C3, $0000004E,$00000008, $0000002E, $000000A1, $00000066, $00000028, $000000D9, $00000024, $000000B2,$00000076, $0000005B, $000000A2, $00000049, $0000006D, $0000008B, $000000D1, $00000025,$00000072, $000000F8, $000000F6, $00000064, $00000086, $00000068, $00000098, $00000016,$000000D4, $000000A4, $0000005C, $000000CC, $0000005D, $00000065, $000000B6, $00000092,$0000006C, $00000070, $00000048, $00000050, $000000FD, $000000ED, $000000B9, $000000DA,$0000005E, $00000015, $00000046, $00000057, $000000A7, $0000008D, $0000009D,$00000084,$00000090, $000000D8, $000000AB, $00000000, $0000008C, $000000BC, $000000D3, $0000000A,$000000F7, $000000E4, $00000058, $00000005, $000000B8, $000000B3, $00000045, $00000006,$000000D0, $0000002C, $0000001E, $0000008F, $000000CA, $0000003F, $0000000F, $00000002,$000000C1, $000000AF, $000000BD, $00000003, $00000001, $00000013, $0000008A, $0000006B,$0000003A, $00000091, $00000011, $00000041, $0000004F, $00000067, $000000DC, $000000EA,$00000097, $000000F2, $000000CF, $000000CE, $000000F0, $000000B4, $000000E6, $00000073,$00000096, $000000AC, $00000074, $00000022, $000000E7, $000000AD, $00000035, $00000085,$000000E2, $000000F9, $00000037, $000000E8, $0000001C, $00000075, $000000DF, $0000006E,$00000047, $000000F1, $0000001A, $00000071, $0000001D, $00000029, $000000C5, $00000089,$0000006F, $000000B7, $00000062, $0000000E, $000000AA, $00000018, $000000BE, $0000001B,$000000FC, $00000056, $0000003E, $0000004B, $000000C6, $000000D2, $00000079, $00000020,$0000009A, $000000DB, $000000C0, $000000FE, $00000078, $000000CD, $0000005A, $000000F4,$0000001F, $000000DD, $000000A8, $00000033, $00000088, $00000007, $000000C7, $00000031,$000000B1, $00000012, $00000010, $00000059, $00000027, $00000080, $000000EC, $0000005F,$00000060, $00000051, $0000007F, $000000A9, $00000019, $000000B5, $0000004A, $0000000D,$0000002D, $000000E5, $0000007A, $0000009F, $00000093, $000000C9, $0000009C, $000000EF,$000000A0, $000000E0, $0000003B, $0000004D, $000000AE, $0000002A, $000000F5, $000000B0,$000000C8, $000000EB, $000000BB, $0000003C, $00000083, $00000053, $00000099, $00000061,$00000017, $0000002B, $00000004, $0000007E, $000000BA, $00000077, $000000D6, $00000026,$000000E1, $00000069, $00000014, $00000063, $00000055, $00000021, $0000000C, $0000007D);procedure ExpandAESKeyForEncryption(const Key: TAESKey128; var ExpandedKey:TAESExpandedKey128);varI, J: integer;T: longword;W0, W1, W2, W3: longword;beginExpandedKey[0] := PLongWord(@Key[0])^;ExpandedKey[1] := PLongWord(@Key[4])^;ExpandedKey[2] := PLongWord(@Key[8])^;ExpandedKey[3] := PLongWord(@Key[12])^;I := 0; J := 1;repeatT := (ExpandedKey[I + 3] shl 24) or (ExpandedKey[I + 3] shr 8);W0 := LastForwardTable[Byte(T)]; W1 := LastForwardTable[Byte(T shr 8)];W2 := LastForwardTable[Byte(T shr 16)]; W3 :=LastForwardTable[Byte(T shr 24)];ExpandedKey[I + 4] := ExpandedKey[I] xor(W0 xor ((W1 shl 8) or (W1 shr 24)) xor((W2 shl 16) or (W2 shr 16)) xor ((W3 shl 24) or (W3 shr 8))) xor Rcon[J];Inc(J);ExpandedKey[I + 5] := ExpandedKey[I + 1] xor ExpandedKey[I + 4];ExpandedKey[I + 6] := ExpandedKey[I + 2] xor ExpandedKey[I + 5];ExpandedKey[I + 7] := ExpandedKey[I + 3] xor ExpandedKey[I + 6];Inc(I, 4);until I >= 40;end;procedure ExpandAESKeyForEncryption(const Key: TAESKey192; var ExpandedKey: TAESExpandedKey192); overload;varI, J: integer;T: longword;W0, W1, W2, W3: longword;beginExpandedKey[0] := PLongWord(@Key[0])^;ExpandedKey[1] := PLongWord(@Key[4])^;ExpandedKey[2] := PLongWord(@Key[8])^;ExpandedKey[3] := PLongWord(@Key[12])^;ExpandedKey[4] := PLongWord(@Key[16])^;ExpandedKey[5] := PLongWord(@Key[20])^;I := 0; J := 1;repeatT := (ExpandedKey[I + 5] shl 24) or (ExpandedKey[I + 5] shr 8);W0 := LastForwardTable[Byte(T)]; W1 := LastForwardTable[Byte(T shr 8)];W2 := LastForwardTable[Byte(T shr 16)]; W3 :=LastForwardTable[Byte(T shr 24)];ExpandedKey[I + 6] := ExpandedKey[I] xor(W0 xor ((W1 shl 8) or (W1 shr 24)) xor((W2 shl 16) or (W2 shr 16)) xor ((W3 shl 24) or (W3 shr 8))) xor Rcon[J];Inc(J);ExpandedKey[I + 7] := ExpandedKey[I + 1] xor ExpandedKey[I + 6];ExpandedKey[I + 8] := ExpandedKey[I + 2] xor ExpandedKey[I + 7];ExpandedKey[I + 9] := ExpandedKey[I + 3] xor ExpandedKey[I + 8];ExpandedKey[I + 10] := ExpandedKey[I + 4] xor ExpandedKey[I + 9];ExpandedKey[I + 11] := ExpandedKey[I + 5] xor ExpandedKey[I + 10];Inc(I, 6);until I >= 46;end;procedure ExpandAESKeyForEncryption(const Key: TAESKey256; var ExpandedKey: TAESExpandedKey256); overload;varI, J: integer;T: longword;W0, W1, W2, W3: longword;beginExpandedKey[0] := PLongWord(@Key[0])^;ExpandedKey[1] := PLongWord(@Key[4])^;ExpandedKey[2] := PLongWord(@Key[8])^;ExpandedKey[3] := PLongWord(@Key[12])^;ExpandedKey[4] := PLongWord(@Key[16])^;ExpandedKey[5] := PLongWord(@Key[20])^;ExpandedKey[6] := PLongWord(@Key[24])^;ExpandedKey[7] := PLongWord(@Key[28])^;I := 0; J := 1;repeatT := (ExpandedKey[I + 7] shl 24) or (ExpandedKey[I + 7] shr 8);W0 := LastForwardTable[Byte(T)]; W1 := LastForwardTable[Byte(T shr 8)];W2 := LastForwardTable[Byte(T shr 16)]; W3 :=LastForwardTable[Byte(T shr 24)];ExpandedKey[I + 8] := ExpandedKey[I] xor(W0 xor ((W1 shl 8) or (W1 shr 24)) xor((W2 shl 16) or (W2 shr 16)) xor ((W3 shl 24) or (W3 shr 8))) xor Rcon[J];Inc(J);ExpandedKey[I + 9] := ExpandedKey[I + 1] xor ExpandedKey[I + 8];ExpandedKey[I + 10] := ExpandedKey[I + 2] xor ExpandedKey[I + 9];ExpandedKey[I + 11] := ExpandedKey[I + 3] xor ExpandedKey[I + 10];W0 := LastForwardTable[Byte(ExpandedKey[I + 11])];W1 := LastForwardTable[Byte(ExpandedKey[I + 11] shr 8)];W2 := LastForwardTable[Byte(ExpandedKey[I + 11] shr 16)];W3 := LastForwardTable[Byte(ExpandedKey[I + 11] shr 24)];ExpandedKey[I + 12] := ExpandedKey[I + 4] xor(W0 xor ((W1 shl 8) or (W1 shr 24)) xor((W2 shl 16) or (W2 shr 16)) xor ((W3 shl 24) or (W3 shr 8)));ExpandedKey[I + 13] := ExpandedKey[I + 5] xor ExpandedKey[I + 12];ExpandedKey[I + 14] := ExpandedKey[I + 6] xor ExpandedKey[I + 13];ExpandedKey[I + 15] := ExpandedKey[I + 7] xor ExpandedKey[I + 14];Inc(I, 8);until I >= 52;end;procedure EncryptAES(const InBuf: TAESBuffer; const Key: TAESExpandedKey128;var OutBuf: TAESBuffer);varT0, T1: array [0..3] of longword;W0, W1, W2, W3: longword;begin// initializingT0[0] := PLongWord(@InBuf[0])^ xor Key[0];T0[1] := PLongWord(@InBuf[4])^ xor Key[1];T0[2] := PLongWord(@InBuf[8])^ xor Key[2];T0[3] := PLongWord(@InBuf[12])^ xor Key[3];// performing transformation 9 times// round 1W0 := ForwardTable[Byte(T0[0])]; W1 := ForwardTable[Byte(T0[1] shr 8)];W2 := ForwardTable[Byte(T0[2] shr 16)]; W3 := ForwardTable[Byte(T0[3] shr 24)];T1[0] := (W0 xor ((W1 shl 8) or (W1 shr 24)) xor ((W2 shl 16) or (W2 shr 16))xor ((W3 shl 24) or (W3 shr 8))) xor Key[4];W0 := ForwardTable[Byte(T0[1])]; W1 := ForwardTable[Byte(T0[2] shr 8)];W2 := ForwardTable[Byte(T0[3] shr 16)]; W3 := ForwardTable[Byte(T0[0] shr 24)];T1[1] := (W0 xor ((W1 shl 8) or (W1 shr 24)) xor ((W2 shl 16) or (W2 shr 16))xor ((W3 shl 24) or (W3 shr 8))) xor Key[5];W0 := ForwardTable[Byte(T0[2])]; W1 := ForwardTable[Byte(T0[3] shr 8)];W2 := ForwardTable[Byte(T0[0] shr 16)]; W3 := ForwardTable[Byte(T0[1] shr 24)];T1[2] := (W0 xor ((W1 shl 8) or (W1 shr 24)) xor ((W2 shl 16) or (W2 shr 16))xor ((W3 shl 24) or (W3 shr 8))) xor Key[6];W0 := ForwardTable[Byte(T0[3])]; W1 := ForwardTable[Byte(T0[0] shr 8)];W2 := ForwardTable[Byte(T0[1] shr 16)]; W3 := ForwardTable[Byte(T0[2] shr 24)];T1[3] := (W0 xor ((W1 shl 8) or (W1 shr 24)) xor ((W2 shl 16) or (W2 shr 16))xor ((W3 shl 24) or (W3 shr 8))) xor Key[7];// round 2W0 := ForwardTable[Byte(T1[0])]; W1 := ForwardTable[Byte(T1[1] shr 8)];W2 := ForwardTable[Byte(T1[2] shr 16)]; W3 := ForwardTable[Byte(T1[3] shr 24)];T0[0] := (W0 xor ((W1 shl 8) or (W1 shr 24)) xor ((W2 shl 16) or (W2 shr 16))xor ((W3 shl 24) or (W3 shr 8))) xor Key[8];W0 := ForwardTable[Byte(T1[1])]; W1 := ForwardTable[Byte(T1[2] shr 8)];W2 := ForwardTable[Byte(T1[3] shr 16)]; W3 := ForwardTable[Byte(T1[0] shr 24)];T0[1] := (W0 xor ((W1 shl 8) or (W1 shr 24)) xor ((W2 shl 16) or (W2 shr 16))xor ((W3 shl 24) or (W3 shr 8))) xor Key[9];W0 := ForwardTable[Byte(T1[2])]; W1 := ForwardTable[Byte(T1[3] shr 8)];W2 := ForwardTable[Byte(T1[0] shr 16)]; W3 := ForwardTable[Byte(T1[1] shr 24)];T0[2] := (W0 xor ((W1 shl 8) or (W1 shr 24)) xor ((W2 shl 16) or (W2 shr 16))xor ((W3 shl 24) or (W3 shr 8))) xor Key[10];W0 := ForwardTable[Byte(T1[3])]; W1 := ForwardTable[Byte(T1[0] shr 8)];W2 := ForwardTable[Byte(T1[1] shr 16)]; W3 := ForwardTable[Byte(T1[2] shr 24)];T0[3] := (W0 xor ((W1 shl 8) or (W1 shr 24)) xor ((W2 shl 16) or (W2 shr 16))xor ((W3 shl 24) or (W3 shr 8))) xor Key[11];// round 3W0 := ForwardTable[Byte(T0[0])]; W1 := ForwardTable[Byte(T0[1] shr 8)];W2 := ForwardTable[Byte(T0[2] shr 16)]; W3 := ForwardTable[Byte(T0[3] shr 24)];T1[0] := (W0 xor ((W1 shl 8) or (W1 shr 24)) xor ((W2 shl 16) or (W2 shr 16))xor ((W3 shl 24) or (W3 shr 8))) xor Key[12];W0 := ForwardTable[Byte(T0[1])]; W1 := ForwardTable[Byte(T0[2] shr 8)];W2 := ForwardTable[Byte(T0[3] shr 16)]; W3 := ForwardTable[Byte(T0[0] shr 24)];T1[1] := (W0 xor ((W1 shl 8) or (W1 shr 24)) xor ((W2 shl 16) or (W2 shr 16))xor ((W3 shl 24) or (W3 shr 8))) xor Key[13];W0 := ForwardTable[Byte(T0[2])]; W1 := ForwardTable[Byte(T0[3] shr 8)];W2 := ForwardTable[Byte(T0[0] shr 16)]; W3 := ForwardTable[Byte(T0[1] shr 24)];T1[2] := (W0 xor ((W1 shl 8) or (W1 shr 24)) xor ((W2 shl 16) or (W2 shr 16))xor ((W3 shl 24) or (W3 shr 8))) xor Key[14];W0 := ForwardTable[Byte(T0[3])]; W1 := ForwardTable[Byte(T0[0] shr 8)];W2 := ForwardTable[Byte(T0[1] shr 16)]; W3 := ForwardTable[Byte(T0[2] shr 24)];T1[3] := (W0 xor ((W1 shl 8) or (W1 shr 24)) xor ((W2 shl 16) or (W2 shr 16))xor ((W3 shl 24) or (W3 shr 8))) xor Key[15];// round 4W0 := ForwardTable[Byte(T1[0])]; W1 := ForwardTable[Byte(T1[1] shr 8)];W2 := ForwardTable[Byte(T1[2] shr 16)]; W3 := ForwardTable[Byte(T1[3] shr 24)];T0[0] := (W0 xor ((W1 shl 8) or (W1 shr 24)) xor ((W2 shl 16) or (W2 shr 16))xor ((W3 shl 24) or (W3 shr 8))) xor Key[16];W0 := ForwardTable[Byte(T1[1])]; W1 := ForwardTable[Byte(T1[2] shr 8)];W2 := ForwardTable[Byte(T1[3] shr 16)]; W3 := ForwardTable[Byte(T1[0] shr 24)];T0[1] := (W0 xor ((W1 shl 8) or (W1 shr 24)) xor ((W2 shl 16) or (W2 shr 16))xor ((W3 shl 24) or (W3 shr 8))) xor Key[17];W0 := ForwardTable[Byte(T1[2])]; W1 := ForwardTable[Byte(T1[3] shr 8)];W2 := ForwardTable[Byte(T1[0] shr 16)]; W3 := ForwardTable[Byte(T1[1] shr 24)];T0[2] := (W0 xor ((W1 shl 8) or (W1 shr 24)) xor ((W2 shl 16) or (W2 shr 16))xor ((W3 shl 24) or (W3 shr 8))) xor Key[18];W0 := ForwardTable[Byte(T1[3])]; W1 := ForwardTable[Byte(T1[0] shr 8)];W2 := ForwardTable[Byte(T1[1] shr 16)]; W3 := ForwardTable[Byte(T1[2] shr 24)];T0[3] := (W0 xor ((W1 shl 8) or (W1 shr 24)) xor ((W2 shl 16) or (W2 shr 16))xor ((W3 shl 24) or (W3 shr 8))) xor Key[19];// round 5W0 := ForwardTable[Byte(T0[0])]; W1 := ForwardTable[Byte(T0[1] shr 8)];W2 := ForwardTable[Byte(T0[2] shr 16)]; W3 := ForwardTable[Byte(T0[3] shr 24)];T1[0] := (W0 xor ((W1 shl 8) or (W1 shr 24)) xor ((W2 shl 16) or (W2 shr 16))xor ((W3 shl 24) or (W3 shr 8))) xor Key[20];W0 := ForwardTable[Byte(T0[1])]; W1 := ForwardTable[Byte(T0[2] shr 8)];W2 := ForwardTable[Byte(T0[3] shr 16)]; W3 := ForwardTable[Byte(T0[0] shr 24)];T1[1] := (W0 xor ((W1 shl 8) or (W1 shr 24)) xor ((W2 shl 16) or (W2 shr 16))xor ((W3 shl 24) or (W3 shr 8))) xor Key[21];W0 := ForwardTable[Byte(T0[2])]; W1 := ForwardTable[Byte(T0[3] shr 8)];W2 := ForwardTable[Byte(T0[0] shr 16)]; W3 := ForwardTable[Byte(T0[1] shr 24)];。

AES加密C语言实现代码

AES加密C语言实现代码

AES加密C语言实现代码以下是一个简单的C语言实现AES加密算法的代码:```c#include <stdio.h>#include <stdlib.h>#include <stdint.h>//定义AES加密的轮数#define NR 10//定义AES加密的扩展密钥长度#define Nk 4//定义AES加密的行数和列数#define Nb 4//定义AES加密的状态矩阵typedef uint8_t state_t[4][4];//定义AES加密的S盒变换表static const uint8_t sbox[256] =//S盒变换表};//定义AES加密的轮常量表static const uint8_t Rcon[11] =//轮常量表};//定义AES加密的密钥扩展变换函数void KeyExpansion(const uint8_t* key, uint8_t* expandedKey) uint32_t* ek = (uint32_t*)expandedKey;uint32_t temp;//密钥拷贝到扩展密钥中for (int i = 0; i < Nk; i++)ek[i] = (key[4 * i] << 24) , (key[4 * i + 1] << 16) ,(key[4 * i + 2] << 8) , (key[4 * i + 3]);}//扩展密钥生成for (int i = Nk; i < Nb * (NR + 1); i++)temp = ek[i - 1];if (i % Nk == 0)//对上一个密钥的字节进行循环左移1位temp = (temp >> 8) , ((temp & 0xFF) << 24);//对每个字节进行S盒变换temp = (sbox[temp >> 24] << 24) , (sbox[(temp >> 16) & 0xFF] << 16) , (sbox[(temp >> 8) & 0xFF] << 8) , sbox[temp & 0xFF];// 取轮常量Rcontemp = temp ^ (Rcon[i / Nk - 1] << 24);} else if (Nk > 6 && i % Nk == 4)//对每个字节进行S盒变换temp = (sbox[temp >> 24] << 24) , (sbox[(temp >> 16) & 0xFF] << 16) , (sbox[(temp >> 8) & 0xFF] << 8) , sbox[temp & 0xFF];}//生成下一个密钥ek[i] = ek[i - Nk] ^ temp;}//定义AES加密的字节替换函数void SubBytes(state_t* state)for (int i = 0; i < 4; i++)for (int j = 0; j < 4; j++)(*state)[i][j] = sbox[(*state)[i][j]];}}//定义AES加密的行移位函数void ShiftRows(state_t* state) uint8_t temp;//第2行循环左移1位temp = (*state)[1][0];(*state)[1][0] = (*state)[1][1]; (*state)[1][1] = (*state)[1][2]; (*state)[1][2] = (*state)[1][3]; (*state)[1][3] = temp;//第3行循环左移2位temp = (*state)[2][0];(*state)[2][0] = (*state)[2][2]; (*state)[2][2] = temp;temp = (*state)[2][1];(*state)[2][1] = (*state)[2][3]; (*state)[2][3] = temp;//第4行循环左移3位temp = (*state)[3][0];(*state)[3][0] = (*state)[3][3];(*state)[3][3] = (*state)[3][2];(*state)[3][2] = (*state)[3][1];(*state)[3][1] = temp;//定义AES加密的列混淆函数void MixColumns(state_t* state)uint8_t temp, tmp, tm;for (int i = 0; i < 4; i++)tmp = (*state)[i][0];tm = (*state)[i][0] ^ (*state)[i][1] ^ (*state)[i][2] ^ (*state)[i][3] ;temp = (*state)[i][0] ^ (*state)[i][1];(*state)[i][0] ^= temp ^ tm;temp = (*state)[i][1] ^ (*state)[i][2];(*state)[i][1] ^= temp ^ tm;temp = (*state)[i][2] ^ (*state)[i][3];(*state)[i][2] ^= temp ^ tm;temp = (*state)[i][3] ^ tmp;(*state)[i][3] ^= temp ^ tm;}//定义AES加密的轮密钥加函数void AddRoundKey(state_t* state, const uint8_t* roundKey) for (int i = 0; i < 4; i++)for (int j = 0; j < 4; j++)(*state)[j][i] ^= roundKey[i * 4 + j];}}//定义AES加密函数void AES_Encrypt(const uint8_t* plainText, const uint8_t* key, uint8_t* cipherText)state_t* state = (state_t*)cipherText;uint8_t expandedKey[4 * Nb * (NR + 1)];//密钥扩展KeyExpansion(key, expandedKey);//初始化状态矩阵for (int i = 0; i < 4; i++)for (int j = 0; j < 4; j++)(*state)[j][i] = plainText[i * 4 + j];}}//第1轮密钥加AddRoundKey(state, key);//迭代执行第2至第10轮加密for (int round = 1; round < NR; round++) SubBytes(state);ShiftRows(state);MixColumns(state);AddRoundKey(state, expandedKey + round * 16); }//执行第11轮加密SubBytes(state);ShiftRows(state);AddRoundKey(state, expandedKey + NR * 16);int maiuint8_t plainText[16] =//明文数据};uint8_t key[16] =//密钥数据};uint8_t cipherText[16];AES_Encrypt(plainText, key, cipherText);。

基于C++的AES算法完整源码

基于C++的AES算法完整源码
{
unsigned char state[4][4];
int i,r,c;
for(r=0; r<4; r++)
{
for(c=0; c<4 ;c++)
{
state[r][c] = input[c*4+r];
}
}
AddRoundKey(state,w[0]);
void MixColumns(unsigned char state[][4]);//列混淆
void AddRoundKey(unsigned char state[][4], unsigned char k[][4]);//轮密钥加
void InvSubBytes(unsigned char state[][4]);//逆字节代替
AES::AES(unsigned char* key)
{
unsigned char sBox[] =
{ /* 0 1 2 3 4 5 6 7 8 9 a b c d e f */
0x63,0x7c,0x77,0x7b,0xf2,0x6b,0x6f,0xc5,0x30,0x01,0x67,0x2b,0xfe,0xd7,0xab,0x76, /*0*/
0x51,0xa3,0x40,0x8f,0x92,0x9d,0x38,0xf5,0xbc,0xb6,0xda,0x21,0x10,0xff,0xf3,0xd2, /*7*/
0xcd,0x0c,0x13,0xec,0x5f,0x97,0x44,0x17,0xc4,0xa7,0x7e,0x3d,0x64,0x5d,0x19,0x73, /*8*/
0x60,0x81,0x4f,0xdc,0x22,0x2a,0x90,0x88,0x46,0xee,0xb8,0x14,0xde,0x5e,0x0b,0xdb, /*9*/

AES算法C语言实现源码

AES算法C语言实现源码

AES算法C语言实现源码/*AES-128 bit CBC Encryptionby Jacob Lister - Mar. 2024AES128-CBC Encryption for CNOTE: This is a C implementation with minimal cost checking, designed for embedded systems with tight code space constraintsgcc -Wall -c aes.cDescription:This code is the implementation of the AES128 algorithm,specifically ECB and CBC mode. ECB stands for ElectronicCode Book mode, which is essentially plain AES encryption.CBC (Cipher Block Chaining) is a mode that allows forenhanced security.*/#include <stdio.h>#include <stdlib.h>#include <string.h>typedef unsigned char AES_BYTE;/*constant in AES. Value=4*/#define Nb 4/* The number of 32 bit words in a key. */#define Nk 4/*Key length in bytes [128 bit](Nk * 4), or 16 bytes.*/#define KEYLEN 16/*The number of rounds in AES Cipher.Number of rounds=10, 12, 14.*/#define Nr 14AES_BYTE * AES_Encrypt(AES_BYTE *plainText, AES_BYTE *key); AES_BYTE * AES_Decrypt(AES_BYTE *cipherText, AES_BYTE *key);Function to store the round keysgenerated from the cipher key.*/void AES_KeyExpansion(AES_BYTE key[4*Nk], AES_BYTE roundKey[4*Nb*(Nr+1)]);/*Cipher is the main function that encryptsthe plaintext given the key [128 bit].*/void AES_Cipher(AES_BYTE *in, AES_BYTE *out, AES_BYTE *roundKey);/*The SubBytes Function is usedto substitute each byte of the statewith its corresponding byte in theRijndael S-box.*/void SubBytes(AES_BYTE *state);The ShiftRows function is usedto shift the rows cyclically aroundthe state.*/void ShiftRows(AES_BYTE *state);/*The MixColumns function is usedto mix the columns of the statematrix.*/void MixColumns(AES_BYTE *state);/*The AddRoundKey function is usedto add round key word to thestate matrix to produce the output.*/void AddRoundKey(AES_BYTE *state, AES_BYTE* roundKey); /*The SubBytes Function is usedto substitute each byte of the state with its inverse in the Rijndael S-box. */void InvSubBytes(AES_BYTE *state);/*The InvShiftRows function is usedto shift the rows cyclically aroundthe state in the opposite direction.*/void InvShiftRows(AES_BYTE *state);/*The InvMixColumns function is usedto mix the columns of the statematrix in the opposite direction.*/void InvMixColumns(AES_BYTE *state);/*The AES_Encrypt functionencrypts the plaintext usingthe provided AES_128 encryptionkey.*/AES_BYTE* AES_Encrypt(AES_BYTE *plainText, AES_BYTE *key) //struct to store ciphertextAES_BYTE *cipherText;int stat_len = 4 * Nb;// The KeyExpansion routine must be called// before encryption.AES_BYTE roundKey[4 * Nb * (Nr + 1)];。

aes算法python实现

aes算法python实现

aes算法python实现一、引言AES(Advanced Encryption Standard)是一种对称加密算法,由美国国家标准与技术研究院(NIST)于2001年发布。

AES算法采用分组密码,对明文进行分组加密,并采用不同的密钥进行加密和解密操作。

在安全性和效率方面都有很高的表现,目前已经成为广泛使用的加密算法之一。

本文将介绍如何使用Python语言实现AES算法。

二、环境准备在使用Python实现AES算法之前,需要安装pycryptodome库。

可以通过pip安装该库:```pip install pycryptodome```三、AES算法原理AES算法采用分组密码的方式,将明文分为若干个块,每个块长度为128位。

同时,每个块都需要一个128位的密钥进行加密和解密操作。

在AES算法中,有三种不同长度的密钥可供选择:128位、192位和256位。

其中,128位是最常用的长度。

AES算法包含四个步骤:字节替换、行移位、列混淆和轮秘钥加。

这四个步骤被重复执行多次(轮数),直到达到预定轮数。

1. 字节替换在该步骤中,将明文中每一个字节替换为另一个字节。

替换的规则由固定的S盒提供。

S盒是一个16x16的数组,其中每个元素都是一个8位二进制数。

2. 行移位在该步骤中,将每一行向左移动若干个位置。

第一行不移动,第二行向左移动1个位置,第三行向左移动2个位置,第四行向左移动3个位置。

3. 列混淆在该步骤中,将每一列进行混淆。

具体操作是将每一列看成一个4元素的向量,然后对其进行矩阵乘法运算。

4. 轮秘钥加在该步骤中,将当前块与轮秘钥进行异或运算。

轮秘钥是由密钥扩展算法生成的。

四、AES算法实现下面给出使用Python实现AES算法的代码:```pythonfrom Crypto.Cipher import AESdef aes_encrypt(key, data):cipher = AES.new(key, AES.MODE_ECB)return cipher.encrypt(data)def aes_decrypt(key, data):cipher = AES.new(key, AES.MODE_ECB)return cipher.decrypt(data)```上述代码中,aes_encrypt函数用于加密数据,aes_decrypt函数用于解密数据。

aes算法c语言实现

aes算法c语言实现

aes算法c语言实现AES(Advanced Encryption Standard)是一种广泛应用于数据加密的算法。

以下是一个使用C语言实现的AES加密算法示例,用于对字符串进行加密和解密。

这个实现是基于ECB模式的,这是一种常用的加密模式,因为它简单且易于实现。

注意:这个实现是为了教学目的而提供的,可能不适合用于生产环境。

生产环境中的加密实现通常需要更复杂和安全的方法。

```c #include <stdio.h> #include <string.h> #include <stdint.h> #include <openssl/aes.h>void AES_encrypt(const uint8_t *key, const uint8_t*plaintext, uint8_t *ciphertext) { AES_KEY aesKey; AES_set_encrypt_key(key, 128, &aesKey);AES_encrypt(plaintext, ciphertext, &aesKey); }void AES_decrypt(const uint8_t *key, const uint8_t*ciphertext, uint8_t *plaintext) { AES_KEY aesKey; AES_set_decrypt_key(key, 128, &aesKey);AES_decrypt(ciphertext, plaintext, &aesKey); }int main() { // 定义密钥和明文/密文缓冲区uint8_t key[AES_BLOCK_SIZE]; // AES_BLOCK_SIZE是AES算法的块大小,通常是16字节(128位) uint8_tplaintext[AES_BLOCK_SIZE], ciphertext[AES_BLOCK_SIZE];// 填充密钥和明文/密文缓冲区 // 这里省略了填充代码,因为在实际应用中,你应该使用合适的填充方案来保护数据的完整性。

AES加密解密与代码实现详解

AES加密解密与代码实现详解

AES加密解密与代码实现详解AES(Advanced Encryption Standard)是一种对称加密算法,其安全性和性能都得到了广泛的认可和应用。

在AES中,采用的是分组密码算法,即将明文分组加密,每个明文分组的长度为128比特(16字节),密钥长度可为128比特、192比特或256比特。

1.初始化轮秘钥:根据密钥生成一系列轮秘钥,用于每轮加密操作。

2.轮加密:对明文进行一系列的轮操作,每轮操作包括字节代换、行移位、列混淆和轮秘钥加。

- 字节代换(SubBytes):将每个字节替换为S盒中对应字节的值,S盒是一个由固定变换生成的字节替代表。

- 行移位(ShiftRows):将第1、2、3行循环左移0、1、2个字节。

- 列混淆(MixColumns):通过一系列的线性变换,完成每个列的混淆操作。

- 轮秘钥加(AddRoundKey):将当前轮的秘钥与状态矩阵进行异或操作。

3.最后一轮加密操作:最后一轮操作不包括列混淆操作。

4.密文生成:将最后一轮加密操作的状态矩阵输出为密文。

解密操作与加密操作相反,主要是将轮操作中的逆变换应用到密文上,恢复出明文。

以下是一个AES加密解密算法的示例代码(使用Python语言实现):```pythonfrom Crypto.Cipher import AESfrom Crypto.Util.Padding import pad, unpadfrom Crypto.Random import get_random_bytes#生成一个随机的16字节密钥key = get_random_bytes(16)def encrypt(plain_text):#创建一个AES对象并使用密钥进行初始化cipher = AES.new(key, AES.MODE_ECB)#对明文进行填充padded_plain_text = pad(plain_text, 16)#加密明文cipher_text = cipher.encrypt(padded_plain_text) return cipher_textdef decrypt(cipher_text):#创建一个AES对象并使用密钥进行初始化cipher = AES.new(key, AES.MODE_ECB)#解密密文decrypted_text = cipher.decrypt(cipher_text)#对解密后的明文进行去填充plain_text = unpad(decrypted_text, 16)return plain_text#要加密的明文plain_text = b"Hello World!"#加密明文得到密文cipher_text = encrypt(plain_text)#解密密文得到明文decrypted_text = decrypt(cipher_text)print("明文:", plain_text)print("密文:", cipher_text)print("解密后明文:", decrypted_text)```通过以上代码,可以实现对称加密算法AES的加密和解密操作。

C#之Aes文件的加密和加密

C#之Aes文件的加密和加密

C#之Aes⽂件的加密和加密前⼏天遇到⼀个关于使⽤Aes算法加密解密字符串或者txt⽂件的问题,接下来我将⽤C#来编程aes算法加密和解密,代码如下这是button的核⼼代码:private void Button_Click(object sender, RoutedEventArgs e){string str1 = "明⽂.txt";string str2 = "密⽂.txt";if (p1.Password.Length<5){MessageBox.Show("密码不能低于5位");return;}byte[] key, iv;aes.GenKeyIV(p1.Password, out key, out iv);string ss = "";FileStream fs = new FileStream(str1, FileMode.Open, FileAccess.Read);StreamReader sr = new StreamReader(fs);ss = sr.ReadToEnd();fs.Close();sr.Close();a1.Text = "原始字符串:" + ss;byte[] data1 = aes.EncryptString(str1, str2, key, iv);string encryptedString = Convert.ToBase64String(data1);a1.Text += "\n加密后的字符串:" + encryptedString;byte[] data2 = Convert.FromBase64String(encryptedString);string s = aes.DescrptString(data2, key, iv);a1.Text += "\n解密后的字符串:" + s;}创建⼀个aes类,核⼼代码为:public static byte[] EncryptString(string str1, string str2, byte[] key, byte[] iv) //使⽤AES算法加密字符串{string ss = "";FileStream fs = new FileStream(str1, FileMode.Open, FileAccess.Read);StreamReader sr = new StreamReader(fs);ss = sr.ReadToEnd();fs.Close();sr.Close();FileStream fs1 = new FileStream(str2, FileMode.Create, FileAccess.Write);using (Aes aesAlg = Aes.Create()){ICryptoTransform encryptor = aesAlg.CreateEncryptor(key, iv);CryptoStream cs = new CryptoStream(fs1, encryptor, CryptoStreamMode.Write);using (StreamWriter sw = new StreamWriter(cs)){sw.Write(ss);}cs.Close();fs1.Close();}fs1 = new FileStream(str2, FileMode.Open, FileAccess.Read);BinaryReader br = new BinaryReader(fs1);byte[] encrypted = br.ReadBytes(10240);br.Close();fs1.Close();return encrypted;}public static string DescrptString(byte[] data, byte[] key, byte[] iv) //使⽤AES算法解密字符串{string str = "";using (Aes aesAlg = Aes.Create()){ICryptoTransform decryptor = aesAlg.CreateDecryptor(key, iv);MemoryStream ms = new MemoryStream(data);CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read);using (StreamReader sr = new StreamReader(cs)){str = sr.ReadToEnd();}cs.Close();ms.Close();}return str;}public static void GenKeyIV(string password, out byte[] key, out byte[] iv) //根据提供的密码⽣成key和IV{using (Aes aes = Aes.Create()){key = new byte[aes.Key.Length];byte[] pwdBytes = Encoding.UTF8.GetBytes(password);for (int i = 0; i < pwdBytes.Length; i++){key[i] = pwdBytes[i];}iv = new byte[aes.IV.Length];for (int i = 0; i < pwdBytes.Length; i++){iv[i] = pwdBytes[i];}}}public static void GenKeyIV(out byte[] key, out byte[] iv) //随机⽣成Key和IV{using (Aes aes = Aes.Create()){key = aes.Key;iv = aes.IV;}}运⾏之后的结果为:加密后的字符串会根据你填写的密码框数据⽽改变。

JAVA实现AES加密算法代码

JAVA实现AES加密算法代码

JAVA实现AES加密算法代码JA V A实现AES加密算法代码近些年DES使用越来越少,原因就在于其使用56位密钥,比较容易被破解,近些年来逐渐被AES替代,AES已经变成目前对称加密中最流行算法之一;AES可以使用128、192、和256位密钥,并且用128位分组加密和解密数据。

本文就简单介绍如何通过JA V A实现AES加密。

1. JA V A 实现闲话少许,掠过AES加密原理及算法,关于这些直接搜索专业网站吧,我们直接看JA V A的具体实现。

1.1 加密代码有详细解释,不多废话。

/*** 加密** @param content 需要加密的内容*@param password 加密密码* @return*/public static byte[] encrypt(String content, String password) {try {KeyGenerator kgen =KeyGenerator.getInstance("AES");kgen.init(128, new SecureRandom(password.getBytes()));SecretKey secretKey = kgen.generateKey();byte[] enCodeFormat = secretKey.getEncoded();SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");Cipher cipher = Cipher.getInstance("AES");// 创建密码器byte[] byteContent = content.getBytes("utf-8");cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化SecretKeySpec(enCodeFormat, "AES");Cipher cipher = Cipher.getInstance("AES");// 创建密码器cipher.init(Cipher.DECRYPT_MODE, key);// 初始化byte[] result = cipher.doFinal(content);return result; //加密} catch (NoSuchAlgorithmException e){ e.printStackTrace();} catch (NoSuchPaddingException e) { e.printStackTrace();} catch (InvalidKeyException e){ e.printStackTrace();} catch (IllegalBlockSizeException e) { e.printStackTrace();} catch (BadPaddingException e){ e.printStackTrace();}return null;}/**解密* @param content 待解密内容* @param password 解密密钥* @return*/public static byte[] decrypt(byte[] content, String password) {try {KeyGenerator kgen =KeyGenerator.getInstance("AES");kgen.init(128, new SecureRandom(password.getBytes()));SecretKey secretKey = kgen.generateKey();byte[] enCodeFormat = secretKey.getEncoded();SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");Cipher cipher = Cipher.getInstance("AES");// 创建密码器cipher.init(Cipher.DECRYPT_MODE, key);// 初始化byte[] result = cipher.doFinal(content);return result; //加密} catch (NoSuchAlgorithmException e){ e.printStackTrace();} catch (NoSuchPaddingException e) { e.printStackTrace();} catch (InvalidKeyException e){ e.printStackTrace();} catch (IllegalBlockSizeException e) { e.printStackTrace();} catch (BadPaddingException e){ e.printStackTrace();}return null;}2.3 测试代码String content = "test";String password = "12345678";//加密System.out.println("加密前:" + content);byte[] encryptResult = encrypt(content, password);//解密byte[] decryptResult = decrypt(encryptResult,password); System.out.println("解密后:" + new String(decryptResult)); String content = "test";String password = "12345678"; //加密System.out.println("加密前:" + content);byte[] encryptResult = encrypt(content, password);//解密byte[] decryptResult =decrypt(encryptResult,password);System.out.println("解密后:" + new String(decryptResult));输出结果如下:加密前:test解密后:test 2.4 容易出错的地方但是如果我们将测试代码修改一下,如下:String content = "test";String password = "12345678";//加密System.out.println("加密前:" + content);byte[] encryptResult = encrypt(content, password);try {String encryptResultStr = newString(encryptResult,"utf-8");//解密byte[] decryptResult =decrypt(encryptResultStr.getBytes("utf-8"),password); System.out.println("解密后:" + newString(decryptResult));} catch (UnsupportedEncodingException e){ e.printStackTrace();}String content = "test"; String password = "12345678";//加密System.out.println("加密前:" + content);byte[] encryptResult = encrypt(content, password);try {String encryptResultStr = newString(encryptResult,"utf-8");//解密byte[] decryptResult =decrypt(encryptResultStr.getBytes("utf-8"),password); System.out.println("解密后:" + newString(decryptResult));} catch(UnsupportedEncodingException e){ e.printStackTrace();}则,系统会报出如下异常:javax.crypto.IllegalBlockSizeException: Input length must be multiple of 16 when decrypting with padded cipher atcom.sun.crypto.provider.SunJCE_f.b(DashoA13*..)at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)at com.sun.crypto.provider.AESCipher.engineDoFinal(DashoA 13*..)at javax.crypto.Cipher.doFinal(DashoA13*..)这主要是因为加密后的byte数组是不能强制转换成字符串的,换言之:字符串和byte数组在这种情况下不是互逆的;要避免这种情况,我们需要做一些修订,可以考虑将二进制数据转换成十六进制表示,主要有如下两个方法: 2.4.1将二进制转换成16进制/**将二进制转换成16进制* @param buf* @return*/public static String parseByte2HexStr(byte buf[]) {StringBuffer sb = new StringBuffer();for (int i = 0; i String hex = Integer.toHexString(buf[i] & 0xFF);if (hex.length() == 1) {hex = '0' + hex;}sb.append(hex.toUpperCase());}returnsb.toString();}/**将二进制转换成16进制*@param buf* @return*/public static StringparseByte2HexStr(byte buf[]) {StringBuffer sb = new StringBuffer();for (int i = 0; i String hex = Integer.toHexString(buf[i] & 0xFF);if (hex.length() == 1) {hex = '0' + hex;}sb.append(hex.toUpperCase());}returnsb.toString();} 2.4.2 将16进制转换为二进制/**将16进制转换为二进制* @param hexStr*@return*/public static byte[]parseHexStr2Byte(String hexStr) {if (hexStr.length() return null;byte[] result = new byte[hexStr.length()/2]; for (int i = 0;i int high =Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);intlow = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16); result[i] = (byte) (high * 16 + low);}return result;}/**将16进制转换为二进制* @param hexStr*@return*/public static byte[]parseHexStr2Byte(String hexStr) {if (hexStr.length() return null;byte[] result = new byte[hexStr.length()/2]; for (int i = 0;i int high =Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);intlow = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16);result[i] = (byte) (high * 16 + low);}return result;}然后,我们再修订以上测试代码,如下:String content = "test";String password = "12345678"; //加密System.out.println("加密前:" + content);byte[] encryptResult = encrypt(content, password);String encryptResultStr = parseByte2HexStr(encryptResult); System.out.println("加密后:" + encryptResultStr);//解密byte[] decryptFrom =parseHexStr2Byte(encryptResultStr);byte[] decryptResult = decrypt(decryptFrom,password); System.out.println("解密后:" + new String(decryptResult)); String content = "test";String password = "12345678"; //加密System.out.println("加密前:" + content);byte[] encryptResult = encrypt(content, password);String encryptResultStr = parseByte2HexStr(encryptResult); System.out.println("加密后:" + encryptResultStr);//解密byte[] decryptFrom =parseHexStr2Byte(encryptResultStr);byte[] decryptResult = decrypt(decryptFrom,password); System.out.println("解密后:" + new String(decryptResult));测试结果如下:加密前:test加密后:73C58BAFE578C59366D8C995CD0B9D6D解密后:test2.5 另外一种加密方式还有一种加密方式,大家可以参考如下:/*** 加密** @param content 需要加密的内容* @param password 加密密码*@return*/public static byte[] encrypt2(String content, String password) {try {SecretKeySpec key = new SecretKeySpec(password.getBytes(), "AES");Cipher cipher =Cipher.getInstance("AES/ECB/NoPadding");byte[] byteContent = content.getBytes("utf-8");cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化byte[] result = cipher.doFinal(byteContent);return result; // 加密} catch (NoSuchAlgorithmException e) { e.printStackTrace();} catch (NoSuchPaddingException e) { e.printStackTrace();} catch (InvalidKeyException e){ e.printStackTrace();} catch (UnsupportedEncodingException e){ e.printStackTrace();} catch (IllegalBlockSizeException e) { e.printStackTrace();} catch (BadPaddingException e){ e.printStackTrace();}return null;}/*** 加密** @param content 需要加密的内容* @param password 加密密码* @return*/ public static byte[] encrypt2(String content, String password) {try {SecretKeySpec key = newSecretKeySpec(password.getBytes(), "AES");Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");byte[] byteContent = content.getBytes("utf-8");cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化byte[] result = cipher.doFinal(byteContent);return result; // 加密} catch (NoSuchAlgorithmException e) { e.printStackTrace();} catch (NoSuchPaddingException e) { e.printStackTrace();} catch (InvalidKeyException e){ e.printStackTrace();} catch (UnsupportedEncodingException e){ e.printStackTrace();} catch (IllegalBlockSizeException e) { e.printStackTrace();} catch (BadPaddingException e){ e.printStackTrace();}return null;}这种加密方式有两种限制密钥必须是16位的待加密内容的长度必须是16的倍数,如果不是16的倍数,就会出如下异常:javax.crypto.IllegalBlockSizeException: Input length not multiple of 16 bytes atcom.sun.crypto.provider.SunJCE_f.a(DashoA13*..)at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)at com.sun.crypto.provider.AESCipher.engineDoFinal(DashoA 13*..)at javax.crypto.Cipher.doFinal(DashoA13*..)要解决如上异常,可以通过补全传入加密内容等方式进行避免。

aesencrypt方法

aesencrypt方法

aesencrypt方法AES(Advanced Encryption Standard)是一种对称加密算法,它是目前应用最广泛的加密算法之一、AES算法使用相同的密钥进行加密和解密,密钥长度可以是128位、192位或256位。

在Python中,可以使用`pycryptodome`库来实现AES加密。

具体实现一个`aesencrypt`方法如下:```pythonfrom Crypto.Cipher import AESfrom Crypto.Util.Padding import paddef aesencrypt(key, plaintext):cipher = AES.new(key, AES.MODE_ECB)padded_plaintext = pad(plaintext, AES.block_size)ciphertext = cipher.encrypt(padded_plaintext)return ciphertext.hex```上述代码中,`aesencrypt`方法接受两个参数:`key`表示密钥,`plaintext`表示待加密的明文。

方法内部首先创建一个AES加密器对象,使用ECB模式进行加密。

然后对明文进行填充操作,确保明文长度是AES分组长度的整数倍。

最后对填充后的明文进行加密,并将结果转换为十六进制字符串形式返回。

使用该`aesencrypt`方法进行加密可以按如下方式调用:```pythonkey = b'Sixteen byte key'plaintext = b'Hello World'ciphertext = aesencrypt(key, plaintext)print(ciphertext)```以上代码中,我们使用一个16字节的密钥`b'Sixteen byte key'`和明文`b'Hello World'`进行加密,并打印出加密结果。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
{
return InitAES(new AES(),inSize,key,keySize,type);
}
/*
*/
void CipherLoop(AES *aes)
{
unsigned char temp[4];
unsigned long *word8 = aes->Word,
*State = aes->State;
---------------------
| | | | |
---------------------
| | | | |
---------------------
| | | | |
---------------------
*/
memcpy(State+Nb,State,12);
/*
int 密钥长
unsigned long 属性(标实类型)
返回AES结构指针
*/
AES *InitAES(AES *aes,
int inSize,
unsigned char* key,
int keySize, TYPE type);
/*
生成加密用的参数AES结构
int inSize 块大小
int *inSize 密文长
byte *out 明文存放的地方
byte *key 密钥key
int *keySize 密钥长
*/
void InvCipher(unsigned char* input, int inSize, unsigned char* out, unsigned char* key, int keySize)
aes->State += 3;
return aes;
}
/*
生成加密用的参数AES结构
int inSize 块大小
byte* 密钥
int 密钥长
返回AES结构指针
*/
AES *InitAES(int inSize, unsigned char* key, int keySize,unsigned long type)
int Nb = aes->Nb,
Nr = aes->Nr;
int r;
for (r = 0; r < Nb; ++r)
{
State[r] ^= word8[r];
}
for (int round =1; round {
word8 += Nb;
/*
假设Nb=4;
---பைடு நூலகம்-----------------
int inSize 块大小
byte* 密钥
int 密钥长
返回AES结构指针
*/
AES *InitAES(AES *aes,int inSize, unsigned char *key, int keySize, TYPE type)
{
int Nb = inSize >>2,
Nk = keySize >>2,
}AES;
/*
加密数据
byte *input 明文
byte *inSize 明文长
byte *out 密文存放的地方
byte *key 密钥key
byte *keySize 密钥长
*/
void Cipher(
unsigned char* input,
int inSize,
/*
加密数据
byte *input 明文
byte *inSize 明文长
byte *out 密文存放的地方
byte *key 密钥key
byte *keySize 密钥长
*/
void Cipher(unsigned char* input, int inSize, unsigned char* out, unsigned char* key, int keySize)
AES加密算法源代码
//AES.h
#define decrypt TRUE
#define encrypt FALSE
#define TYPE BOOL
typedef struct _AES{
int Nb;
int Nr;
int Nk;
unsigned long *Word;
unsigned long *State;
void InvCipher(
unsigned char* input,
int inSize,
unsigned char* out,
unsigned char* key,
int keySize);
/*
生成加密用的参数AES结构
int inSize 块大小
byte* 密钥
int Nb = aes->Nb,
Nr = aes->Nr;
unsigned char temp[4];
int r =0;
Word += Nb*Nr;
for (r = 0; r < Nb; ++r)
{
State[r] ^= Word[r];
}
State -= 3;
for (int round = Nr-1; round > 0; --round)
---------------------
| | s1 | s2 | s3 |
---------------------
| | | s6 | s7 |
---------------------
| | | | sb |
---------------------
*/
for(r =0; r {
---------------------
| s4 | s5 | s6 | s7 |
---------------------
| s8 | s9 | sa | sb |
---------------------
| sc | sd | se | sf |
---------------------
*((unsigned char*)State+1) = Sbox[*((unsigned char*)(State+1)+1)];
*((unsigned char*)State+2) = Sbox[*((unsigned char*)(State+2)+2)];
*((unsigned char*)State+3) = Sbox[*((unsigned char*)(State+3)+3)];
temp[3] = Sbox[*((unsigned char*)(State+3)+3)];
*((unsigned char*)State) = Log_02[temp[0]] ^ Log_03[temp[1]] ^ temp[2] ^ temp[3];
*((unsigned char*)State+1) = Log_02[temp[1]] ^ Log_03[temp[2]] ^ temp[3] ^ temp[0];
AES *aes);
/*
解密时进行Nr轮逆运算
AES * aes 运行时参数
*/
void InvCipherLoop(
AES *aes);
/*
释放AES结构和State和密钥库word
*/
void freeAES(
AES *aes);
//AES.cpp
#include "stdafx.h"
unsigned char* out,
unsigned char* key,
int keySize);
/*
解密数据
byte *input 密文
int *inSize 密文长
byte *out 明文存放的地方
byte *key 密钥key
int *keySize 密钥长
*/
*/
memcpy(State,State+Nb,12);
*State ^= word8[r];
State++;
}
State -= Nb;
}
memcpy(State+Nb,State,12);
word8 += Nb;
for(r =0; r {
*((unsigned char*)State) = Sbox[*(unsigned char*)State];
Nr = Nb < Nk ? Nk:Nb+6;
aes->Nb = Nb;
aes->Nk = Nk;
aes->Nr = Nr;
aes->Word = keyExpansion(key,Nb,Nr,Nk);
aes->State = new unsigned long[Nb+3];
if(type)
Nb=4;
---------------------
| s0 | | | |
---------------------
| s4 | s5 | | |
相关文档
最新文档