Int CTextHandler::GetTextInternal(PVoid pvOutBuffer, Int32 BufferSize, PCChar lpSrcText, Int32 SrcLength, Bool bRemove) { PByte pbOutBuffer; Int32 TextLength, Length; UInt32 Hash[4], SrcTextHash[8]; PUInt32 pEncryptedText; STextHeader *pHeader; aes_encrypt_ctx ctx; sha256((PByte)lpSrcText, SrcLength, (PByte)SrcTextHash); Hash[0] = SrcTextHash[0] ^ SrcTextHash[4]; Hash[1] = SrcTextHash[1] ^ SrcTextHash[5]; Hash[2] = SrcTextHash[2] ^ SrcTextHash[6]; Hash[3] = SrcTextHash[3] ^ SrcTextHash[7]; pHeader = FindTextPos(Hash); if (pHeader == NULL || bRemove) return (Int)pHeader; TextLength = pHeader->Length ^ pHeader->Hash[0] ^ pHeader->Hash[2]; aes_encrypt_key128(&SrcTextHash[4], &ctx); pbOutBuffer = (PByte)pvOutBuffer; pEncryptedText = (PUInt32)(pHeader + 1); Length = TextLength; while (Length >= 16 && BufferSize >= 16) { Length -= 16; BufferSize -= 16; aes_encrypt(SrcTextHash, SrcTextHash, &ctx); *((PUInt32)pbOutBuffer + 0) = pEncryptedText[0] ^ SrcTextHash[0]; *((PUInt32)pbOutBuffer + 1) = pEncryptedText[1] ^ SrcTextHash[1]; *((PUInt32)pbOutBuffer + 2) = pEncryptedText[2] ^ SrcTextHash[2]; *((PUInt32)pbOutBuffer + 3) = pEncryptedText[3] ^ SrcTextHash[3]; SrcTextHash[0] = pEncryptedText[0]; SrcTextHash[1] = pEncryptedText[1]; SrcTextHash[2] = pEncryptedText[2]; SrcTextHash[3] = pEncryptedText[3]; pbOutBuffer += 16; pEncryptedText += 4; } if (Length != 0 && BufferSize >= Length) { UInt32 DecryptBuffer[4]; aes_encrypt(SrcTextHash, SrcTextHash, &ctx); DecryptBuffer[0] = pEncryptedText[0] ^ SrcTextHash[0]; DecryptBuffer[1] = pEncryptedText[1] ^ SrcTextHash[1]; DecryptBuffer[2] = pEncryptedText[2] ^ SrcTextHash[2]; DecryptBuffer[3] = pEncryptedText[3] ^ SrcTextHash[3]; memcpy(pbOutBuffer, DecryptBuffer, min(Length, BufferSize)); pbOutBuffer += Length; BufferSize -= Length; } /* if (BufferSize > 0) *pbOutBuffer++ = 0; */ return pbOutBuffer - (PByte)pvOutBuffer; }
int main(int argc,char **argv) { if(argc != 2) { perror("\n Error:\nCorrect Usage: Enter Password to be used"); exit(-1); } EVP_CIPHER_CTX en,de; /* The EVP structure which keeps track of all crypt operations see evp.h for details */ int in, out, fd, dec; /* fd for input and output files and random dev*/ unsigned int pwd_len = strlen((const char *)argv[1]); /* Length of the pwd supplied by the user */ unsigned char *pwd =(unsigned char*) argv[1]; /* Pointer to the pwd supplied by the user */ unsigned char salt[8]; if((in = open("plain.txt",O_RDONLY)) == -1) /* Opening a plain text file for encryption */ { perror("\n Error,Opening file for reading::"); exit(-1); } if((fd = open("/dev/random", O_RDONLY)) == -1) { perror("\n Error,Opening /dev/random::"); exit(-1); } else{ if(read(fd,salt,8) == -1) { perror("\n Error,reading from /dev/random::"); exit(-1); } } if(aes_init(pwd,pwd_len,(unsigned char*) salt,&en,&de)) /* Generating Key and IV and initializing the EVP struct */ { perror("\n Error, Cant initialize key and IV:"); return -1; } if((out = open("encrypt.txt",O_RDWR|O_CREAT,0400|0200)) == -1) { perror("\n Error,Opening the file to be written::"); exit(-1); } if((dec = open("dec22.txt",O_RDWR|O_CREAT,0400|0200)) == -1) { perror("\n ERROR,Opening the file to write decrypted bytes::"); exit(-1); } if(aes_encrypt(&en,in,out)) { perror("\n ERROR,ENCRYPTING:"); exit(-1); } else { if((lseek(out,0,SEEK_SET)) != 0) { perror("\n ERROR,lseek:"); exit(-1); } if(aes_decrypt(&de,out,dec)) { perror("\n ERROR,DECRYPTING DATA:"); exit(-1); } } close(in); close(out); close(fd); close(dec); EVP_CIPHER_CTX_cleanup(&en); EVP_CIPHER_CTX_cleanup(&de); return 0; }
int crypto_cipher_encrypt(struct crypto_cipher *ctx, const u8 *plain, u8 *crypt, size_t len) { size_t i, j, blocks; switch (ctx->alg) { case CRYPTO_CIPHER_ALG_RC4: if (plain != crypt) os_memcpy(crypt, plain, len); rc4_skip(ctx->u.rc4.key, ctx->u.rc4.keylen, ctx->u.rc4.used_bytes, crypt, len); ctx->u.rc4.used_bytes += len; break; case CRYPTO_CIPHER_ALG_AES: if (len % AES_BLOCK_SIZE) return -1; blocks = len / AES_BLOCK_SIZE; for (i = 0; i < blocks; i++) { for (j = 0; j < AES_BLOCK_SIZE; j++) ctx->u.aes.cbc[j] ^= plain[j]; aes_encrypt(ctx->u.aes.ctx_enc, ctx->u.aes.cbc, ctx->u.aes.cbc); os_memcpy(crypt, ctx->u.aes.cbc, AES_BLOCK_SIZE); plain += AES_BLOCK_SIZE; crypt += AES_BLOCK_SIZE; } break; case CRYPTO_CIPHER_ALG_3DES: if (len % 8) return -1; blocks = len / 8; for (i = 0; i < blocks; i++) { for (j = 0; j < 8; j++) ctx->u.des3.cbc[j] ^= plain[j]; des3_encrypt(ctx->u.des3.cbc, &ctx->u.des3.key, ctx->u.des3.cbc); os_memcpy(crypt, ctx->u.des3.cbc, 8); plain += 8; crypt += 8; } break; case CRYPTO_CIPHER_ALG_DES: if (len % 8) return -1; blocks = len / 8; for (i = 0; i < blocks; i++) { for (j = 0; j < 8; j++) ctx->u.des3.cbc[j] ^= plain[j]; des_block_encrypt(ctx->u.des.cbc, ctx->u.des.ek, ctx->u.des.cbc); os_memcpy(crypt, ctx->u.des.cbc, 8); plain += 8; crypt += 8; } break; default: return -1; } return 0; }
/* * encrypt_stream * * This function is called to encrypt the open data steam "infp". */ int encrypt_stream(FILE *infp, FILE *outfp, wchar_t* passwd, int passlen) { aes_context aes_ctx; sha256_context sha_ctx; aescrypt_hdr aeshdr; sha256_t digest; unsigned char IV[16]; unsigned char iv_key[48]; int i, j, n; unsigned char buffer[32]; unsigned char ipad[64], opad[64]; unsigned char tag_buffer[256]; HCRYPTPROV hProv; DWORD result_code; // Prepare for random number generation if (!CryptAcquireContext( &hProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) { result_code = GetLastError(); if (GetLastError() == NTE_BAD_KEYSET) { if (!CryptAcquireContext( &hProv, NULL, NULL, PROV_RSA_FULL, CRYPT_NEWKEYSET|CRYPT_VERIFYCONTEXT)) { result_code = GetLastError(); } else { result_code = ERROR_SUCCESS; } } if (result_code != ERROR_SUCCESS) { fprintf(stderr, "Could not acquire handle to crypto context"); return -1; } } // Create the 16-bit IV and 32-bit encryption key // used for encrypting the plaintext file. We do // not trust the system's randomization functions, so // we improve on that by also hashing the random digits // and using only a portion of the hash. This IV and key // generation could be replaced with any good random // source of data. memset(iv_key, 0, 48); for (i=0; i<48; i+=16) { memset(buffer, 0, 32); sha256_starts(&sha_ctx); for(j=0; j<256; j++) { if (!CryptGenRandom(hProv, 32, (BYTE *) buffer)) { fprintf(stderr, "Windows is unable to generate random digits"); return -1; } sha256_update(&sha_ctx, buffer, 32); } sha256_finish(&sha_ctx, digest); memcpy(iv_key+i, digest, 16); } // Write an AES signature at the head of the file, along // with the AES file format version number. buffer[0] = 'A'; buffer[1] = 'E'; buffer[2] = 'S'; buffer[3] = (unsigned char) 0x02; // Version 2 buffer[4] = '\0'; // Reserved for version 0 if (fwrite(buffer, 1, 5, outfp) != 5) { fprintf(stderr, "Error: Could not write out header data\n"); CryptReleaseContext(hProv, 0); return -1; } // Write out the CREATED-BY tag j = 11 + // "CREATED-BY\0" (int)strlen(PROG_NAME) + // Program name 1 + // Space (int)strlen(PROG_VERSION); // Program version ID // Our extension buffer is only 256 octets long, so // let's not write an extension if it is too big if (j < 256) { buffer[0] = '\0'; buffer[1] = (unsigned char) (j & 0xff); if (fwrite(buffer, 1, 2, outfp) != 2) { fprintf(stderr, "Error: Could not write tag to AES file (1)\n"); CryptReleaseContext(hProv, 0); return -1; } strncpy((char *)tag_buffer, "CREATED_BY", 255); tag_buffer[255] = '\0'; if (fwrite(tag_buffer, 1, 11, outfp) != 11) { fprintf(stderr, "Error: Could not write tag to AES file (2)\n"); CryptReleaseContext(hProv, 0); return -1; } sprintf((char *)tag_buffer, "%s %s", PROG_NAME, PROG_VERSION); j = (int) strlen((char *)tag_buffer); if (fwrite(tag_buffer, 1, j, outfp) != j) { fprintf(stderr, "Error: Could not write tag to AES file (3)\n"); CryptReleaseContext(hProv, 0); return -1; } } // Write out the "container" extension buffer[0] = '\0'; buffer[1] = (unsigned char) 128; if (fwrite(buffer, 1, 2, outfp) != 2) { fprintf(stderr, "Error: Could not write tag to AES file (4)\n"); CryptReleaseContext(hProv, 0); return -1; } memset(tag_buffer, 0, 128); if (fwrite(tag_buffer, 1, 128, outfp) != 128) { fprintf(stderr, "Error: Could not write tag to AES file (5)\n"); CryptReleaseContext(hProv, 0); return -1; } // Write out 0x0000 to indicate that no more extensions exist buffer[0] = '\0'; buffer[1] = '\0'; if (fwrite(buffer, 1, 2, outfp) != 2) { fprintf(stderr, "Error: Could not write tag to AES file (6)\n"); CryptReleaseContext(hProv, 0); return -1; } // Create a random IV sha256_starts( &sha_ctx); for (i=0; i<256; i++) { if (!CryptGenRandom(hProv, 32, (BYTE *) buffer)) { fprintf(stderr, "Windows is unable to generate random digits"); CryptReleaseContext(hProv, 0); return -1; } sha256_update( &sha_ctx, buffer, 32); } sha256_finish( &sha_ctx, digest); memcpy(IV, digest, 16); // We're finished collecting random data CryptReleaseContext(hProv, 0); // Write the initialization vector to the file if (fwrite(IV, 1, 16, outfp) != 16) { fprintf(stderr, "Error: Could not write out initialization vector\n"); return -1; } // Hash the IV and password 8192 times memset(digest, 0, 32); memcpy(digest, IV, 16); for(i=0; i<8192; i++) { sha256_starts( &sha_ctx); sha256_update( &sha_ctx, digest, 32); sha256_update( &sha_ctx, (unsigned char*)passwd, (unsigned long)(passlen * sizeof(wchar_t))); sha256_finish( &sha_ctx, digest); } // Set the AES encryption key aes_set_key(&aes_ctx, digest, 256); // Set the ipad and opad arrays with values as // per RFC 2104 (HMAC). HMAC is defined as // H(K XOR opad, H(K XOR ipad, text)) memset(ipad, 0x36, 64); memset(opad, 0x5C, 64); for(i=0; i<32; i++) { ipad[i] ^= digest[i]; opad[i] ^= digest[i]; } sha256_starts(&sha_ctx); sha256_update(&sha_ctx, ipad, 64); // Encrypt the IV and key used to encrypt the plaintext file, // writing that encrypted text to the output file. for(i=0; i<48; i+=16) { // Place the next 16 octets of IV and key buffer into // the input buffer. memcpy(buffer, iv_key+i, 16); // XOR plain text block with previous encrypted // output (i.e., use CBC) for(j=0; j<16; j++) { buffer[j] ^= IV[j]; } // Encrypt the contents of the buffer aes_encrypt(&aes_ctx, buffer, buffer); // Concatenate the "text" as we compute the HMAC sha256_update(&sha_ctx, buffer, 16); // Write the encrypted block if (fwrite(buffer, 1, 16, outfp) != 16) { fprintf(stderr, "Error: Could not write iv_key data\n"); return -1; } // Update the IV (CBC mode) memcpy(IV, buffer, 16); } // Write the HMAC sha256_finish(&sha_ctx, digest); sha256_starts(&sha_ctx); sha256_update(&sha_ctx, opad, 64); sha256_update(&sha_ctx, digest, 32); sha256_finish(&sha_ctx, digest); // Write the encrypted block if (fwrite(digest, 1, 32, outfp) != 32) { fprintf(stderr, "Error: Could not write iv_key HMAC\n"); return -1; } // Re-load the IV and encryption key with the IV and // key to now encrypt the datafile. Also, reset the HMAC // computation. memcpy(IV, iv_key, 16); // Set the AES encryption key aes_set_key(&aes_ctx, iv_key+16, 256); // Set the ipad and opad arrays with values as // per RFC 2104 (HMAC). HMAC is defined as // H(K XOR opad, H(K XOR ipad, text)) memset(ipad, 0x36, 64); memset(opad, 0x5C, 64); for(i=0; i<32; i++) { ipad[i] ^= iv_key[i+16]; opad[i] ^= iv_key[i+16]; } // Wipe the IV and encryption mey from memory memset(iv_key, 0, 48); sha256_starts(&sha_ctx); sha256_update(&sha_ctx, ipad, 64); // Initialize the last_block_size value to 0 aeshdr.last_block_size = 0; while ((n = (int)fread(buffer, 1, 16, infp)) > 0) { // XOR plain text block with previous encrypted // output (i.e., use CBC) for(i=0; i<16; i++) { buffer[i] ^= IV[i]; } // Encrypt the contents of the buffer aes_encrypt(&aes_ctx, buffer, buffer); // Concatenate the "text" as we compute the HMAC sha256_update(&sha_ctx, buffer, 16); // Write the encrypted block if (fwrite(buffer, 1, 16, outfp) != 16) { fprintf(stderr, "Error: Could not write to output file\n"); return -1; } // Update the IV (CBC mode) memcpy(IV, buffer, 16); // Assume this number of octets is the file modulo aeshdr.last_block_size = n; } // Check to see if we had a read error if (n < 0) { fprintf(stderr, "Error: Couldn't read input file\n"); return -1; } // Write the file size modulo buffer[0] = (char) (aeshdr.last_block_size & 0x0F); if (fwrite(buffer, 1, 1, outfp) != 1) { fprintf(stderr, "Error: Could not write the file size modulo\n"); return -1; } // Write the HMAC sha256_finish(&sha_ctx, digest); sha256_starts(&sha_ctx); sha256_update(&sha_ctx, opad, 64); sha256_update(&sha_ctx, digest, 32); sha256_finish(&sha_ctx, digest); if (fwrite(digest, 1, 32, outfp) != 32) { fprintf(stderr, "Error: Could not write the file HMAC\n"); return -1; } return 0; }
int main(int argc, char *argv[]) { /* { fix start } */ ltc_mp = ltm_desc; /* { fix end } */ int sockfd = 0; struct sockaddr_in serv_addr; if(argc != 2) { printf("\n Usage: %s <ip of server> \n",argv[0]); return 1; } if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { printf("\n Error : Could not create socket \n"); return 1; } memset(&serv_addr, '0', sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(5002); if(inet_pton(AF_INET, argv[1], &serv_addr.sin_addr)<=0) { printf("\n inet_pton error occured\n"); return 1; } if( connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) { printf("\n Error : Connect Failed \n"); return 1; } initEncrypt(); ecc_key encryptKey; loadKey(&encryptKey, "bpublic.key"); ecc_key decryptKey; loadKey(&decryptKey, "aprivate.key"); /* { userString start } */ printf("Enter message to send\n"); unsigned char message[256]; fgets((char*)message,256,stdin); /* { userString end } */ /* { sendNonceA start } */ int nonceA = randomNumber(); printf("nonceA = %i\n",nonceA); printf("Encrypting nonceA with bpub\n"); unsigned char nonceA_enc[2048]; unsigned long outLength = 2048; ecc_encrypt((unsigned char*)&nonceA, sizeof(int), nonceA_enc, &outLength,&encryptKey); printf("Sending nonceA\n"); write(sockfd, nonceA_enc, outLength); /* { sendNonceA end } */ /* { resiveSessionKey start } */ unsigned char recvBuff[1024]; unsigned long msgLength; msgLength = recv(sockfd, recvBuff, sizeof(recvBuff),0); struct SessionKey sKey; unsigned long inLength = sizeof(struct SessionKey); ecc_decrypt(recvBuff,msgLength,(unsigned char*)&sKey,&inLength,&decryptKey); printf("Received sKey, nonceA = %i, key = %i\n", sKey.nonceA, sKey.key); /* { resiveSessionKey end } */ /* { resendKey start } */ my_aes_setup(sKey.key); sKey.nonceA ++; printf("Sending nonceA = %i encrypted with AES\n", sKey.nonceA); outLength = 2048; aes_encrypt((unsigned char*)&sKey.nonceA,sizeof(int),nonceA_enc, &outLength); write(sockfd, nonceA_enc, outLength); /* { resendKey end } */ /* { sendMessage start } */ printf("Sending message encrypted with AES\n"); printf("%s", message); outLength = 2048; unsigned char message_enc[2048]; aes_encrypt(message, strlen((char*)message), message_enc, &outLength); write(sockfd, message_enc, outLength); /* { sendMessage end } */ return -1; }
void WiiSave::writeBanner() { m_writer->setEndianess(Stream::BigEndian); m_writer->setAutoResizing(true); m_writer->writeInt64(m_banner->gameID()); m_writer->writeInt32((0x60a0+0x1200)*m_banner->icons().size()); m_writer->writeByte((Int8)m_banner->permissions()); m_writer->seek(1); m_writer->writeBytes((Int8*)md5_blanker, 16); m_writer->seek(2); m_writer->writeInt32(0x5749424E); // WIBN m_writer->writeInt32(m_banner->flags()); m_writer->writeInt16(m_banner->animationSpeed()); m_writer->seek(22); m_writer->writeUnicode(m_banner->title()); if (m_writer->position() != 0x0080) m_writer->seek(0x0080, Stream::Beginning); m_writer->writeUnicode(m_banner->subtitle()); if (m_writer->position() != 0x00C0) m_writer->seek(0x00C0, Stream::Beginning); WiiImage* bannerImage = m_banner->bannerImage(); m_writer->writeBytes((Int8*)bannerImage->data(), bannerImage->width()*bannerImage->height()*2); // For empty icons Uint8* tmpIcon = new Uint8[48*48*2]; memset(tmpIcon, 0, 48*48*2); for (Uint32 i = 0; i < 8; ++i) { if (i < m_banner->icons().size()) { writeImage(m_banner->icons()[i]); } else { m_writer->writeBytes((Int8*)tmpIcon, 48*48*2); } } m_writer->save(); delete[] tmpIcon; // delete tmp buffer; Uint8* hash = new Uint8[0x10]; MD5(hash, (Uint8*)m_writer->data(), 0xF0C0); m_writer->seek(0x0E, Stream::Beginning); m_writer->writeBytes((Int8*)hash, 0x10); aes_set_key(sd_key); Uint8 data[0xF0C0]; memcpy(data, m_writer->data(), 0xF0C0); Uint8 tmpIV[26]; memcpy(tmpIV, sd_iv, 16); aes_encrypt(tmpIV, data, data, 0xF0C0); m_writer->seek(0, Stream::Beginning); m_writer->writeBytes((Int8*)data, 0xF0C0); m_writer->seek(0xF0C0, Stream::Beginning); }
int main(int argc, char **argv) { void* handle; char* error; EVP_CIPHER_CTX en, de; unsigned int salt[] = {12345, 54321}; unsigned char *key_data; FILE *fp; int key_data_len, i; char *input[] = {"Welcome Back Master! Unlocking.",NULL}; char *plaintext; unsigned char *ciphertext; int olen, len; long (*ReaderOpen)(void); long (*ReaderClose)(void); long (*LinearWrite)(PBYTE, short, short, short*, unsigned char, unsigned char); if (argc != 2) { printf("Please enter a 32-byte key string as parameter\n"); return -1; } if (strlen(argv[1]) != 32) { printf("Please enter a 32-byte key string as parameter\n"); return -1; } key_data = (unsigned char *)argv[1]; key_data_len = strlen(argv[1]); if (aes_init(key_data, key_data_len, (unsigned char *)&salt, &en, &de)) { printf("Couldn't initialize AES cipher\n"); return -1; } olen = len = strlen(input[0])+1; ciphertext = aes_encrypt(&en, (unsigned char *)input[0], &len); fp = fopen("/etc/MyAuth", "w"); if (!fp) { printf("Failed to open MyAuth file. Are you running as root?\n"); return -1; } fwrite(ciphertext, 1, 48, fp); fclose(fp); printf("MyAuth file has been created successfully\n"); handle = dlopen ("/usr/local/lib/libuFCoder1x64.so", RTLD_LAZY); error = dlerror (); if (error) { printf("libuFCoder1x64 library not found.\n"); return -1; } ReaderOpen = dlsym (handle, "ReaderOpen"); error = dlerror (); if (error) { printf ("Unable to find ReaderOpen function. Wrong library?\n", error); return -1; } i = ReaderOpen(); if (i != 0) { printf("\nUnable to open reader, error: %d\n", i); return -1; } LinearWrite = dlsym (handle, "LinearWrite"); error = dlerror (); if (error) { printf ("Unable to find LinearWrite function. Wrong library?\n", error); return -1; } short bytesret; BYTE DataBuf[753]; for (i=0;i<32;i++) DataBuf[i] = argv[1][i]; DataBuf[32]=0x00; i = LinearWrite(DataBuf, 0, 32, &bytesret, 0x60, 0); if (i== 0) { printf("\nKey written to RFID card successfully!\n"); printf("\nNow compile and install NFCMyAuth module\n"); printf("\nThen add \"auth required NFCMyAuth.so\" into PAM file\n"); } else printf("\nFailed to write to card! Error: %d\n", i); ReaderClose = dlsym (handle, "ReaderClose"); ReaderClose(); free(ciphertext); EVP_CIPHER_CTX_cleanup(&en); EVP_CIPHER_CTX_cleanup(&de); return 0; }
static void aes_encrypt_wrapper(cipher_ctx_t ctx, cipher_length_t length, uint8_t *dst, const uint8_t *src) { aes_encrypt(ctx, length, dst, src); }
int main(int argc, char *argv[]) { srand(time(NULL)); int fileSize, i, j, subkeySize = 1024, totalBytes = 0; // LOOOOOOOOOL int padMisses = 0; int got, numcrypts; char magic[2], dmagic[2]; uchar *aesKey, verifyBlock[22], backbuffer[16], subkey[1024]; uchar *plaintext = "<<'08infamouspat"; uchar *SHAworkspace; uchar salt[16], salted[16], dsalted[16]; uchar encbuf[4080], decbuf[4080]; aes_encrypt_ctx ctx[1]; char *openFile, *destFile; FILE *fd, *dfd; printIntro("Pump It Up Pro"); if (argc < 3) { printf("usage: %s <input file> <output file>\n", argv[0]); exit(0); } openFile = argv[1]; destFile = argv[2]; if ((fd = fopen(openFile, "rb")) == NULL) { fprintf(stderr, "%s: fopen(%s) failed D=\n", argv[0], argv[1]); exit(-1); } for (i = 0; i < subkeySize; i++) subkey[i] = rand() * 255; SHAworkspace = (uchar*)malloc(sizeof(uchar) * (subkeySize+47)); memcpy(SHAworkspace, subkey, subkeySize); memcpy(SHAworkspace+subkeySize, PProSubkeySalt, 47); aesKey = (uchar*)malloc(24 * sizeof(uchar)); memset(aesKey, '\0', 24); gcry_md_hash_buffer(GCRY_MD_SHA1, aesKey, SHAworkspace, subkeySize+47); printKey(aesKey); aes_encrypt_key(aesKey, 24, ctx); for (i = 0; i < 16; i++) salt[i] = rand() * 255; saltHash(salted, salt, 0x123456); aes_encrypt(salted, dsalted, ctx); for (i = 0; i < 16; i++) { verifyBlock[i] = plaintext[i] ^ dsalted[i]; } #ifdef KD_DEBUG printKey(aesKey); printbuffer("salt", salt); printbuffer("salted", salted); printbuffer("dsalted", dsalted); printbuffer("plaintext", plaintext); printbuffer("verifyBlock", verifyBlock); #endif if ((dfd = fopen(destFile, "wb")) == NULL) { fprintf(stderr, "%s: fopen(%s) failed D=\n", argv[0], destFile); fclose(fd); exit(-1); } fwrite("8O", 1, 2, dfd); fwrite(&subkeySize, 1, 4, dfd); fwrite(subkey, 1, subkeySize, dfd); fwrite(salt, 1, 16, dfd); fseek(fd, 0, SEEK_END); fileSize = ftell(fd); fseek(fd, 0, SEEK_SET); printf("file size: %u\n", fileSize); fwrite(&fileSize, 1, 4, dfd); fwrite(verifyBlock, 1, 16, dfd); printf("encrypting into %s...\n", destFile); do { if ((got = fread(decbuf, 1, 4080, fd)) == -1) { fprintf(stderr, "wtf..?\n"); fclose(dfd); fclose(fd); exit(-1); } numcrypts = got / 16; if (got % 16 > 0) { numcrypts++; } if (got > 0) { for (i = 0; i < numcrypts; i++) { //saltHash(salted, salt, numcrypts); //memcpy(salted, salt, 16); //salted[0] += numcrypts; aes_encrypt(salt, dsalted, ctx); // LOLOLOLOLOL // this should cover about a 320GB file, so we should be good... if (salt[0] == 255 && salt[1] == 255 && salt[2] == 255 && salt[3] == 255 && salt[4] == 255) salt[5]++; if (salt[0] == 255 && salt[1] == 255 && salt[2] == 255 && salt[3] == 255) salt[4]++; if (salt[0] == 255 && salt[1] == 255 && salt[2] == 255) salt[3]++; if (salt[0] == 255 && salt[1] == 255) salt[2]++; if (salt[0] == 255) salt[1]++; salt[0]++; for (j = 0; j < 16; j++) { encbuf[(i*16)+j] = dsalted[j] ^ decbuf[(i*16)+j]; } //decbuf[i] = dsalted[i%16] ^ encbuf[i]; } totalBytes += got; if (totalBytes > fileSize) { got -= totalBytes - fileSize; totalBytes -= totalBytes - fileSize; } fwrite(encbuf, 1, numcrypts * 16, dfd); } } while (got > 0); fclose(dfd); fclose(fd); return 0; }
u8 * ccmp_encrypt(const u8 *tk, u8 *frame, size_t len, size_t hdrlen, u8 *qos, u8 *pn, int keyid, size_t *encrypted_len) { u8 aad[2 + 30], nonce[13]; size_t aad_len; u8 b[AES_BLOCK_SIZE], x[AES_BLOCK_SIZE], a[AES_BLOCK_SIZE]; void *aes; u8 *crypt, *pos, *ppos, *mpos; size_t plen, last; struct ieee80211_hdr *hdr; int i; if (len < hdrlen || hdrlen < 24) return NULL; plen = len - hdrlen; last = plen % AES_BLOCK_SIZE; crypt = os_malloc(hdrlen + 8 + plen + 8 + AES_BLOCK_SIZE); if (crypt == NULL) return NULL; os_memcpy(crypt, frame, hdrlen); hdr = (struct ieee80211_hdr *) crypt; hdr->frame_control |= host_to_le16(WLAN_FC_ISWEP); pos = crypt + hdrlen; *pos++ = pn[5]; /* PN0 */ *pos++ = pn[4]; /* PN1 */ *pos++ = 0x00; /* Rsvd */ *pos++ = 0x20 | (keyid << 6); *pos++ = pn[3]; /* PN2 */ *pos++ = pn[2]; /* PN3 */ *pos++ = pn[1]; /* PN4 */ *pos++ = pn[0]; /* PN5 */ aes = aes_encrypt_init(tk, 16); if (aes == NULL) { os_free(crypt); return NULL; } os_memset(aad, 0, sizeof(aad)); ccmp_aad_nonce(hdr, crypt + hdrlen, &aad[2], &aad_len, nonce); WPA_PUT_BE16(aad, aad_len); wpa_hexdump(MSG_EXCESSIVE, "CCMP AAD", &aad[2], aad_len); wpa_hexdump(MSG_EXCESSIVE, "CCMP nonce", nonce, 13); /* Authentication */ /* B_0: Flags | Nonce N | l(m) */ b[0] = 0x40 /* Adata */ | (3 /* M' */ << 3) | 1 /* L' */; os_memcpy(&b[1], nonce, 13); WPA_PUT_BE16(&b[14], plen); wpa_hexdump(MSG_EXCESSIVE, "CCMP B_0", b, AES_BLOCK_SIZE); aes_encrypt(aes, b, x); /* X_1 = E(K, B_0) */ wpa_hexdump(MSG_EXCESSIVE, "CCMP B_1", aad, AES_BLOCK_SIZE); xor_aes_block(aad, x); aes_encrypt(aes, aad, x); /* X_2 = E(K, X_1 XOR B_1) */ wpa_hexdump(MSG_EXCESSIVE, "CCMP B_2", &aad[AES_BLOCK_SIZE], AES_BLOCK_SIZE); xor_aes_block(&aad[AES_BLOCK_SIZE], x); aes_encrypt(aes, &aad[AES_BLOCK_SIZE], x); /* X_3 = E(K, X_2 XOR B_2) */ ppos = frame + hdrlen; for (i = 0; i < plen / AES_BLOCK_SIZE; i++) { /* X_i+1 = E(K, X_i XOR B_i) */ xor_aes_block(x, ppos); ppos += AES_BLOCK_SIZE; aes_encrypt(aes, x, x); } if (last) { /* XOR zero-padded last block */ for (i = 0; i < last; i++) x[i] ^= *ppos++; aes_encrypt(aes, x, x); } /* Encryption */ /* CCM: M=8 L=2, Adata=1, M' = (M-2)/2 = 3, L' = L-1 = 1 */ /* A_i = Flags | Nonce N | Counter i */ a[0] = 0x01; /* Flags = L' */ os_memcpy(&a[1], nonce, 13); ppos = crypt + hdrlen + 8; /* crypt = msg XOR (S_1 | S_2 | ... | S_n) */ mpos = frame + hdrlen; for (i = 1; i <= plen / AES_BLOCK_SIZE; i++) { WPA_PUT_BE16(&a[14], i); /* S_i = E(K, A_i) */ aes_encrypt(aes, a, ppos); xor_aes_block(ppos, mpos); ppos += AES_BLOCK_SIZE; mpos += AES_BLOCK_SIZE; } if (last) { WPA_PUT_BE16(&a[14], i); aes_encrypt(aes, a, ppos); /* XOR zero-padded last block */ for (i = 0; i < last; i++) *ppos++ ^= *mpos++; } wpa_hexdump(MSG_EXCESSIVE, "CCMP T", x, 8); /* U = T XOR S_0; S_0 = E(K, A_0) */ WPA_PUT_BE16(&a[14], 0); aes_encrypt(aes, a, b); for (i = 0; i < 8; i++) ppos[i] = x[i] ^ b[i]; wpa_hexdump(MSG_EXCESSIVE, "CCMP U", ppos, 8); wpa_hexdump(MSG_EXCESSIVE, "CCMP encrypted", crypt + hdrlen + 8, plen); aes_encrypt_deinit(aes); *encrypted_len = hdrlen + 8 + plen + 8; return crypt; }
u8 * ccmp_decrypt(const u8 *tk, const struct ieee80211_hdr *hdr, const u8 *data, size_t data_len, size_t *decrypted_len) { u8 aad[2 + 30], nonce[13]; size_t aad_len; u8 b[AES_BLOCK_SIZE], x[AES_BLOCK_SIZE], a[AES_BLOCK_SIZE]; void *aes; const u8 *m, *mpos, *mic; size_t mlen, last; int i; u8 *plain, *ppos; u8 t[8]; if (data_len < 8 + 8) return NULL; plain = os_malloc(data_len + AES_BLOCK_SIZE); if (plain == NULL) return NULL; aes = aes_encrypt_init(tk, 16); if (aes == NULL) { os_free(plain); return NULL; } m = data + 8; mlen = data_len - 8 - 8; last = mlen % AES_BLOCK_SIZE; os_memset(aad, 0, sizeof(aad)); ccmp_aad_nonce(hdr, data, &aad[2], &aad_len, nonce); WPA_PUT_BE16(aad, aad_len); wpa_hexdump(MSG_EXCESSIVE, "CCMP AAD", &aad[2], aad_len); wpa_hexdump(MSG_EXCESSIVE, "CCMP nonce", nonce, 13); /* CCM: M=8 L=2, Adata=1, M' = (M-2)/2 = 3, L' = L-1 = 1 */ /* A_i = Flags | Nonce N | Counter i */ a[0] = 0x01; /* Flags = L' */ os_memcpy(&a[1], nonce, 13); /* Decryption */ mic = data + data_len - 8; wpa_hexdump(MSG_EXCESSIVE, "CCMP U", mic, 8); /* U = T XOR S_0; S_0 = E(K, A_0) */ WPA_PUT_BE16(&a[14], 0); aes_encrypt(aes, a, x); for (i = 0; i < 8; i++) t[i] = mic[i] ^ x[i]; wpa_hexdump(MSG_EXCESSIVE, "CCMP T", t, 8); /* plaintext = msg XOR (S_1 | S_2 | ... | S_n) */ ppos = plain; mpos = m; for (i = 1; i <= mlen / AES_BLOCK_SIZE; i++) { WPA_PUT_BE16(&a[14], i); /* S_i = E(K, A_i) */ aes_encrypt(aes, a, ppos); xor_aes_block(ppos, mpos); ppos += AES_BLOCK_SIZE; mpos += AES_BLOCK_SIZE; } if (last) { WPA_PUT_BE16(&a[14], i); aes_encrypt(aes, a, ppos); /* XOR zero-padded last block */ for (i = 0; i < last; i++) *ppos++ ^= *mpos++; } wpa_hexdump(MSG_EXCESSIVE, "CCMP decrypted", plain, mlen); /* Authentication */ /* B_0: Flags | Nonce N | l(m) */ b[0] = 0x40 /* Adata */ | (3 /* M' */ << 3) | 1 /* L' */; os_memcpy(&b[1], nonce, 13); WPA_PUT_BE16(&b[14], mlen); wpa_hexdump(MSG_EXCESSIVE, "CCMP B_0", b, AES_BLOCK_SIZE); aes_encrypt(aes, b, x); /* X_1 = E(K, B_0) */ wpa_hexdump(MSG_EXCESSIVE, "CCMP B_1", aad, AES_BLOCK_SIZE); xor_aes_block(aad, x); aes_encrypt(aes, aad, x); /* X_2 = E(K, X_1 XOR B_1) */ wpa_hexdump(MSG_EXCESSIVE, "CCMP B_2", &aad[AES_BLOCK_SIZE], AES_BLOCK_SIZE); xor_aes_block(&aad[AES_BLOCK_SIZE], x); aes_encrypt(aes, &aad[AES_BLOCK_SIZE], x); /* X_3 = E(K, X_2 XOR B_2) */ ppos = plain; for (i = 0; i < mlen / AES_BLOCK_SIZE; i++) { /* X_i+1 = E(K, X_i XOR B_i) */ xor_aes_block(x, ppos); ppos += AES_BLOCK_SIZE; aes_encrypt(aes, x, x); } if (last) { /* XOR zero-padded last block */ for (i = 0; i < last; i++) x[i] ^= *ppos++; aes_encrypt(aes, x, x); } aes_encrypt_deinit(aes); if (os_memcmp(x, t, 8) != 0) { u16 seq_ctrl = le_to_host16(hdr->seq_ctrl); wpa_printf(MSG_INFO, "Invalid CCMP MIC in frame: A1=" MACSTR " A2=" MACSTR " A3=" MACSTR " seq=%u frag=%u", MAC2STR(hdr->addr1), MAC2STR(hdr->addr2), MAC2STR(hdr->addr3), WLAN_GET_SEQ_SEQ(seq_ctrl), WLAN_GET_SEQ_FRAG(seq_ctrl)); wpa_hexdump(MSG_DEBUG, "CCMP decrypted", plain, mlen); os_free(plain); return NULL; } *decrypted_len = mlen; return plain; }
// See aes128_key_wrap_unwrap.h for documentation on this function. void do_aes128_key_wrap(const uint8_t plaintext[], uint8_t wrapped_ciphertext[], uint32_t expanded_kek[]) { uint32_t i, j; // loop counters uint8_t in[16]; // 128-bit temporary plaintext input vector // step 1: initialize the byte-sized data variables // set A = IV // for i = 1 to n // R[i] = P[i] a[0] = iv[0]; a[1] = iv[1]; a[2] = iv[2]; a[3] = iv[3]; a[4] = iv[4]; a[5] = iv[5]; a[6] = iv[6]; a[7] = iv[7]; for (i = 1; i <= N; i++) { r[8 * i + 0] = plaintext[8 * (i - 1) + 0]; r[8 * i + 1] = plaintext[8 * (i - 1) + 1]; r[8 * i + 2] = plaintext[8 * (i - 1) + 2]; r[8 * i + 3] = plaintext[8 * (i - 1) + 3]; r[8 * i + 4] = plaintext[8 * (i - 1) + 4]; r[8 * i + 5] = plaintext[8 * (i - 1) + 5]; r[8 * i + 6] = plaintext[8 * (i - 1) + 6]; r[8 * i + 7] = plaintext[8 * (i - 1) + 7]; } // step 2: calculate intermediate values // for j = 0 to 5 // for i = 1 to n // B = AES(K, A | R[i]) // A = MSB(64, B) ^ (n*j)+i // R[i] = LSB(64, B) for (j = 0; j <= 5; j++) { for (i = 1; i <= N; i++) { in[0] = a[0]; in[1] = a[1]; in[2] = a[2]; in[3] = a[3]; in[4] = a[4]; in[5] = a[5]; in[6] = a[6]; in[7] = a[7]; in[8] = r[8 * i + 0]; in[9] = r[8 * i + 1]; in[10] = r[8 * i + 2]; in[11] = r[8 * i + 3]; in[12] = r[8 * i + 4]; in[13] = r[8 * i + 5]; in[14] = r[8 * i + 6]; in[15] = r[8 * i + 7]; #if defined BOOTLOADER_HOST Cipher(in, expanded_kek, 10, in); // perform aes128 encryption #else aes_encrypt((uint32_t *)in, expanded_kek, (uint32_t *)in); #endif // BOOTLOADER_HOST a[0] = in[0]; a[1] = in[1]; a[2] = in[2]; a[3] = in[3]; a[4] = in[4]; a[5] = in[5]; a[6] = in[6]; a[7] = in[7] ^ ((N * j) + i); r[8 * i + 0] = in[8]; r[8 * i + 1] = in[9]; r[8 * i + 2] = in[10]; r[8 * i + 3] = in[11]; r[8 * i + 4] = in[12]; r[8 * i + 5] = in[13]; r[8 * i + 6] = in[14]; r[8 * i + 7] = in[15]; } // end for (i) } // end for (j) // step 3: output the results // set C[0] = A // for i = 1 to n // C[i] = R[i] wrapped_ciphertext[0] = a[0]; wrapped_ciphertext[1] = a[1]; wrapped_ciphertext[2] = a[2]; wrapped_ciphertext[3] = a[3]; wrapped_ciphertext[4] = a[4]; wrapped_ciphertext[5] = a[5]; wrapped_ciphertext[6] = a[6]; wrapped_ciphertext[7] = a[7]; for (i = 1; i <= N; i++) { wrapped_ciphertext[8 * i + 0] = r[8 * i + 0]; wrapped_ciphertext[8 * i + 1] = r[8 * i + 1]; wrapped_ciphertext[8 * i + 2] = r[8 * i + 2]; wrapped_ciphertext[8 * i + 3] = r[8 * i + 3]; wrapped_ciphertext[8 * i + 4] = r[8 * i + 4]; wrapped_ciphertext[8 * i + 5] = r[8 * i + 5]; wrapped_ciphertext[8 * i + 6] = r[8 * i + 6]; wrapped_ciphertext[8 * i + 7] = r[8 * i + 7]; } }
/* we don't use additional input */ int drbg_aes_generate(struct drbg_aes_ctx *ctx, unsigned length, uint8_t * dst, unsigned add_size, const uint8_t *add) { uint8_t tmp[AES_BLOCK_SIZE]; uint8_t seed[DRBG_AES_SEED_SIZE]; unsigned left; if (ctx->seeded == 0) return 0; if (add_size > 0) { if (add_size > DRBG_AES_SEED_SIZE) return 0; memcpy(seed, add, add_size); if (add_size != DRBG_AES_SEED_SIZE) memset(&seed[add_size], 0, DRBG_AES_SEED_SIZE - add_size); drbg_aes_update(ctx, seed); } else { memset(seed, 0, DRBG_AES_SEED_SIZE); } /* Throw the first block generated. FIPS 140-2 requirement (see * the continuous random number generator test in 4.9.2) */ if (ctx->prev_block_present == 0) { INCREMENT(sizeof(ctx->v), ctx->v); aes_encrypt(&ctx->key, AES_BLOCK_SIZE, ctx->prev_block, ctx->v); ctx->prev_block_present = 1; } /* Perform the actual encryption */ for (left = length; left >= AES_BLOCK_SIZE; left -= AES_BLOCK_SIZE, dst += AES_BLOCK_SIZE) { INCREMENT(sizeof(ctx->v), ctx->v); aes_encrypt(&ctx->key, AES_BLOCK_SIZE, dst, ctx->v); /* if detected loop */ if (memcmp(dst, ctx->prev_block, AES_BLOCK_SIZE) == 0) { _gnutls_switch_lib_state(LIB_STATE_ERROR); return 0; } memcpy(ctx->prev_block, dst, AES_BLOCK_SIZE); } if (left > 0) { /* partial fill */ INCREMENT(sizeof(ctx->v), ctx->v); aes_encrypt(&ctx->key, AES_BLOCK_SIZE, tmp, ctx->v); /* if detected loop */ if (memcmp(tmp, ctx->prev_block, AES_BLOCK_SIZE) == 0) { _gnutls_switch_lib_state(LIB_STATE_ERROR); return 0; } memcpy(ctx->prev_block, tmp, AES_BLOCK_SIZE); memcpy(dst, tmp, left); } if (ctx->reseed_counter > DRBG_AES_RESEED_TIME) return 0; ctx->reseed_counter++; drbg_aes_update(ctx, seed); return 1; }
void aes_key_wrap(UWORD8 *text, UWORD8 *key, UWORD32 n) { UWORD32 t = 0; UWORD32 i = 0; UWORD32 j = 0; UWORD32 k = 0; UWORD32 c = 0; UWORD32 idx = 0; UWORD16 curr_idx = 0; UWORD8 *A = 0; //[8]; UWORD8 *B = 0; //[16]; UWORD8 *R[8] = {0}; //[8][100]; UWORD8 *Rbuff = NULL; aes_context_t ctx = {{0},}; /* Save the current scratch memory index */ curr_idx = get_scratch_mem_idx(); /* Allocate scratch memory for the temporary variables */ A = (UWORD8 *)scratch_mem_alloc(8); if(A == NULL) { /* Restore the saved scratch memory index */ restore_scratch_mem_idx(curr_idx); return; } B = (UWORD8 *)scratch_mem_alloc(16); if(B == NULL) { /* Restore the saved scratch memory index */ restore_scratch_mem_idx(curr_idx); return; } Rbuff = (UWORD8 *)scratch_mem_alloc(8*100); if(Rbuff == NULL) { /* Restore the saved scratch memory index */ restore_scratch_mem_idx(curr_idx); return; } for(i = 0; i < 8; i ++) { R[i] = Rbuff + i*100; } /* AES initialization - Key scheduling */ ctx.nrounds = NUM_ROUNDS; aes_setup(&ctx, 16, key); /* 1) Initialize variables */ /* Set A = IV */ /* For i = 1 to n */ /* R[i] = P[i] */ for(k = 0; k < 8; k++) A[k] = g_iv[k]; for(i = 0, idx = 0; i < n; i++) for(k = 0; k < 8; k++) R[k][i] = text[idx++]; /* 2) Compute intermediate values */ /* For j = 5 to 0 */ /* For i = 1 to n */ /* B = AES(K, A | R[i]) */ /* A = MSB(64, B) ^ t where t = (n*j)+i */ /* R[i] = LSB(64, B) */ for(j = 0; j <= 5; j++) { for(i = 0; i < n; i++) { UWORD8 temp128[16]; /* A | R[i] */ for(k = 0; k < 8; k ++) temp128[k] = A[k]; for(k = 8, c = 0; k < 16 && c < 8; k++, c++) temp128[k] = R[c][i]; /* B = AES(K, A | R[i] */ aes_encrypt(&ctx, temp128, B); /* MSB(64, B) */ for(k = 0; k < 8; k++) A[k] = B[k]; /* t does not need to be greater than 32 bits for allowed data */ /* lengths. Verify this. */ t = (n * j) + (i + 1); /* A = MSB(64, B) ^ t where t = (n*j)+i */ for(k = 0; k < 4; k ++) { UWORD8 ptr = (UWORD8)(t >> (k << 3)); A[7 - k] = A[7 - k] ^ ptr; } /* R[i] = LSB(64, B) */ for(k = 0; k < 8; k++) R[k][i] = B[k + 8]; } } /* 3) Output Results */ /* C[0] = A */ /* For i = 1 to n */ /* C[i] = R[i] */ for(k = 0; k < 8; k ++) text[k] = A[k]; idx = 8; for(i = 0; i < n; i++) for(k = 0; k < 8; k ++) text[idx++] = R[k][i]; /* Restore the saved scratch memory index */ restore_scratch_mem_idx(curr_idx); }
void* images_inject_img3(const void* img3Data, const void* newData, size_t newDataLen) { uint8_t IVKey[16 + (256 / 8)]; uint8_t* IV = IVKey; uint8_t* Key = &IVKey[16]; uint32_t dataOffset = 0; uint32_t dataLength = 0; uint32_t kbagOffset = 0; uint32_t kbagLength = 0; uint32_t offset = (uint32_t)(img3Data + sizeof(AppleImg3RootHeader)); size_t contentsLength = ((AppleImg3RootHeader*) img3Data)->base.dataSize; while((offset - (uint32_t)(img3Data + sizeof(AppleImg3RootHeader))) < contentsLength) { AppleImg3Header* header = (AppleImg3Header*) offset; if(header->magic == IMG3_DATA_MAGIC) { dataOffset = offset + sizeof(AppleImg3Header); dataLength = header->size; } if(header->magic == IMG3_KBAG_MAGIC) { kbagOffset = offset + sizeof(AppleImg3Header); kbagLength = header->dataSize; } offset += header->size; } AppleImg3KBAGHeader* kbag = (AppleImg3KBAGHeader*) kbagOffset; if(kbag != 0 && kbag->key_modifier == 1) { memcpy(IVKey, (void*)(kbagOffset + sizeof(AppleImg3KBAGHeader)), 16 + (kbag->key_bits / 8)); aes_decrypt(IVKey, 16 + (kbag->key_bits / 8), AESGID, NULL, NULL); } void* newImg3 = malloc(sizeof(AppleImg3RootHeader)); memcpy(newImg3, img3Data, sizeof(AppleImg3RootHeader)); AppleImg3RootHeader* rootHeader = (AppleImg3RootHeader*) newImg3; rootHeader->base.dataSize = rootHeader->base.dataSize - dataLength + (((newDataLen + 3)/4)*4) + sizeof(AppleImg3Header); rootHeader->base.size = (((rootHeader->base.dataSize + sizeof(AppleImg3RootHeader)) + 0x3F)/0x40)*0x40; newImg3 = realloc(newImg3, rootHeader->base.size); rootHeader = (AppleImg3RootHeader*) newImg3; void* cursor = newImg3 + sizeof(AppleImg3RootHeader); memset(cursor, 0, rootHeader->base.size - sizeof(AppleImg3RootHeader)); offset = (uint32_t)(img3Data + sizeof(AppleImg3RootHeader)); while((offset - (uint32_t)(img3Data + sizeof(AppleImg3RootHeader))) < contentsLength) { AppleImg3Header* header = (AppleImg3Header*) offset; if(header->magic == IMG3_DATA_MAGIC) { memcpy(cursor, (void*) offset, sizeof(AppleImg3Header)); AppleImg3Header* newHeader = (AppleImg3Header*) cursor; newHeader->dataSize = newDataLen; newHeader->size = sizeof(AppleImg3Header) + (((newHeader->dataSize + 3)/4)*4); memcpy(cursor + sizeof(AppleImg3Header), newData, newDataLen); if(kbag != 0) { aes_encrypt(cursor + sizeof(AppleImg3Header), (newDataLen / 16) * 16, AESCustom, Key, IV); } cursor += newHeader->size; } else { if(header->magic == IMG3_SHSH_MAGIC) { rootHeader->extra.shshOffset = (uint32_t)cursor - (uint32_t)newImg3 - sizeof(AppleImg3RootHeader); } memcpy(cursor, (void*) offset, header->size); cursor += header->size; } offset += header->size; } return newImg3; }
void CConfig::SaveConfig() { //保存配置到文件中去 char pszFullPath[MAX_STRING]; char pszFilename[MAX_STRING]=CONFIGNAME; char szTemp[MAX_STRING]; GetFullPathToFile(pszFullPath, pszFilename); //LOAD_CONFIG_INT_NAME_VAR("HeartInterval", m_iHeartInterval, 30); #define WRITE_CONFIG_INT_NAME_VAR(n, v) {sprintf(szTemp,"%d",v);WritePrivateProfileString("config", n, szTemp, pszFullPath);} WRITE_CONFIG_INT_NAME_VAR("Timeout", m_iTimeout); WRITE_CONFIG_INT_NAME_VAR("HeartInterval", m_iHeartInterval); #define WRITE_CONFIG_BOOL_NAME_VAR(n, v) WritePrivateProfileString("config", n, v?"1":"0", pszFullPath); WRITE_CONFIG_BOOL_NAME_VAR("RememberPWD", m_bRememberPWD); WRITE_CONFIG_BOOL_NAME_VAR("WebAuth", m_bWebAuth); WRITE_CONFIG_BOOL_NAME_VAR("WebLogout", m_bWebLogout); WRITE_CONFIG_BOOL_NAME_VAR("Autorun", m_bAutorun); WRITE_CONFIG_BOOL_NAME_VAR("Autologon", m_bAutologon); WRITE_CONFIG_BOOL_NAME_VAR("ShowBubble", m_bShowBubble); WRITE_CONFIG_BOOL_NAME_VAR("EnableWebAccount", m_bEnableWebAccount); WRITE_CONFIG_BOOL_NAME_VAR("TimingReauth", m_bTimingReauth); WRITE_CONFIG_BOOL_NAME_VAR("AutoUpdate", m_bAutoUpdate); WRITE_CONFIG_BOOL_NAME_VAR("AutoFilter", m_bAutoFilter); WRITE_CONFIG_BOOL_NAME_VAR("Debug", m_bDebug); WRITE_CONFIG_BOOL_NAME_VAR("DHCP", m_bDHCP); WRITE_CONFIG_BOOL_NAME_VAR("HttpHeart", m_bHttpHeart); WRITE_CONFIG_BOOL_NAME_VAR("Ping", m_Ping); WRITE_CONFIG_BOOL_NAME_VAR("FaillReauth", m_Reauth); WRITE_CONFIG_BOOL_NAME_VAR("UEIP", m_UEIP); WRITE_CONFIG_BOOL_NAME_VAR("ChansePWD", m_Changepwd); WRITE_CONFIG_BOOL_NAME_VAR("SlienceUp", m_SlienceUp); WRITE_CONFIG_BOOL_NAME_VAR("ZTEAuth", m_ZTEAuth); WRITE_CONFIG_BOOL_NAME_VAR("WebAuth", m_WebAuth); WRITE_CONFIG_BOOL_NAME_VAR("TYAuth", m_WebAuth2); WRITE_CONFIG_BOOL_NAME_VAR("CYClient", m_CYClient); WRITE_CONFIG_BOOL_NAME_VAR("AutoBas", m_AutoBas); HKEY hRun; LONG kResult = ::RegOpenKeyEx( HKEY_LOCAL_MACHINE, _T("Software\\Microsoft\\Windows\\CurrentVersion\\Run"), NULL ,KEY_ALL_ACCESS ,&hRun); if (m_bAutorun == TRUE) //设置开机自动启动 { char szTemp[MAX_STRING],pjPath[MAX_STRING]; DWORD regsz=REG_SZ; DWORD iPathLen; strcpy(pszFilename,AfxGetApp()->m_pszExeName); strcat(pszFilename,".exe"); GetFullPathToFile(szTemp,pszFilename); sprintf(pjPath,"\"%s\"",szTemp); iPathLen = (strlen(szTemp) +1) *sizeof(char); kResult = ::RegQueryValueEx(hRun, _T("zte"), NULL, ®sz, (BYTE *)szTemp, &iPathLen); if (kResult!=ERROR_SUCCESS || strcmp(szTemp,pjPath)!=0) { iPathLen = (strlen(pjPath) +1) *sizeof(char); kResult = ::RegSetValueEx(hRun, _T("zte"), NULL, REG_SZ, (BYTE *)pjPath, iPathLen); } } else { RegDeleteValue(hRun, _T("zte")); } ::RegCloseKey(hRun); #define WRITE_CONFIG_STRING_NAME_VAR(n, v) WritePrivateProfileString("config", n, v, pszFullPath); if (edubas.GetLength() != 0) m_csEduBas = edubas; WRITE_CONFIG_STRING_NAME_VAR("HeartUrl", m_csHeartUrl); WRITE_CONFIG_STRING_NAME_VAR("HeartCookies", m_csHeartCookies); WRITE_CONFIG_STRING_NAME_VAR("ZTEServer",Config.m_csZTEServer); WRITE_CONFIG_STRING_NAME_VAR("ReauthTime", m_csReauthTime); WRITE_CONFIG_STRING_NAME_VAR("netcard", m_csNetCard); WRITE_CONFIG_STRING_NAME_VAR("WebAuthUrl", m_csWebAuthUrl); WRITE_CONFIG_STRING_NAME_VAR("WebLogoutUrl", m_csWebLogoutUrl); WRITE_CONFIG_STRING_NAME_VAR("Version", STR_Version); WRITE_CONFIG_STRING_NAME_VAR("LastUser", m_csLastUser); WRITE_CONFIG_STRING_NAME_VAR("WebUsername", aes_encrypt((LPCTSTR)m_csWebUsername)); WRITE_CONFIG_STRING_NAME_VAR("WebPassword", aes_encrypt((LPCTSTR)m_csWebPassword)); WRITE_CONFIG_STRING_NAME_VAR("BannerUrl", banner_url); WRITE_CONFIG_STRING_NAME_VAR("EduBas", m_csEduBas); #define WRITE_USER(u, p) WritePrivateProfileString("users", u, aes_encrypt((LPCTSTR)p), pszFullPath); //读取所有账号密码参数 CString user,pass; POSITION p = Config.m_UserInfo.GetStartPosition(); while(p != NULL) { Config.m_UserInfo.GetNextAssoc(p, user, pass); if(user.GetLength() > 0) WRITE_USER(user, pass); } }
int main( ) { size_t len = 536870912; int align = 4096; scif_epd_t endpoint; struct scif_portID portid; int ret; uint8_t *in_key = malloc(16 * sizeof(uint8_t)); struct crypto_tfm *tfm = malloc( sizeof(struct crypto_tfm) + sizeof(struct crypto_aes_ctx) ); struct crypto_aes_ctx *ctx = crypto_tfm_ctx(tfm); ctx->key_length = AES_KEYSIZE_256; crypto_aes_set_key(tfm, in_key, AES_KEYSIZE_256); endpoint = scif_open( ); if( endpoint == SCIF_OPEN_FAILED ) { printf("scif open failed\n"); return 1; } ret = scif_bind(endpoint, 23955); if(ret==-1) { printf("scif_bind failed"); return 1; } portid.node = 0; portid.port = 23968; ret = scif_connect(endpoint, &portid); for( int attempt = 0; ret == -1 && attempt < 10; ++attempt ) { sleep(1); ret = scif_connect(endpoint, &portid); } if (ret==-1) { printf("scif_connect failed\n"); return 1; } void *ptr; ret = posix_memalign((void**)&ptr, align, len); if (ret) { printf("Allocating memory failed\n"); return 1; } memset(ptr, 0, len); if( SCIF_REGISTER_FAILED == scif_register(endpoint, ptr, len, (long)ptr, SCIF_PROT_READ | SCIF_PROT_WRITE, SCIF_MAP_FIXED ) ) { printf("scif_register of ptr failed due to: %s\n", strerror(errno)); return 1; } void *tempbuffer; ret = posix_memalign((void**)&tempbuffer, align, len); if (ret) { printf("Allocating tempbuffer failed\n"); return 1; } if( SCIF_REGISTER_FAILED == scif_register(endpoint, tempbuffer, len, (long)tempbuffer, SCIF_PROT_READ | SCIF_PROT_WRITE, SCIF_MAP_FIXED ) ) { printf("scif_register of temp failed due to: %s\n", strerror(errno)); return 1; } void *outbuffer; ret = posix_memalign((void**)&outbuffer, align, len); if (ret) { printf("Allocating outbuffer failed %s\n", strerror(errno)); return 1; } if( SCIF_REGISTER_FAILED == scif_register(endpoint, outbuffer, len, (long)outbuffer, SCIF_PROT_READ | SCIF_PROT_WRITE, SCIF_MAP_FIXED ) ) { printf("scif_register of outbuffer failed due to: %s\n", strerror(errno)); return 1; } void *remote_ptr; void *return_ptr; ret = scif_recv(endpoint, &remote_ptr, sizeof(void*), SCIF_RECV_BLOCK); if (ret==-1) { printf("scif_recv failed due to: %s\n", strerror(errno)); return 1; } ret = scif_recv(endpoint, &return_ptr, sizeof(void*), SCIF_RECV_BLOCK); if (ret==-1) { printf("scif_recv failed due to: %s\n", strerror(errno)); return 1; } struct timespec start_enc, stop_enc; clock_gettime(CLOCK_REALTIME, &start_enc); if (scif_readfrom(endpoint, (long)ptr, len, (long)remote_ptr, SCIF_RMA_SYNC)) { printf("scif_readfrom failed due to: %s\n", strerror(errno)); return 1; } #pragma omp parallel for for (int k = 0; k<len; k+=16) { aes_encrypt(tfm, (uint8_t*)&tempbuffer[k], (uint8_t*)&ptr[k]); } if (scif_writeto(endpoint, (long)tempbuffer, len, (long)return_ptr, SCIF_RMA_SYNC)) { printf("scif_writeto failed due to: %s\n", strerror(errno)); return 1; } clock_gettime(CLOCK_REALTIME, &stop_enc); double time_enc = (stop_enc.tv_sec - start_enc.tv_sec) + ( stop_enc.tv_nsec - start_enc.tv_nsec) / NANOSECONDS; double result0 = len/time_enc/1048576; printf("%1f,", result0); struct timespec start_for, stop_for; clock_gettime(CLOCK_REALTIME, &start_for); if (scif_readfrom(endpoint, (long)ptr, len, (long)remote_ptr, SCIF_RMA_SYNC)) { printf("scif_readfrom failed due to: %s\n", strerror(errno)); return 1; } #pragma omp parallel for for (int k=0; k<len; k+=16) { aes_decrypt(tfm, (uint8_t*)&outbuffer[k], (uint8_t*)&tempbuffer[k]); } if (scif_writeto(endpoint, (long)outbuffer, len, (long)return_ptr, SCIF_RMA_SYNC)) { printf("scif_writeto failed due to: %s\n", strerror(errno)); return 1; } clock_gettime(CLOCK_REALTIME, &stop_for); double time_for = (stop_for.tv_sec - start_for.tv_sec) + ( stop_for.tv_nsec - start_for.tv_nsec) / NANOSECONDS; double result = 536870912/time_for/1048576; printf("%1f \n", result); ret = scif_send(endpoint, &ptr, sizeof(long), SCIF_SEND_BLOCK); if (ret==-1) { printf("scif_send failed due to: %s\n", strerror(errno)); return 1; } ret = scif_unregister(endpoint, (off_t)ptr, len ); if(ret==-1 && errno!=ENOTCONN ) { printf("scif_unregister failed %s\n", strerror(errno)); return 1; } scif_close(endpoint); }
void cmd_aes(int argc, char** argv) { AESKeyType keyType; uint8_t* data = NULL; uint8_t* key = NULL; uint8_t* iv = NULL; int dataLength; int keyLength; int ivLength; if(argc < 4) { bufferPrintf("Usage: %s <enc/dec> <gid/uid/key> [data] [iv]\r\n", argv[0]); return; } if(strcmp(argv[2], "gid") == 0) { keyType = AESGID; } else if(strcmp(argv[2], "uid") == 0) { keyType = AESUID; } else { hexToBytes(argv[2], &key, &keyLength); keyType = AESCustom; } hexToBytes(argv[3], &data, &dataLength); if(argc > 4) { hexToBytes(argv[4], &iv, &ivLength); } if(strcmp(argv[1], "enc") == 0) { aes_encrypt(data, dataLength, keyType, key, iv); bytesToHex(data, dataLength); bufferPrintf("\r\n"); } else if(strcmp(argv[1], "dec") == 0) { aes_decrypt(data, dataLength, keyType, key, iv); bytesToHex(data, dataLength); bufferPrintf("\r\n"); } else { bufferPrintf("Usage: %s <enc/dec> <GID/UID/key> [data] [iv]\r\n", argv[0]); } if(data) free(data); if(iv) free(iv); if(key) free(key); }
void aes_128_encrypt(unsigned char blk[BLK_SIZE], unsigned long expanded_key[EXPANDED_KEY_SIZE]){ unsigned char tmp_blk[BLK_SIZE]; memcpy(tmp_blk, blk, BLK_SIZE); aes_encrypt(tmp_blk, blk, expanded_key, 128); }
/* Key and message values given by FIPS-192 Appendix B. */ void test_lib() { unsigned char out[16]; unsigned char iout[16]; /* Reference message subject to encryption. */ unsigned char msg[] = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff }; /* Encryption/decryption keys. */ unsigned char key128[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f }; unsigned char key192[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17 }; unsigned char key256[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f }; /* Reference encrypted msg output for 128, 192 and 256 bit keys. */ unsigned char out128[] = { 0x69, 0xc4, 0xe0, 0xd8, 0x6a, 0x7b, 0x04, 0x30, 0xd8, 0xcd, 0xb7, 0x80, 0x70, 0xb4, 0xc5, 0x5a }; unsigned char out192[] = { 0xdd, 0xa9, 0x7c, 0xa4, 0x86, 0x4c, 0xdf, 0xe0, 0x6e, 0xaf, 0x70, 0xa0, 0xec, 0x0d, 0x71, 0x91 }; unsigned char out256[] = { 0x8e, 0xa2, 0xb7, 0xca, 0x51, 0x67, 0x45, 0xbf, 0xea, 0xfc, 0x49, 0x90, 0x4b, 0x49, 0x60, 0x89 }; unsigned char *key[] = { key128, key192, key256 }; unsigned char *encmsg[] = { out128, out192, out256 }; char *key_str[] = { "key128", "key192", "key256" }; unsigned int key_type[] = { AES_KEY_128, AES_KEY_192, AES_KEY_256 }; struct aes_context *ctx; int i; for (i = 0; i < 3; i++) { printf("\n"); printf("State: %s\n", key_str[i]); ctx = aes_context_new(); aes_set_key(ctx, key[i], key_type[i]); printf("CIPHER (ENCRYPT): "); aes_encrypt(ctx, msg, out); if (memcmp(out, encmsg[i], sizeof(msg)) != 0) { fprintf(stderr, "Warning!!! encrypt test failed for %s\n", key_str[i]); goto next; } else printf("OK\n"); printf("INVERSE CIPHER (DECRYPT): "); aes_decrypt(ctx, out, iout); if (memcmp(msg, iout, sizeof(msg)) != 0) fprintf(stderr, "Warning!!! decrypt test failed for %s\n", key_str[i]); else printf("OK\n"); next: aes_context_free(&ctx); } }