int main (int argc, char *argv[]) { Card deck[DECK_SIZE]; Card starting_deck[DECK_SIZE]; char in_message[MAX_MESSAGE_LENGTH]; char out_message[MAX_MESSAGE_LENGTH]; int mode = 0; //encrypt = 0, decrypt = 1 if (argc != 1) { printf("usage: SolitareEncryption1\n"); printf("SEKEY environment variable must be set to the key value\n"); exit(1); } init_deck(starting_deck); while (1) { //set the deck to the key starting position memcpy(deck, starting_deck, sizeof(Card) * DECK_SIZE); print_deck(deck); if (!mode) { printf("Enter message to be encrypted (type '/help' for help):\n"); } else { printf("Enter message to be decrypted (type '/help' for help):\n"); } fflush(stdout); if (fgets(in_message, MAX_MESSAGE_LENGTH, stdin) == NULL) { printf("fgets failure\n"); exit(1); } //get rid of the newline from fgets int i; for (i = 0; in_message[i] != '\0'; i++) { if (in_message[i] == '\n') { in_message[i] = '\0'; break; } } if (!strcmp(in_message, "/quit")) { break; } else if (!strcmp(in_message, "/encrypt")) { mode = 0; printf("Encryption mode\n"); } else if (!strcmp(in_message, "/decrypt")) { mode = 1; printf("Decryption mode\n"); } else if (!strcmp(in_message, "/help")) { printf("/encrypt: switch to encryption mode\n" "/decrypt: switch to decryption mode\n" "/quit: quit program\n"); } else { if (!mode) { printf("Unencrypted: %s\n", in_message); printf("Encrypted: %s\n", encrypt(deck, in_message, out_message)); } else { printf("Encrypted: %s\n", in_message); printf("Decrypted: %s\n", decrypt(deck, in_message, out_message)); } } } return 0; }
static void process_discovery(uint8_t sock, Remote_Info *remote_info, WIZnet_Header *wiznet_header) { uint16_t len; uint8_t buffer[sizeof(WIZnet_Header) + sizeof(WIZnet_Discovery_Mixed_Condition)]; // header + most biggest structure uint32_t ptr; WIZnet_Discovery_Reply reply; S2E_Packet *s2e_packet = get_S2E_Packet_pointer(); uint8_t ip[4]; uint16_t port; getsockopt(sock, SO_REMAINSIZE, &len); if(len != wiznet_header->length) return; switch(wiznet_header->op_code[0]) { case DISCOVERY_ALL: break; case DISCOVERY_PRODUCT_CODE: { WIZnet_Discovery_Product_Code product_code; recvfrom(sock, (uint8_t *)&product_code, sizeof(WIZnet_Discovery_Product_Code), ip, &port); if((wiznet_header->valid & 0x80)) decrypt((wiznet_header->valid & 0x7F), (uint8_t *)&product_code, len); if(memcmp(product_code.product_code, s2e_packet->module_type, 3)) return; break; } case DISCOVERY_MAC_ADDRESS: { WIZnet_Discovery_MAC_Address mac_address; recvfrom(sock, (uint8_t *)&mac_address, sizeof(WIZnet_Discovery_MAC_Address), ip, &port); if((wiznet_header->valid & 0x80)) decrypt((wiznet_header->valid & 0x7F), (uint8_t *)&mac_address, len); if( mac_address.start_mac_address[0] > s2e_packet->network_info_common.mac[0] || mac_address.start_mac_address[1] > s2e_packet->network_info_common.mac[1] || mac_address.start_mac_address[2] > s2e_packet->network_info_common.mac[2] || mac_address.start_mac_address[3] > s2e_packet->network_info_common.mac[3] || mac_address.start_mac_address[4] > s2e_packet->network_info_common.mac[4] || mac_address.start_mac_address[5] > s2e_packet->network_info_common.mac[5]) return; if( mac_address.end_mac_address[0] < s2e_packet->network_info_common.mac[0] || mac_address.end_mac_address[1] < s2e_packet->network_info_common.mac[1] || mac_address.end_mac_address[2] < s2e_packet->network_info_common.mac[2] || mac_address.end_mac_address[3] < s2e_packet->network_info_common.mac[3] || mac_address.end_mac_address[4] < s2e_packet->network_info_common.mac[4] || mac_address.end_mac_address[5] < s2e_packet->network_info_common.mac[5]) return; break; } case DISCOVERY_ALIAS: { WIZnet_Discovery_Alias alias; recvfrom(sock, (uint8_t *)&alias, sizeof(WIZnet_Discovery_Alias), ip, &port); if((wiznet_header->valid & 0x80)) decrypt((wiznet_header->valid & 0x7F), (uint8_t *)&alias, len); if(memcmp(alias.alias, s2e_packet->module_name, strlen((char *)alias.alias))) return; break; } case DISCOVERY_MIXED_COND: { WIZnet_Discovery_Mixed_Condition mixed_condition; recvfrom(sock, (uint8_t *)&mixed_condition, sizeof(WIZnet_Discovery_Mixed_Condition), ip, &port); if((wiznet_header->valid & 0x80)) decrypt((wiznet_header->valid & 0x7F), (uint8_t *)&mixed_condition, len); break; } default: return; } // reply wiznet_header->length = sizeof(WIZnet_Discovery_Reply); wiznet_header->op_code[1] = WIZNET_REPLY; memcpy(reply.product_code, s2e_packet->module_type, 3); memcpy(reply.fw_version, s2e_packet->fw_ver, 3); memcpy(reply.mac_address, s2e_packet->network_info_common.mac, 6); if((wiznet_header->valid & 0x80)) encrypt((wiznet_header->valid & 0x7F), (uint8_t *)&reply, sizeof(WIZnet_Discovery_Reply)); ptr = 0; memcpy(buffer, wiznet_header, sizeof(WIZnet_Header)); ptr += sizeof(WIZnet_Header); memcpy(buffer + ptr, (void *)&reply, sizeof(WIZnet_Discovery_Reply)); ptr += sizeof(WIZnet_Discovery_Reply); if(wiznet_header->unicast == 0) { memset(remote_info->ip, 255, 4); } sendto(sock, buffer, ptr, remote_info->ip, remote_info->port); }
return stream << credential.m_serverUuid << credential.m_userName << credential.m_login << encrypt( credential.m_password ); } QDataStream& operator >>( QDataStream& stream, ServerCredential& credential ) { QByteArray password; stream >> credential.m_serverUuid >> credential.m_userName >> credential.m_login >> password; credential.m_password = decrypt( password ); return stream; } HttpCredential::HttpCredential() { } HttpCredential::HttpCredential( const QString& hostName, const QString& login, const QString& password ) : m_hostName( hostName ), m_login( login ), m_password( password ) { } HttpCredential::~HttpCredential()
SafeString<char> ProtectedBuffer::toString(){ SafeString<char> result(data.begin(), data.end()); decrypt(const_cast<uint8_t*>(reinterpret_cast<const uint8_t*>(result.data())), result.size()); return result; }
int main(int argc, char**argv) { int n; char sendline[10000]; char recvline[10000]; char key[32]; memset(key,'\0',32); unsigned char decrypted[10000]; FILE *file; //memset(recvline,'\0',10000); //char user_input[1000]; file=fopen(argv[1],"r"); char *split=strtok(argv[1],"."); split=strtok(NULL,"."); if(file==0 || strcmp(split,"bank")) { printf("Error opening ATM initialization file\n"); return 64; } fread(key,sizeof(key),32,file); key[32]='\0'; //printf("bank file contents: %s\n",key); HashTable *users = hash_table_create(100); HashTable *balance = hash_table_create(100); Bank *bank = bank_create(); //bank->users = list_create(); //bank->usr_key = hash_table_create(100); //bank->usr_bal = hash_table_create(100); printf("%s", prompt); fflush(stdout); while(1) { memset(decrypted,'\0',10000); memset(recvline,'\0',10000); //memset(sendline,'\0',10000); fd_set fds; FD_ZERO(&fds); FD_SET(0, &fds); FD_SET(bank->sockfd, &fds); select(bank->sockfd+1, &fds, NULL, NULL, NULL); if(FD_ISSET(0, &fds)) { fgets(sendline, 10000,stdin); bank_process_local_command(bank, sendline, strlen(sendline),users,balance); printf("%s", prompt); fflush(stdout); } else if(FD_ISSET(bank->sockfd, &fds)) { ; //int flag = 0; n = bank_recv(bank, recvline, 10000); //int flag=decrypt(recvline,key,decrypted,n); if(!decrypt(recvline,key,decrypted,n)) { //this means that it has not been decrypted correctly so it will return a null packet unsigned char encrypted[10000]; char packet[10000]; sprintf(packet,"<%s>",NULL); int out_size =0; encrypt(packet,key,encrypted,&out_size); bank_send(bank, encrypted, out_size); printf("%s", prompt); fflush(stdout); continue; } //printf("%s\n",decrypted); char * message=strtok(decrypted,"\n"); bank_process_remote_command(bank, message, n, users,key,balance); } } hash_table_free(balance); hash_table_free(users); //never executes bank_free(bank); //fclose(file); return EXIT_SUCCESS; }
// Main method of HW5, mostly taking user input and running the correct prog int main(int argc, char *argv[]) { // Look for correct command line arguments if(argc <= 1) { usage(); return 0; } else { if(strcmp(argv[1], "tablecheck") == 0) { // Tablecheck prog should be run FILE* tablefile = NULL; for(int i=2; i<argc; i++) { if(strncmp(argv[i], "-t=", 3) == 0) { tablefile = fopen(argv[i]+3, "r"); if(tablefile == NULL) { fprintf(stderr, "ERROR: invalid file '%s' for reading.\n", argv[i]+3); return 0; } } } if(tablefile) { tablecheck(tablefile); fclose(tablefile); } else { usage("tablecheck"); } } else if(strcmp(argv[1], "encrypt") == 0) { // Encrypt prog should be run char *key = NULL; FILE* tablefile = NULL; for(int i=2; i<argc; i++) { if(strncmp(argv[i], "-k=", 3) == 0) { key = argv[i]+3; } else if(strncmp(argv[i], "-t=", 3) == 0) { tablefile = fopen(argv[i]+3, "r"); if(tablefile == NULL) { fprintf(stderr, "ERROR: invalid file '%s' for reading.\n", argv[i]+3); return 0; } } } if(key && tablefile) { if(argv[argc-1][0] != '-') { // Take input from file FILE* fin = NULL; fin = fopen(argv[argc-1], "r"); if(fin == NULL) { fprintf(stderr, "ERROR: invalid file '%s' for reading.\n", argv[argc-1]); return 0; } encrypt(key, tablefile, fin); fclose(fin); } else { // Take input from cmd line encrypt(key, tablefile, stdin); } fclose(tablefile); } else { usage("encrypt"); } } else if(strcmp(argv[1], "decrypt") == 0) { // Decrypt prog should be run char *key = NULL; FILE* tablefile = NULL; for(int i=2; i<argc; i++) { if(strncmp(argv[i], "-k=", 3) == 0) { key = argv[i]+3; } else if(strncmp(argv[i], "-t=", 3) == 0) { tablefile = fopen(argv[i]+3, "r"); if(tablefile == NULL) { fprintf(stderr, "ERROR: invalid file '%s' for reading.\n", argv[i]+3); return 0; } } } if(key && tablefile) { if(argv[argc-1][0] != '-') { // Take input from file FILE* fin = NULL; fin = fopen(argv[argc-1], "r"); if(fin == NULL) { fprintf(stderr, "ERROR: invalid file '%s' for reading.\n", argv[argc-1]); return 0; } decrypt(key, tablefile, fin); fclose(fin); } else { // Take input from cmd line decrypt(key, tablefile, stdin); } fclose(tablefile); } else { usage("decrypt"); } } else if(strcmp(argv[1], "encrypt3") == 0) { // Encrypt3 prog should be run char *key3 = NULL; FILE* tablefile = NULL; for(int i=2; i<argc; i++) { if(strncmp(argv[i], "-k=", 3) == 0) { key3 = argv[i]+3; } else if(strncmp(argv[i], "-t=", 3) == 0) { tablefile = fopen(argv[i]+3, "r"); if(tablefile == NULL) { fprintf(stderr, "ERROR: invalid file '%s' for reading.\n", argv[i]+3); return 0; } } } if(key3 && tablefile) { if(argv[argc-1][0] != '-') { // Take input from file FILE* fin = NULL; fin = fopen(argv[argc-1], "r"); if(fin == NULL) { fprintf(stderr, "ERROR: invalid file '%s' for reading.\n", argv[argc-1]); return 0; } encrypt3(key3, tablefile, fin); fclose(fin); } else { // Take input from cmd line encrypt3(key3, tablefile, stdin); } fclose(tablefile); } else { usage("encrypt3"); } } else if(strcmp(argv[1], "decrypt3") == 0) { // Decrypt3 prog should be run char *key3 = NULL; FILE* tablefile = NULL; for(int i=2; i<argc; i++) { if(strncmp(argv[i], "-k=", 3) == 0) { key3 = argv[i]+3; } else if(strncmp(argv[i], "-t=", 3) == 0) { tablefile = fopen(argv[i]+3, "r"); if(tablefile == NULL) { fprintf(stderr, "ERROR: invalid file '%s' for reading.\n", argv[i]+3); return 0; } } } if(key3 && tablefile) { if(argv[argc-1][0] != '-') { // Take input from file FILE* fin = NULL; fin = fopen(argv[argc-1], "r"); if(fin == NULL) { fprintf(stderr, "ERROR: invalid file '%s' for reading.\n", argv[argc-1]); return 0; } decrypt3(key3, tablefile, fin); fclose(fin); } else { // Take input from cmd line decrypt3(key3, tablefile, stdin); } fclose(tablefile); } else { usage("decrypt3"); } } else { // Failed input usage(); } } return 0; }
int main(int argc, char **argv) { const char *pubkeyfile = NULL, *seckeyfile = NULL, *msgfile = NULL, *xfile = NULL; char xfilebuf[1024]; const char *ident = NULL; int ch; int embedded = 0; int quiet = 0; int v1compat = 0; const char *password = NULL; opt_binary binary = { 0 }; enum { NONE, DECRYPT, ENCRYPT, GENERATE, SIGN, VERIFY } verb = NONE; while ((ch = getopt(argc, argv, "1CDEGSVbei:m:np:qs:x:")) != -1) { switch (ch) { case '1': v1compat = 1; break; case 'D': if (verb) usage(NULL); verb = DECRYPT; break; case 'E': if (verb) usage(NULL); verb = ENCRYPT; break; case 'G': if (verb) usage(NULL); verb = GENERATE; break; case 'S': if (verb) usage(NULL); verb = SIGN; break; case 'V': if (verb) usage(NULL); verb = VERIFY; break; case 'b': binary.v = 1; break; case 'e': embedded = 1; break; case 'i': ident = optarg; break; case 'm': msgfile = optarg; break; case 'n': password = ""; break; case 'p': pubkeyfile = optarg; break; case 'q': quiet = 1; break; case 's': seckeyfile = optarg; break; case 'x': xfile = optarg; break; default: usage(NULL); break; } } argc -= optind; argv += optind; if (argc != 0) usage(NULL); switch (verb) { case ENCRYPT: case DECRYPT: if (!msgfile) usage("You must specify a message-file"); if (!xfile) { if (strcmp(msgfile, "-") == 0) usage("must specify encfile with - message"); if (snprintf(xfilebuf, sizeof(xfilebuf), "%s.enc", msgfile) >= sizeof(xfilebuf)) errx(1, "path too long"); xfile = xfilebuf; } break; case SIGN: case VERIFY: if (!xfile && msgfile) { if (strcmp(msgfile, "-") == 0) usage("must specify sigfile with - message"); if (snprintf(xfilebuf, sizeof(xfilebuf), "%s.sig", msgfile) >= sizeof(xfilebuf)) errx(1, "path too long"); xfile = xfilebuf; } break; default: break; } switch (verb) { case DECRYPT: decrypt(pubkeyfile, seckeyfile, msgfile, xfile); break; case ENCRYPT: if (seckeyfile && (!pubkeyfile && !ident)) usage("specify a pubkey or ident"); if (pubkeyfile || ident) { if (v1compat) v1pubencrypt(pubkeyfile, ident, seckeyfile, msgfile, xfile, binary); else pubencrypt(pubkeyfile, ident, seckeyfile, msgfile, xfile, binary); } else symencrypt(msgfile, xfile, binary); break; case GENERATE: if (!ident && !(ident= getenv("USER"))) ident = "unknown"; /* can specify none, but not only one */ if ((!pubkeyfile && seckeyfile) || (!seckeyfile && pubkeyfile)) usage("must specify pubkey and seckey"); /* if none, create ~/.reop */ if (!pubkeyfile && !seckeyfile) { char buf[1024]; const char *home; if (!(home = getenv("HOME"))) errx(1, "can't find HOME"); snprintf(buf, sizeof(buf), "%s/.reop", home); if (mkdir(buf, 0700) == -1 && errno != EEXIST) err(1, "Unable to create ~/.reop"); } generate(pubkeyfile, seckeyfile, ident, password); break; case SIGN: if (!msgfile) usage("must specify message"); signfile(seckeyfile, msgfile, xfile, embedded); break; case VERIFY: if (!msgfile && !xfile) usage("must specify message or sigfile"); if (msgfile) verifysimple(pubkeyfile, msgfile, xfile, quiet); else verifyembedded(pubkeyfile, xfile, quiet); break; default: usage(NULL); break; } return 0; }
Coin<FIELD> decrypt(const AddrPair<FIELD>& addr) const { return decrypt(addr.secretAddr(), addr.publicAddr()); }
int traiter_recu (char * requete_recu) { unsigned char requete_decrypt[sizeof(requete_recu)]; puts("YIHI"); decrypt(requete_recu, requete_decrypt, strlen(requete_recu)); printf("JAI RECU -> %s\n", requete_recu); printf("DECRYPT -> %s\n", requete_decrypt); char *type = malloc (sizeof (char*) * 256); char *donnee = malloc (sizeof (char*) * 256); char * save_ptr; type = strtok_r(requete_decrypt, "*", &save_ptr); int j = 0; /*while (*save_ptr != '\0') { donnee[j] = *(save_ptr++); j++; }*/ //if (type[0] == 'R') printf("DONNEE de la reponse -> %s\n", donnee); switch(type[0]) { case 'R' : while (*save_ptr != '\0') { donnee[j] = *(save_ptr++); j++; } printf("DONNEE de la reponse -> %s\n", donnee); break; case '1' : ; char *status_requete = malloc (sizeof (char*) * 1024); char *test = malloc (sizeof (char*) * 1024); char *nom = recup_valeur("nom"); printf("NOM -> %s\n", nom); //char *status = recup_valeur("status"); printf("RECUP_STATUS -> %s\n", recup_valeur("status")); status_requete = strtok_r(NULL, "*", &save_ptr); test = strtok_r(NULL, "*", &save_ptr); //printf("TEST -> %s\n", test); printf("STATUS -> %s\n", status_requete); if( strcmp(recup_valeur("status"), status_requete) == 0) { puts("Correspond"); unsigned char a_envoyer[sizeof (char *) * 1024]; sprintf(a_envoyer, "1*%s*%s", nom, recup_valeur("status")); unsigned char a_envoyer_crypt[sizeof(a_envoyer)]; crypt(a_envoyer, a_envoyer_crypt, strlen(a_envoyer)); envoi_requete(a_envoyer_crypt); } else { puts("NOP"); unsigned char a_envoyer[sizeof (char *) * 1024]; sprintf(a_envoyer, "1*none"); unsigned char a_envoyer_crypt[sizeof(a_envoyer)]; crypt(a_envoyer, a_envoyer_crypt, strlen(a_envoyer)); envoi_requete(a_envoyer_crypt); } break; } return 0; }
void decrypt(const char* in, std::size_t len, uint8_t* out) { decrypt(reinterpret_cast<const uint8_t*>(in), len, out); }
int main(int argc, char *argv[]) { FILE *rsapub_key_fp; unsigned char *cam128_key, *cam128_iv; unsigned char *cipher_of_secret_text, *cipher_of_signed_key, *signed_key, *secret_text, *clobbered_key; EVP_PKEY *rsapub_key; unsigned char *rc4_40_key; const EVP_CIPHER *cam128_cfb8, *rc4_40; const EVP_MD *sha; EVP_MD_CTX sha_ctx; int cam128_cfb8_keylen, cam128_cfb8_ivlen, rc4_40_keylen, signed_key_size; int ret, count; long cipher_of_signed_key_size, clobbered_key_size, cipher_of_secret_text_size, secret_text_size; // get the parameters for CAMELLIA128_cfb8 cam128_cfb8 = EVP_camellia_128_cfb8(); cam128_cfb8_keylen = EVP_CIPHER_key_length(cam128_cfb8); cam128_cfb8_ivlen = EVP_CIPHER_iv_length(cam128_cfb8); // get the parameters for RC4_40 rc4_40 = EVP_rc4_40(); rc4_40_keylen = EVP_CIPHER_key_length(rc4_40); // get the parameters for sha sha = EVP_sha(); // read the s67766-clobbered-key.bin and store the key and iv for CAMELLIA128-cfb8 cam128_key = malloc(cam128_cfb8_keylen); cam128_iv = malloc(cam128_cfb8_ivlen); clobbered_key_size = read_file(clobbered_key_file, &clobbered_key); if(clobbered_key_size != cam128_cfb8_keylen+cam128_cfb8_ivlen) { printf("reading file %s returned not enough Bytes: %ld, instead of: %d\n", clobbered_key_file, clobbered_key_size, cam128_cfb8_keylen+cam128_cfb8_ivlen); perror(""); } memcpy(cam128_key, clobbered_key, cam128_cfb8_keylen); memcpy(cam128_iv, clobbered_key+cam128_cfb8_keylen, cam128_cfb8_ivlen); // read the s67766-cipher-of-signed-key.bin cipher_of_signed_key_size = read_file(cipher_of_signed_key_file, &cipher_of_signed_key); // read the public key from rsapub.pem rsapub_key_fp = fopen(rsapub_key_file, "r"); if (!rsapub_key_fp) { printf("opening file %s returned error\n", rsapub_key_file); perror(""); } rsapub_key = PEM_read_PUBKEY(rsapub_key_fp, NULL, NULL, NULL); if (!rsapub_key) { printf("PEM_read_PUBKEY returned error for RSA\n"); } if(fclose(rsapub_key_fp) != 0) { printf("closing file %s returned error\n", rsapub_key_file); perror(""); } // restore the clobbered key with bruteforce signed_key = malloc(cipher_of_signed_key_size); for(count = 0; count<=255; count++) { memset(cam128_key, count, 1); //decrypt the cipher with guessed key signed_key_size = decrypt(cam128_cfb8, &signed_key, cipher_of_signed_key, cipher_of_signed_key_size, cam128_key, cam128_iv); if(signed_key_size==-1) { return -1; } if(EVP_VerifyInit(&sha_ctx, sha) == 0) { printf("EVP_VerifyInit returned error for SHA\n"); } if(EVP_VerifyUpdate(&sha_ctx, signed_key, rc4_40_keylen) == 0) { printf("EVP_VerifyUpdate returned error for SHA\n"); } ret = EVP_VerifyFinal(&sha_ctx, signed_key+rc4_40_keylen, signed_key_size-rc4_40_keylen, rsapub_key); switch(ret) { case -1: printf("EVP_VerifyFinal returned error for SHA\n"); break; case 0: break; case 1: count = 255; break; } } // extract the key for RC-4 40 rc4_40_key = malloc(rc4_40_keylen); memcpy(rc4_40_key, signed_key, rc4_40_keylen); // read the s67766-cipher-of-secret-text.bin cipher_of_secret_text_size = read_file(cipher_of_secret_text_file, &cipher_of_secret_text); // decrypt s67766-cipher-of-secret-text.bin secret_text = malloc(cipher_of_secret_text_size); secret_text_size = 0; secret_text_size = decrypt(rc4_40, &secret_text, cipher_of_secret_text, cipher_of_secret_text_size, rc4_40_key, NULL); // write the s67766-plain.bin if(write_file(plain_file, secret_text, secret_text_size)==-1) { return -1; } return 0; }
void decrypt(const char* in, std::size_t len, char* out) { decrypt(in, len, reinterpret_cast<byte*>(out)); }
int main() { srand((unsigned)time(NULL)); int i; EC_KEY* key; //key = EC_KEY_new_by_curve_name(415); key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1); const EC_GROUP *group = EC_KEY_get0_group(key); if (EC_KEY_generate_key(key)==0) { printf("Error generate key\n"); return -1; } unsigned char pk_b[33]; const EC_POINT *pub = EC_KEY_get0_public_key(key); if (EC_POINT_point2oct(group, pub, POINT_CONVERSION_COMPRESSED, pk_b, 33, 0)!=33) { printf("Error 2\n"); return -1; } unsigned char h1[16],h2[16]; printf("\x02"); for (i=0;i<16;i++) { h1[i]=rand()%256; printf("%c",h1[i]); } for (i=0;i<33;i++) printf("%c",pk_b[i]); fflush(stdout); //get h2 for (i=0;i<16;i++) h2[i]=rand()%256; for (i=0;i<16;i++) scanf("%c",&h2[i]); //get peerpk_b unsigned char peerpk_b[33]={2 , 30 , 25 , 50 , 17 , 242 , 232 , 55 , 157 , 18 , 106 , 115 , 214 , 193 , 192 , 39 , 207 , 226 , 184 , 216 , 244 , 147 , 111 , 188 , 125 , 230 , 38 , 125 , 231 , 50 , 56 , 152 , 148 }; for (i=0;i<33;i++) scanf("%c",&peerpk_b[i]); EC_POINT *peerpk = EC_POINT_new(group); if (EC_POINT_oct2point(group, peerpk, peerpk_b, 33, 0)==0) { printf("Error 3\n"); return -1; } unsigned char skey[33]; if (ECDH_compute_key(skey, 32, peerpk, key, NULL)==0) { printf("Error 4\n"); return -1; } SHA512_CTX shactx; unsigned char hash[SHA512_DIGEST_LENGTH]; SHA512_Init(&shactx); SHA512_Update(&shactx, h2, 16); SHA512_Update(&shactx, skey, 32); SHA512_Update(&shactx, h1, 16); SHA512_Final(hash, &shactx); for (i=0;i<64;i++) printf("%02x",hash[i]); fflush(stdout); struct cipher c; c.recvfd=0; c.sendfd=1; for (i=0;i<16;i++) c.sendkey[i]=hash[i]; for (i=0;i<4;i++) c.sendiv[i]=hash[32+i]; for (i=0;i<16;i++) c.recvkey[i]=hash[16+i]; for (i=0;i<4;i++) c.recviv[i]=hash[36+i]; c.sendcnt=0; c.recvcnt=0; unsigned char d[1000]; unsigned char oiv[8]; int op; char dlen; while (true) { scanf("%d",&op); scanf("%c",&dlen); scanf("%c",&dlen); for (i=0;i<dlen;i++) scanf("%c",&d[i]); if (op==1) { for (i=0;i<8;i++) oiv[i]=rand()%256; encrypt(c,d,dlen,oiv); c.recvcnt+=1; } else if (op==2) { for (i=0;i<8;i++) scanf("%c",&oiv[i]); decrypt(c,d,dlen,oiv, NULL); c.sendcnt+=1; } fflush(stdout); } return 0; }
//----------------------------------------------------- // //----------------------------------------------------- bool initLDAP(IPropertyTree * ldapProps) { StringAttr serverType( ldapProps->queryProp("@serverType") ); if (!serverType.length()) { fprintf(stderr, "\nERROR: serverType not set in LDAPServer component"); return false; } StringBuffer hpccUser; StringBuffer hpccPwd; ldapProps->getProp("@systemUser", hpccUser); ldapProps->getProp("@systemPassword", hpccPwd); if (0==hpccUser.length() || 0==hpccPwd.length()) { fprintf(stderr, "\nERROR: HPCC systemUser credentials not found in configuration"); return false; } StringBuffer ldapAddress; ldapProps->getProp("@ldapAddress", ldapAddress); //Get LDAP admin creds from user char buff[100]; fprintf(stdout, "\nEnter the '%s' LDAP Admin User name on '%s'...",serverType.get(),ldapAddress.str()); do { char * line = fgets(buff, sizeof(buff), stdin); if (!line) return false; } while (buff[0] == (char)'\n'); if (buff[strlen(buff)-1] == '\n') buff[strlen(buff)-1] = (char)NULL; StringAttr ldapUser(buff); fprintf(stdout, "Enter the LDAP Admin user '%s' password...",ldapUser.get()); char * line = fgets(buff, sizeof(buff), stdin); if (!line) return false; if (buff[strlen(buff)-1] == '\n') buff[strlen(buff)-1] = (char)NULL; StringAttr ldapPwd(buff); if (0==ldapUser.length() || 0==ldapPwd.length()) { fprintf(stderr, "\nERROR: Invalid LDAP Admin account credentials entered"); return false; } fprintf(stdout, "\nReady to initialize HPCC LDAP Environment, using the following settings"); fprintf(stdout, "\n\tLDAP Server : %s", ldapAddress.str()); fprintf(stdout, "\n\tLDAP Type : %s", serverType.get()); fprintf(stdout, "\n\tHPCC Admin User : %s", hpccUser.str()); fprintf(stdout, "\nProceed? y/n "); for (;;) { int c = getchar(); if (c == 'y' || c == 'Y') break; else if (c == 'n' || c == 'N') return true; } if (stricmp(serverType.get(),"ActiveDirectory")) ldapProps->setProp("@systemBasedn", ""); //Replace system user with LDAP Admin credentials ldapProps->setProp("@systemUser", ldapUser); ldapProps->setProp("@systemCommonName", ldapUser); StringBuffer sb; encrypt(sb,ldapPwd); ldapProps->setProp("@systemPassword", sb.str()); //Create security manager. This creates the required OUs Owned<ISecManager> secMgr; try { secMgr.setown(newLdapSecManager("initldap", *LINK(ldapProps))); } catch(IException *e) { StringBuffer buff; e->errorMessage(buff); e->Release(); fprintf(stderr, "\nERROR: Unable to create security manager : %s", buff.str()); return false; } //Create HPCC Admin user Owned<ISecUser> user = secMgr->createUser(hpccUser.str()); StringBuffer pwd; decrypt(pwd, hpccPwd.str()); user->credentials().setPassword(pwd.str()); try { secMgr->addUser(*user.get()); } catch(...) {}//user may already exist, so just move on //Add HPCC admin user to Administrators group CLdapSecManager* ldapSecMgr = dynamic_cast<CLdapSecManager*>(secMgr.get()); if (!ldapSecMgr) { fprintf(stderr, "\nERROR: Unable to access CLdapSecManager object"); return false; } StringAttr adminGroup; bool isActiveDir = true; if (0 == stricmp(serverType.get(),"ActiveDirectory")) adminGroup.set("Administrators"); else adminGroup.set("Directory Administrators"); try { ldapSecMgr->changeUserGroup("add", hpccUser.str(), adminGroup); } catch(...) {}//user may already be in group so just move on fprintf(stdout, "\n\nLDAP Initialization successful\n"); return true; }
bool CMyPlug::importTerrainData(iSceneData * pSceneData, const std::string& strFilename) { pSceneData->clear(); if (pSceneData->resize(253,253)) { // EncTerrain IOReadBase* pRead = IOReadBase::autoOpen(strFilename); if (pRead) { if (MAP_FILE_SIZE==pRead->GetSize()) { char buffer[MAP_FILE_SIZE]; pRead->Read(buffer,MAP_FILE_SIZE); decrypt(buffer,MAP_FILE_SIZE); char* p = buffer; unsigned short uMuFlgMap = *((unsigned short*)p); p+=2; for (int y=0; y<253; ++y) { for (int x=0; x<253; ++x) { pSceneData->setCellTileID(x,y,*p,0); p++; } p+=3; } p+=256*3; for (int y=0; y<253; ++y) { for (int x=0; x<253; ++x) { pSceneData->setCellTileID(x,y,*p,1); p++; } p+=3; } p+=256*3; for (int y=0; y<254; ++y) { for (int x=0; x<254; ++x) { pSceneData->setVertexColor(x,y,Color32(*p,255,255,255)); p++; } p+=2; } } IOReadBase::autoClose(pRead); } // EncTerrain.att pRead = IOReadBase::autoOpen(ChangeExtension(strFilename,".att")); if (pRead) { if (ATT_FILE_129KB_SIZE==pRead->GetSize()) { char buffer[ATT_FILE_129KB_SIZE]; pRead->Read(buffer,ATT_FILE_129KB_SIZE); decrypt(buffer,ATT_FILE_129KB_SIZE); decrypt2(buffer,ATT_FILE_129KB_SIZE); char* p = buffer; unsigned long uMuFlgAtt = *((unsigned long*)p); p+=4; for (int y=0; y<253; ++y) { for (int x=0; x<253; ++x) { pSceneData->setCellAttribute(x,y,*p); p+=2; } p+=6; } } else if (ATT_FILE_65KB_SIZE==pRead->GetSize()) { char buffer[ATT_FILE_65KB_SIZE]; pRead->Read(buffer,ATT_FILE_65KB_SIZE); decrypt(buffer,ATT_FILE_65KB_SIZE); decrypt2(buffer,ATT_FILE_65KB_SIZE); char* p = buffer; unsigned long uMuFlgAtt = *((unsigned long*)p); p+=4; for (int y=0; y<253; ++y) { for (int x=0; x<253; ++x) { pSceneData->setCellAttribute(x,y,*p); p++; } p+=3; } } IOReadBase::autoClose(pRead); } // TerrainHeight std::string strHeightFilename = GetParentPath(strFilename)+"TerrainHeight.ozb"; pRead = IOReadBase::autoOpen(strHeightFilename); if (pRead) { if (HEIGHT_HEAD_SIZE+HEIGHT_BUFFER_SIZE<=pRead->GetSize()) { pRead->Move(HEIGHT_HEAD_SIZE); for (int y=0; y<254; ++y) { pRead->Move(2); for (int x=0; x<254; ++x) { unsigned char uVal; pRead->Read(&uVal,1); pSceneData->setVertexHeight(x,y,uVal*0.015f); } } } IOReadBase::autoClose(pRead); } } return true; }
/* used to be handleServerMsg() */ void IrcParser::processNetworkIncoming(NetworkDataEvent *e) { CoreNetwork *net = qobject_cast<CoreNetwork *>(e->network()); if (!net) { qWarning() << "Received network event without valid network pointer!"; return; } // note that the IRC server is still alive net->resetPingTimeout(); QByteArray msg = e->data(); if (msg.isEmpty()) { qWarning() << "Received empty string from server!"; return; } // Now we split the raw message into its various parts... QString prefix; QByteArray trailing; QString cmd, target; // First, check for a trailing parameter introduced by " :", since this might screw up splitting the msg // NOTE: This assumes that this is true in raw encoding, but well, hopefully there are no servers running in japanese on protocol level... int idx = msg.indexOf(" :"); if (idx >= 0) { if (msg.length() > idx + 2) trailing = msg.mid(idx + 2); msg = msg.left(idx); } // OK, now it is safe to split... QList<QByteArray> params = msg.split(' '); // This could still contain empty elements due to (faulty?) ircds sending multiple spaces in a row // Also, QByteArray is not nearly as convenient to work with as QString for such things :) QList<QByteArray>::iterator iter = params.begin(); while (iter != params.end()) { if (iter->isEmpty()) iter = params.erase(iter); else ++iter; } if (!trailing.isEmpty()) params << trailing; if (params.count() < 1) { qWarning() << "Received invalid string from server!"; return; } QString foo = net->serverDecode(params.takeFirst()); // a colon as the first chars indicates the existence of a prefix if (foo[0] == ':') { foo.remove(0, 1); prefix = foo; if (params.count() < 1) { qWarning() << "Received invalid string from server!"; return; } foo = net->serverDecode(params.takeFirst()); } // next string without a whitespace is the command cmd = foo.trimmed(); QList<Event *> events; EventManager::EventType type = EventManager::Invalid; uint num = cmd.toUInt(); if (num > 0) { // numeric reply if (params.count() == 0) { qWarning() << "Message received from server violates RFC and is ignored!" << msg; return; } // numeric replies have the target as first param (RFC 2812 - 2.4). this is usually our own nick. Remove this! target = net->serverDecode(params.takeFirst()); type = EventManager::IrcEventNumeric; } else { // any other irc command QString typeName = QLatin1String("IrcEvent") + cmd.at(0).toUpper() + cmd.mid(1).toLower(); type = eventManager()->eventTypeByName(typeName); if (type == EventManager::Invalid) { type = eventManager()->eventTypeByName("IrcEventUnknown"); Q_ASSERT(type != EventManager::Invalid); } target = QString(); } // Almost always, all params are server-encoded. There's a few exceptions, let's catch them here! // Possibly not the best option, we might want something more generic? Maybe yet another layer of // unencoded events with event handlers for the exceptions... // Also, PRIVMSG and NOTICE need some special handling, we put this in here as well, so we get out // nice pre-parsed events that the CTCP handler can consume. QStringList decParams; bool defaultHandling = true; // whether to automatically copy the remaining params and send the event switch (type) { case EventManager::IrcEventPrivmsg: defaultHandling = false; // this might create a list of events if (checkParamCount(cmd, params, 1)) { QString senderNick = nickFromMask(prefix); QByteArray msg = params.count() < 2 ? QByteArray() : params.at(1); QStringList targets = net->serverDecode(params.at(0)).split(',', QString::SkipEmptyParts); QStringList::const_iterator targetIter; for (targetIter = targets.constBegin(); targetIter != targets.constEnd(); ++targetIter) { QString target = net->isChannelName(*targetIter) ? *targetIter : senderNick; msg = decrypt(net, target, msg); events << new IrcEventRawMessage(EventManager::IrcEventRawPrivmsg, net, msg, prefix, target, e->timestamp()); } } break; case EventManager::IrcEventNotice: defaultHandling = false; if (checkParamCount(cmd, params, 2)) { QStringList targets = net->serverDecode(params.at(0)).split(',', QString::SkipEmptyParts); QStringList::const_iterator targetIter; for (targetIter = targets.constBegin(); targetIter != targets.constEnd(); ++targetIter) { QString target = *targetIter; // special treatment for welcome messages like: // :[email protected]. NOTICE egst :[#apache] Welcome, this is #apache. Please read the in-channel topic message. This channel is being logged by IRSeekBot. If you have any question please see http://blog.freenode.net/?p=68 if (!net->isChannelName(target)) { QString decMsg = net->serverDecode(params.at(1)); QRegExp welcomeRegExp("^\\[([^\\]]+)\\] "); if (welcomeRegExp.indexIn(decMsg) != -1) { QString channelname = welcomeRegExp.cap(1); decMsg = decMsg.mid(welcomeRegExp.matchedLength()); CoreIrcChannel *chan = static_cast<CoreIrcChannel *>(net->ircChannel(channelname)); // we only have CoreIrcChannels in the core, so this cast is safe if (chan && !chan->receivedWelcomeMsg()) { chan->setReceivedWelcomeMsg(); events << new MessageEvent(Message::Notice, net, decMsg, prefix, channelname, Message::None, e->timestamp()); continue; } } } if (prefix.isEmpty() || target == "AUTH") { target = QString(); } else { if (!target.isEmpty() && net->prefixes().contains(target.at(0))) target = target.mid(1); if (!net->isChannelName(target)) target = nickFromMask(prefix); } #ifdef HAVE_QCA2 // Handle DH1080 key exchange if (params[1].startsWith("DH1080_INIT") && !net->isChannelName(target)) { events << new KeyEvent(EventManager::KeyEvent, net, prefix, target, KeyEvent::Init, params[1].mid(12)); } else if (params[1].startsWith("DH1080_FINISH") && !net->isChannelName(target)) { events << new KeyEvent(EventManager::KeyEvent, net, prefix, target, KeyEvent::Finish, params[1].mid(14)); } else #endif events << new IrcEventRawMessage(EventManager::IrcEventRawNotice, net, params[1], prefix, target, e->timestamp()); } } break; // the following events need only special casing for param decoding case EventManager::IrcEventKick: if (params.count() >= 3) { // we have a reason decParams << net->serverDecode(params.at(0)) << net->serverDecode(params.at(1)); decParams << net->channelDecode(decParams.first(), params.at(2)); // kick reason } break; case EventManager::IrcEventPart: if (params.count() >= 2) { QString channel = net->serverDecode(params.at(0)); decParams << channel; decParams << net->userDecode(nickFromMask(prefix), params.at(1)); } break; case EventManager::IrcEventQuit: if (params.count() >= 1) { decParams << net->userDecode(nickFromMask(prefix), params.at(0)); } break; case EventManager::IrcEventTopic: if (params.count() >= 1) { QString channel = net->serverDecode(params.at(0)); decParams << channel; decParams << (params.count() >= 2 ? net->channelDecode(channel, decrypt(net, channel, params.at(1), true)) : QString()); } break; case EventManager::IrcEventNumeric: switch (num) { case 301: /* RPL_AWAY */ if (params.count() >= 2) { QString nick = net->serverDecode(params.at(0)); decParams << nick; decParams << net->userDecode(nick, params.at(1)); } break; case 332: /* RPL_TOPIC */ if (params.count() >= 2) { QString channel = net->serverDecode(params.at(0)); decParams << channel; decParams << net->channelDecode(channel, decrypt(net, channel, params.at(1), true)); } break; case 333: /* Topic set by... */ if (params.count() >= 3) { QString channel = net->serverDecode(params.at(0)); decParams << channel << net->serverDecode(params.at(1)); decParams << net->channelDecode(channel, params.at(2)); } break; } default: break; } if (defaultHandling && type != EventManager::Invalid) { for (int i = decParams.count(); i < params.count(); i++) decParams << net->serverDecode(params.at(i)); // We want to trim the last param just in case, except for PRIVMSG and NOTICE // ... but those happen to be the only ones not using defaultHandling anyway if (!decParams.isEmpty() && decParams.last().endsWith(' ')) decParams.append(decParams.takeLast().trimmed()); IrcEvent *event; if (type == EventManager::IrcEventNumeric) event = new IrcEventNumeric(num, net, prefix, target); else event = new IrcEvent(type, net, prefix); event->setParams(decParams); event->setTimestamp(e->timestamp()); events << event; } foreach(Event *event, events) { emit newEvent(event); }
void decrypt_file (const gchar *input_file_path, const gchar *pwd) { GError *err = NULL; goffset file_size = get_file_size (input_file_path); if (file_size == -1) { return; } if (file_size < (goffset) (sizeof (Metadata) + SHA512_DIGEST_SIZE)) { g_printerr ("The selected file is not encrypted.\n"); return; } GFile *in_file = g_file_new_for_path (input_file_path); GFileInputStream *in_stream = g_file_read (in_file, NULL, &err); if (err != NULL) { g_printerr ("%s\n", err->message); // TODO return; } gchar *output_file_path; if (!g_str_has_suffix (input_file_path, ".enc")) { g_printerr ("The selected file may not be encrypted\n"); output_file_path = g_strconcat (input_file_path, ".decrypted", NULL); } else { output_file_path = g_strndup (input_file_path, (gsize) g_utf8_strlen (input_file_path, -1) - 4); // remove .enc } GFile *out_file = g_file_new_for_path (output_file_path); GFileOutputStream *out_stream = g_file_append_to (out_file, G_FILE_CREATE_REPLACE_DESTINATION, NULL, &err); if (err != NULL) { g_printerr ("%s\n", err->message); // TODO return; } Metadata *header_metadata = g_new0 (Metadata, 1); CryptoKeys *decryption_keys = g_new0 (CryptoKeys, 1); gssize rw_len = g_input_stream_read (G_INPUT_STREAM (in_stream), header_metadata, sizeof (Metadata), NULL, &err); if (rw_len == -1) { g_printerr ("%s\n", err->message); // TODO return; } guchar *original_hmac = g_malloc (SHA512_DIGEST_SIZE); if (!g_seekable_seek (G_SEEKABLE (in_stream), file_size - SHA512_DIGEST_SIZE, G_SEEK_SET, NULL, &err)) { g_printerr ("Couldn't set the position, exiting...\n"); //TODO return; } rw_len = g_input_stream_read (G_INPUT_STREAM (in_stream), original_hmac, SHA512_DIGEST_SIZE, NULL, &err); if (rw_len == -1) { g_printerr ("%s\n", err->message); // TODO return; } if (!g_seekable_seek (G_SEEKABLE (in_stream), 0, G_SEEK_SET, NULL, &err)) { g_printerr ("Couldn't set the position, exiting...\n"); //TODO return; } GFile *file_encrypted_data = get_g_file_with_encrypted_data (in_stream, file_size); if (file_encrypted_data == NULL) { // TODO return; } if (!setup_keys (pwd, gcry_cipher_get_algo_keylen (header_metadata->algo), header_metadata, decryption_keys)) { g_printerr ("Error during key derivation or during memory allocation\n"); //TODO return; } if (!compare_hmac (decryption_keys->hmac_key, original_hmac, file_encrypted_data)) { g_printerr ("HMAC differs from the one stored inside the file.\nEither the password is wrong or the file has been corrupted.\n"); // TODO return; } decrypt (header_metadata, decryption_keys, file_encrypted_data, file_size - sizeof (Metadata) - SHA512_DIGEST_SIZE, out_stream); g_unlink (g_file_get_path (file_encrypted_data)); // TODO remove encrypted file? Give option to the user multiple_unref (5, (gpointer) &file_encrypted_data, (gpointer) &in_stream, (gpointer) &out_stream, (gpointer) &in_file, (gpointer) &out_file); multiple_gcry_free (3, (gpointer) &decryption_keys->crypto_key, (gpointer) &decryption_keys->derived_key, (gpointer) &decryption_keys->hmac_key); multiple_free (4, (gpointer) &header_metadata, (gpointer) &output_file_path, (gpointer) &original_hmac, (gpointer) &decryption_keys); }
bool matches(InputStream &stream) { unsigned char header[12]; return stream.read(0, header, sizeof header) && decrypt(header); }
int main() { int listen_sock, conn_sock; int server_len, client_len; struct sockaddr_in server_address; struct sockaddr_in client_address; listen_sock = socket(AF_INET, SOCK_STREAM, 0); if (listen_sock == -1) { printf("khong tao duoc socket\n"); return 0; } printf("Tao socket thanh cong\n"); server_address.sin_family = AF_INET; inet_aton("127.0.0.1",&server_address.sin_addr); server_address.sin_port = htons(5500); server_len = sizeof(server_address); if(bind(listen_sock, (struct sockaddr *)&server_address,server_len)<0) { printf("bind failed.\n"); return 0; } printf("bind done\n"); int check = listen(listen_sock,10); if (check == -1) { printf("error connect"); return 0; } printf("waiting connect ...\n"); while(1) { client_len = sizeof(client_address); conn_sock = accept(listen_sock,(struct sockaddr *)&client_address, &client_len); if(conn_sock==-1){ printf("error connect\n"); return 1; }else{ printf("Accept new connection\n"); } if(fork() == 0){ close(listen_sock); int sentBytes,revedBytes,i; //char buff[1024]; int chose; while(1){ revedBytes = recv(conn_sock,buff,1024,0); if(revedBytes < 0) break; if(strcmp(buff,"S")==0) chose = 1; else if(strcmp(buff,"M")==0) chose =2; else if(strcmp(buff,"exit")==0) chose = 3; switch(chose){ case 1: printf("Menu1 \n"); while(1){ revedBytes = recv(conn_sock,buff,1024,0); buff[revedBytes]='\0'; if(strcmp(buff,"Q")==0) break; printf("string send by client : %s\n",buff); for(i=0;buff[i]!=NULL;i++) m[i]=buff[i]; n=p*q; t=(p-1)*(q-1); ce(); encrypt(); //decrypt(); for (i = 0; i < strlen(buff); i++) { buff[i]=en[i]; } sentBytes=send(conn_sock,buff,1024,0); } printf("exit menu1 \n"); break; case 2: printf("\n Menu2"); while(1){ revedBytes = recv(conn_sock,buff,1024,0); buff[revedBytes]='\0'; if(strcmp(buff,"Q")==0) break; printf("string send by client : %s\n",buff); n=p*q; t=(p-1)*(q-1); for(i=0;buff[i]!=NULL;i++) en[i]=buff[i] ; ce();decrypt(); for (i = 0; m[i]!=-1; i++) { buff[i]=(char)m[i]; } buff[i]='\0'; printf("%s\n",buff); sentBytes=send(conn_sock,buff,1024,0); } printf("exit menu2 \n"); break; case 3: close(conn_sock); break; default: break; } } close(conn_sock); exit(1); } signal(SIGCHLD,sig_chld); } return 1; }
unsigned char * AesFileEnc::key ( ) { FILE* keystore; keystore = fopen(this->keystore_path, "r"); unsigned char *iv = this->iv(32); unsigned char* key = new unsigned char[32]; const char *prompt; prompt = getpass("Your password to keystore: " ); unsigned char* sha; sha = SHA256(reinterpret_cast<const unsigned char*>(prompt), 32, NULL); //uwaga //printf("SHA %s aaa",(char *)sha); delete prompt; ERR_load_crypto_strings(); OpenSSL_add_all_algorithms(); OPENSSL_config(NULL); if(keystore == NULL) { keystore = fopen(this->keystore_path, "w+"); std::cout<<this->keystore_path; srand(time(0)); int j; char *buffer; buffer = new char; for(int i = 0 ; i<32; i++) { j = (int)(rand() / (RAND_MAX + 1.0) * 16); sprintf(buffer,"%x",j); key[i] = *buffer; } delete(buffer); unsigned char ciphertext[512]; int ciphertext_len; ciphertext_len = this->encrypt (key, 32, sha, iv, ciphertext); fprintf(keystore, "%s" ,(const char *)ciphertext); //printf("KLUCZ zapisywany:%s KKK %i" ,(const char *)ciphertext, ciphertext_len); } else{ unsigned char * decryptedtext = new unsigned char[512]; unsigned char* keycipher = new unsigned char[512]; int ciphertext_len = 0; int buff; while((buff = getc(keystore))!= EOF) { keycipher[ciphertext_len] = (unsigned char)buff; ciphertext_len++; } ciphertext_len--; //fscanf(keystore, "%512c", keycipher); int decryptedtext_len; //printf("KLUCZ wczytany:%s KKK %i" ,(const char *)keycipher, ciphertext_len); decryptedtext_len = decrypt(keycipher, ciphertext_len, sha, iv, decryptedtext); key = ( unsigned char *)decryptedtext; } unsigned char* KEY; KEY = new unsigned char[this->keyLength]; KEY[this->keyLength] = '\0'; printf("%s PIES \n",KEY); for(int i =0; i<this->keyLength; i++) {KEY[i] = key[i];} //delete(key); //delete(sha); //std::cout << "tutajkhjghjfghyt" <<std::endl; fclose(keystore); //std::cout<<this->keyLength <<std::endl; //printf("KLUCZ %s",KEY); std::cout << (const char *)KEY<<"PIES"<<std::endl; std::cout <<key<<"PIES"<<std::endl; EVP_cleanup(); ERR_free_strings(); return KEY; }
void Rijndael::decrypt(unsigned char* block, int &length){ if (block == NULL){ return; } unsigned char** _last_cipher_text; unsigned char** _next_cipher_text; if (_mode != ECB){ //allocates temp mem to save last chain block _next_cipher_text = new unsigned char* [4]; _last_cipher_text = new unsigned char* [4]; for (int i = 0; i < 4; i++){ _last_cipher_text[i] = new unsigned char [4]; _next_cipher_text[i] = new unsigned char [4]; } } int blocks = length / (_block_char_size); if (length % _block_char_size != 0){ blocks++; } unsigned char* _temp_shifted_block = new unsigned char [16]; // do inverse matrix, so pointers for char** are in position unsigned char** _temp_block = new unsigned char* [4]; for (int b = 0; b < blocks; b++){ for (int i = 0; i < 4; i++){ memcpy(_temp_shifted_block+i*4, block+i+0+b*16, 1); memcpy(_temp_shifted_block+i*4+1, block+i+4+b*16, 1); memcpy(_temp_shifted_block+i*4+2, block+i+8+b*16, 1); memcpy(_temp_shifted_block+i*4+3, block+i+12+b*16, 1); } for (int i = 0; i < 4; i++){ _temp_block[i] = &_temp_shifted_block[i*4]; } switch (_mode){ // pre block mode case ECB: break; case CBC: for (int i = 0; i < 4; i++){ memcpy(_last_cipher_text[i], _next_cipher_text[i], 4); memcpy(_next_cipher_text[i], _temp_block[i], 4); } break; case CFB: case OFB: if (b != 0){ for (int i = 0; i < 4; i++){ memcpy(_next_cipher_text[i], _temp_block[i], 4); memcpy(_temp_block[i], _last_cipher_text[i], 4); } } else{ for (int i = 0; i < 4; i++){ memcpy(_next_cipher_text[i], _temp_block[i], 4); memcpy(_temp_block[i], _iv[i], 4); } } break; } switch (_mode){ // decrypt or encrypt case ECB: case CBC: decrypt(_temp_block); break; case CFB: case OFB: encrypt(_temp_block); break; } switch (_mode){ // pos block mode case ECB: break; case CBC: if (b != 0){ xorBlock(_temp_block, _last_cipher_text); } else{ xorBlock(_temp_block, _iv); } break; case CFB: xorBlock(_temp_block, _next_cipher_text); for (int i = 0; i < 4; i++){ memcpy(_last_cipher_text[i], _next_cipher_text[i], 4); } break; case OFB: for (int i = 0; i < 4; i++){ memcpy(_last_cipher_text[i], _temp_block[i], 4); } xorBlock(_temp_block, _next_cipher_text); break; } for (int i = 0; i < 4; i++){ memcpy(block+i*4+b*16, _temp_shifted_block+i+0, 1); memcpy(block+i*4+1+b*16, _temp_shifted_block+i+4, 1); memcpy(block+i*4+2+b*16, _temp_shifted_block+i+8, 1); memcpy(block+i*4+3+b*16, _temp_shifted_block+i+12, 1); } } if (_mode != ECB){ for (int i = 0; i < 4; i++){ delete[] _last_cipher_text[i]; delete[] _next_cipher_text[i]; } delete[] _next_cipher_text; delete[] _last_cipher_text; } // removePadding(block, length, blocks); delete[] _temp_block; delete[] _temp_shifted_block; }
void pipedecryption(FILE *input, int CoreNumber){ int ProcessCount = 0; fd_set rfds; fd_set wfds; // we are only using the number of cores - because we restrict one to the parent int ProcessTotal = CoreNumber-1; int ProcessArr[ProcessTotal]; FD_ZERO(&rfds); FD_ZERO(&wfds); // timeval is used for the SELECT function struct timeval tv; tv.tv_sec = 100; tv.tv_usec = 0; int EncryptionDirectoryPipe[ProcessTotal][2]; int ProcessReadyPipe[ProcessTotal][2]; int ProcessStatus = 1; int RRcount = 0; char* directory[2050]; int directorysize; time_t ltime; for(int i = 0; i < ProcessTotal; i++){ // create the pipes. Include error handling if it fails. if(pipe(EncryptionDirectoryPipe[i])||pipe(ProcessReadyPipe[i])) { printf("[%s] Parent #%i failed to pipe. Exiting.\n",CurrTime(ltime), getpid()); exit(-1); } int ChildID = fork(); if (ChildID){ // parent process FD_SET(ProcessReadyPipe[i][1],&wfds); FD_SET(EncryptionDirectoryPipe[i][1],&wfds); FD_SET(ProcessReadyPipe[i][0],&rfds); // close the writing end of the pipe, we willl be reading from the child for its status close(ProcessReadyPipe[i][1]); // close reading end, we will be writing to the child processes close(EncryptionDirectoryPipe[i][0]); // add the child into the ProcessArr to keep track of processes created ProcessArr[i] = ChildID; } else if (ChildID == 0){ // child process // close appropriate ends of the pipe for the child process close(ProcessReadyPipe[i][0]); close(EncryptionDirectoryPipe[i][1]); while(1){ // read from the pipe the length of the incoming msg into dirsize. If its null, the pipe is empty, // so finish the loop with a break. int dirsize = 0; int readstatus = read(EncryptionDirectoryPipe[i][0], &dirsize,sizeof(int)); if (readstatus==0){ break;} // get the incoming msg using the size dirsize given in the privious msg // create character array with null termination, then zero it out char directorybuffer[dirsize+1]; bzero(&directorybuffer, dirsize+1); read(EncryptionDirectoryPipe[i][0], directorybuffer,dirsize); // parse the directory into input and output pointers respectfully char *inouttemp = strtok(directorybuffer, " "); char *input = inouttemp; inouttemp = strtok(NULL, " "); char *output = inouttemp; output = strtok(output, "\n"); // run decryption printf("[%s] Child Process ID #%i will decrypt %s. \n",CurrTime(ltime),getpid(),input); if(decrypt(input,output) > 0) printf("[%s] Process ID #%i decrypted %s successfully. \n",CurrTime(ltime),getpid(),input); if // Case for FCFS: send msg to parent saying its ready. write(ProcessReadyPipe[i][1],&ProcessStatus,sizeof(ProcessStatus)); } // Process is done all jobs. Close its writing pipe. printf("closing all work, jobs are done \n"); close(ProcessReadyPipe[i][1]); exit(0); } else{
SafeVector<uint8_t> ProtectedBuffer::toBuffer(){ SafeVector<uint8_t> result(data.begin(), data.end()); decrypt(result.data(), result.size()); return result; }
void main() { encrypt(); decrypt(); getch(); }
static void process_firmware_upload_init(uint8_t sock, Remote_Info *remote_info, WIZnet_Header *wiznet_header) { S2E_Packet *value = get_S2E_Packet_pointer(); struct __network_info_common tmp; uint16_t len; WIZnet_Firmware_Upload_Init firmware_upload; uint8_t buffer[sizeof(WIZnet_Header) + sizeof(WIZnet_Firmware_Upload_Done_Reply)]; uint32_t ptr; WIZnet_Firmware_Upload_Init_Reply reply; Firmware_Upload_Info firmware_upload_info; S2E_Packet *s2e_packet = get_S2E_Packet_pointer(); uint8_t ip[4]; uint16_t port; getsockopt(sock, SO_REMAINSIZE, &len); if(len != wiznet_header->length) return; recvfrom(sock, (uint8_t *)&firmware_upload, sizeof(WIZnet_Firmware_Upload_Init), ip, &port); if(wiznet_header->op_code[0] != FIRMWARE_UPLOAD_INIT) return; if((wiznet_header->valid & 0x80)) decrypt((wiznet_header->valid & 0x7F), (uint8_t *)&firmware_upload, len); if(memcmp(firmware_upload.dst_mac_address, s2e_packet->network_info_common.mac, 6)) return; if(strcmp((char *)firmware_upload.set_pw, (char *)s2e_packet->options.pw_setting)) return; /* Storee Current Network Information (For DHCP) */ memcpy(&tmp, &(value->network_info_common), sizeof(struct __network_info_common)); load_S2E_Packet_from_storage(); memcpy(&(value->network_info_common), &tmp, sizeof(struct __network_info_common)); save_S2E_Packet_to_storage(); //write the TFTP server ip, port, filename and etc. to storage memcpy(&firmware_upload_info.wiznet_header , wiznet_header , sizeof(WIZnet_Header)); memcpy(&firmware_upload_info.configtool_info , remote_info , sizeof(Remote_Info)); memcpy(firmware_upload_info.tftp_info.ip , (uint8_t *) (firmware_upload.server_ip) , sizeof(uint8_t)*4); memcpy((uint8_t *)&(firmware_upload_info.tftp_info.port) , (uint8_t *)&(firmware_upload.server_port), sizeof(uint8_t)*2); memcpy(firmware_upload_info.filename , (uint8_t *) (firmware_upload.file_name) , sizeof(uint8_t)*50); write_storage(0, &firmware_upload_info, sizeof(Firmware_Upload_Info)); // reply wiznet_header->length = sizeof(WIZnet_Firmware_Upload_Init_Reply); wiznet_header->op_code[1] = WIZNET_REPLY; memcpy(reply.src_mac_address, s2e_packet->network_info_common.mac, 6); if((wiznet_header->valid & 0x80)) encrypt((wiznet_header->valid & 0x7F), (uint8_t *)&reply, sizeof(WIZnet_Firmware_Upload_Init_Reply)); ptr = 0; memcpy(buffer, wiznet_header, sizeof(WIZnet_Header)); ptr += sizeof(WIZnet_Header); memcpy(buffer + ptr, (void *)&reply, sizeof(WIZnet_Firmware_Upload_Init_Reply)); ptr += sizeof(WIZnet_Firmware_Upload_Init_Reply); if(wiznet_header->unicast == 0) { memset(remote_info->ip, 255, 4); } sendto(sock, buffer, ptr, remote_info->ip, remote_info->port); // Reboot to bootloader NVIC_SystemReset(); }
SecAccessFlags getPermissions(const char *key,const char *obj,IUserDescriptor *udesc,unsigned auditflags,const char * reqSignature, CDateTime * reqUTCTimestamp) { if (!ldapsecurity||((getLDAPflags()&DLF_ENABLED)==0)) return SecAccess_Full; StringBuffer username; StringBuffer password; if (udesc) { udesc->getUserName(username); udesc->getPassword(password); } else { WARNLOG("NULL UserDescriptor in daldap.cpp getPermissions('%s')",key ? key : "NULL"); } if (0 == username.length()) { username.append(filesdefaultuser); decrypt(password, filesdefaultpassword); } Owned<ISecUser> user = ldapsecurity->createUser(username); user->credentials().setPassword(password); bool authenticated = false; //Check that the digital signature provided by the caller (signature of //caller's "scope;username;timeStamp") matches what we expect it to be if (!isEmptyString(reqSignature)) { if (nullptr == pDSM) pDSM = queryDigitalSignatureManagerInstanceFromEnv(); if (pDSM && pDSM->isDigiVerifierConfigured()) { StringBuffer requestTimestamp; reqUTCTimestamp->getString(requestTimestamp, false);//extract timestamp string from Dali request CDateTime now; now.setNow(); if (now.compare(*reqUTCTimestamp) < 0)//timestamp from the future? { ERRLOG("LDAP: getPermissions(%s) scope=%s user=%s Request digital signature timestamp %s from the future",key?key:"NULL",obj?obj:"NULL",username.str(), requestTimestamp.str()); return SecAccess_None;//deny } CDateTime expiry; expiry.set(now); expiry.adjustTime(requestSignatureExpiryMinutes);//compute expiration timestamp if (expiry.compare(*reqUTCTimestamp) < 0)//timestamp too far in the past? { ERRLOG("LDAP: getPermissions(%s) scope=%s user=%s Expired request digital signature timestamp %s",key?key:"NULL",obj?obj:"NULL",username.str(), requestTimestamp.str()); return SecAccess_None;//deny } VStringBuffer expectedStr("%s;%s;%s", obj, username.str(), requestTimestamp.str()); StringBuffer b64Signature(reqSignature);// signature of scope;user;timestamp if (!pDSM->digiVerify(expectedStr, b64Signature))//does the digital signature match what we expect? { ERRLOG("LDAP: getPermissions(%s) scope=%s user=%s fails digital signature verification",key?key:"NULL",obj?obj:"NULL",username.str()); return SecAccess_None;//deny } authenticated = true;//Digital signature verified } else ERRLOG("LDAP: getPermissions(%s) scope=%s user=%s digital signature support not available",key?key:"NULL",obj?obj:"NULL",username.str()); } if (!authenticated && !ldapsecurity->authenticateUser(*user, NULL)) { ERRLOG("LDAP: getPermissions(%s) scope=%s user=%s fails LDAP authentication",key?key:"NULL",obj?obj:"NULL",username.str()); return SecAccess_None;//deny } bool filescope = stricmp(key,"Scope")==0; bool wuscope = stricmp(key,"workunit")==0; if (filescope || wuscope) { SecAccessFlags perm = SecAccess_None; unsigned start = msTick(); if (filescope) perm=ldapsecurity->authorizeFileScope(*user, obj); else if (wuscope) perm=ldapsecurity->authorizeWorkunitScope(*user, obj); if (perm == SecAccess_Unavailable) perm = SecAccess_None; unsigned taken = msTick()-start; #ifndef _DEBUG if (taken>100) #endif { PROGLOG("LDAP: getPermissions(%s) scope=%s user=%s returns %d in %d ms",key?key:"NULL",obj?obj:"NULL",username.str(),perm,taken); } if (auditflags&DALI_LDAP_AUDIT_REPORT) { StringBuffer auditstr; if ((auditflags&DALI_LDAP_READ_WANTED)&&!HASREADPERMISSION(perm)) auditstr.append("Lookup Access Denied"); else if ((auditflags&DALI_LDAP_WRITE_WANTED)&&!HASWRITEPERMISSION(perm)) auditstr.append("Create Access Denied"); if (auditstr.length()) { auditstr.append(":\n\tProcess:\tdaserver"); auditstr.appendf("\n\tUser:\t%s",username.str()); auditstr.appendf("\n\tScope:\t%s\n",obj?obj:""); SYSLOG(AUDIT_TYPE_ACCESS_FAILURE,auditstr.str()); } } return perm; } return SecAccess_Full; }
/* Main */ int main(void) { // Initialise Arduino functionality init(); // Attach USB for applicable processors #ifdef USBCON USBDevice.attach(); #endif /* SETUP */ int prime = 19211; int generator = 6; uint16_t private_key = prime + 1; /* Generates private key, sometimes takes a while */ while(private_key >= prime){ private_key = generate_private(); } Serial.begin(9600); int public_key_A = pow_mod(generator, private_key, prime); Serial.print("Public key A: "); Serial.println(public_key_A); int public_key_B = enter_public(); Serial.print("Public key B: "); Serial.println(public_key_B); int shared_key = pow_mod(public_key_B, private_key, prime); Serial.print("The shared key is: "); Serial.println(shared_key); /* LOOP */ Serial3.begin(9600); // Serial3: communication with other board int incoming_byte = 0; int my_PC_byte = 0; while(true){ //grab byte from other Arduino incoming_byte = Serial3.read(); if(incoming_byte != -1){ //decrypt byte int decrypted_byte = decrypt(incoming_byte, shared_key); if(decrypted_byte == 10 || decrypted_byte == 13){ Serial.write('\n'); //character code line feed Serial.write('\r'); //carriage return } else { Serial.write(decrypted_byte); } } //grab byte from PC my_PC_byte = Serial.read(); if(my_PC_byte != -1){ //encrypt byte char byte_to_send = encrypt(my_PC_byte, shared_key); Serial.write((char)my_PC_byte); Serial3.write((char)byte_to_send); } } Serial.end(); Serial3.end(); return 0; }
int main(int argc, char* argv[]) { rsa_packet packet; int i; bool cipher_done = 0; Command cmd; timeval hard_time; int sceMiVersion = SceMi::Version( SCEMI_VERSION_STRING ); SceMiParameters params("scemi.params"); SceMi *sceMi = SceMi::Init(sceMiVersion, ¶ms); // Initialize the crypto library crypto_init(); // Initialize the SceMi inport InportProxyT<Command> inport ("", "scemi_rsaxactor_req_inport", sceMi); // Initialize the SceMi outport OutportQueueT<BIG_INT> outport ("", "scemi_rsaxactor_resp_outport", sceMi); ResetXactor reset("", "scemi", sceMi); ShutdownXactor shutdown("", "scemi_shutdown", sceMi); // Service SceMi requests SceMiServiceThread *scemi_service_thread = new SceMiServiceThread (sceMi); reset.reset(); char *test_texts[] = { "deadbeef" , "badf00d" , "0ff1ce" , "cafe" , "defaced" , "aeb45a0ee831ad6e538f9c59300290db92696abbaa06a0b1df6ca317239292160d81f220c99bd788cce66cc41033e2c3eddb" , "46f4ef8bf4cf769bc5ab709267981dbb44801f9c419e99a2fc7639baaf6de6741cee37af64d5d50c87402713505cb51a88fb" , "4d889e31f9a92bd62df29e16047beb747fc92e3eceebab44d399b386825d1f55294f6d854e56d0f9a7b610c67b2ae7b5e5bd36" , "8ecbff22d54c29902bda135826fd302787742d4ce7a064f73c4ecca822235035fbdf1350bb7d9abcb4f54eb3257f2c96798d2e" , "853493ee4fd1fe0cde743cba9b180bff20bd457c152e258b9e3b478bd25fa60a6766b8d36a95885c2c47aaa63f22ff93ebea08" , "050e383b35f7688879a54ef463961533f040f943467b6a5617fdf88000c91c662d0688ddd5144f12c49106d8d81a5e04ff5ca2" , "f355db88fb426ebea4a551ad129d4fcb243b903411e638a08a81e22bfe250937f1194caea4d1f312f06ecfa906d79e8c948a0d" , "11d1e35094599325a2122f2f919a64e4d4ace48812f192ea7c11410c539707149c5d335f921f132d11795bcc1ebbf4a20b65e9" , "7b101a938d50b8dc88780235f226bc1c6650df830c3290565e12d6b9c347c06b1fb0b6fb2e648019c8526e2d4adc4dc766dba5" , "7305d1b0e93f54de5fa19eb1089fa6fbc566f8479cd381ca5894492c3078d23ef3d7a1923b9a96ffb7bf2b727fc28c6d522e54" , "4228043134c88aed152a8cd0d9aef45f742e6d12511d0ecbfbf34ea593998c499f19c6315e8779184ab58dd8e731a25d410d61" , "c04bb261996776e003d70116c3d7d56c6e2375f349983d478416f6600edeec1dbc286d4a57445be4ded180dcb7e157b35a8a4f" , "eac2be8a8e3ef31a292c4faafa9c8a63acf1e4046672c5379215f6f145ce2062ace5587f3ea226f628178426062dd9ff81186c" , "c3387e260634be9995b52c1f7114cf23d01cce8ef598cc8e5364db272aee60d06e626a2a67964d7391d5ed5c7193ab36eba81e" , "ac84645df2aaca9dee4d03e8b900007905f9bfe93bbef391ea7b57513948ec88b252add18db987b0ff886e1c7d25152f7dc1af" , "7176de621be4b8d4f5060b6ae0ab188d2c33f3aeddaddbe639cd89a8ca5784a8cdb0135108eb7f35020556795764c71536b49e" , "1a3f9f30e4c3d5d244c1d9e6cfb8f4dd47f686efb74e99de63358750e6f0622b24afc212a472bf9a93b0d39e79ff4a71ee57c6" , "68a9101d17cadfa1d89353a1d12d878dede2630904fbd8bf08ee36ccaa3c2b1759415ec3fe54bfa9f1034c5a20d01673fa06f6" , "31206814135169d02ec6893064bcaab54d9a2cc44fedc5e16dba2d97adca09fd6838af21e06def28a3815dccae369ce1e2f4af" , "f536b2e57395c6421008095dc6832282d8083ac466debc88f5979e8ada0e0b4820754f0325de29d77c46eada3683bb5be3fd10" }; for (int tests = 0; tests < 20; tests++) { char *public_key, *private_key; printf("Generating keypair in software..."); generate_key(&packet, &public_key, &private_key); #ifdef DEFINE printf("Raw data dump\n Modulus length: %zi\n", packet.mod_len); for(i = 0; i < packet.mod_len; i++) { printf("%02X", packet.mod[i]); } printf("\nPrivate exponent length: %zi\n", packet.priv_len); for(i = 0; i < packet.priv_len; i++) { printf("%02X", packet.priv_exp[i]); } printf("\nPublic exponent length: %zi\n", packet.pub_len); for(i = 0; i < packet.pub_len; i++) { printf("%02X", packet.pub_exp[i]); } #endif printf("Public Key:\n%s\n", public_key); printf("Private Key:\n%s\n", private_key); char *plaintext = test_texts[tests]; printf("Plain Text:\n%s\n\n", plaintext); char *ciphertext; ciphertext = encrypt(&packet, public_key, plaintext); printf("Software-calculated cipher Text:\n%s\n", ciphertext); printf("\nCiphertext length: %zi\n", packet.cipher_len); for(i = 0; i < packet.cipher_len; i++) { printf("%02X", packet.ciphertext[i]); } char *decrypted; decrypted = decrypt(private_key, ciphertext); printf("\nSoftware-decrypted plain Text:\n%s\n\n", decrypted); /*char *signature; signature = sign(private_key, plaintext); printf("Software signature:\n%s\n", signature); if (verify(public_key, plaintext, signature)) { printf("Software signature GOOD!\n"); } else { printf("Software signature BAD!\n"); }*/ printf("Sending to FPGA..\n"); // Pack the command for transport to FPGA // Command is specified in Command.h, run build and look in tbinclude // Assuming mod_len >= priv_len/pub_len/len(ciphertext) for(i = 0; i < packet.mod_len; i++) { cmd.m_modulus = packet.mod[packet.mod_len - i - 1]; // Send the data for decryption if(i < packet.priv_len) { cmd.m_exponent = packet.priv_exp[packet.priv_len - i - 1]; } else { cmd.m_exponent = 0; } // Since the exponent is short, pack it backwards if(i < packet.cipher_len) { cmd.m_data = packet.ciphertext[packet.cipher_len - i - 1]; } else { cmd.m_data = 0; } //printf("Sending message %i, mod: %X coeff: %X data:%X\n", i, cmd.m_data.get(), cmd.m_exponent.get(), cmd.m_data.get()); inport.sendMessage(cmd); } printf("Sending padding, 1 packet"); cmd.m_modulus = 0; cmd.m_exponent = 0; cmd.m_data = 0; timer_start(&hard_time); inport.sendMessage(cmd); printf("Getting result.."); std::cout << "Result: " << outport.getMessage() << std::endl; timer_poll("FPGA wall time: %d.%06d seconds\n", &hard_time); } std::cout << "shutting down..." << std::endl; shutdown.blocking_send_finish(); scemi_service_thread->stop(); scemi_service_thread->join(); SceMi::Shutdown(sceMi); std::cout << "finished" << std::endl; return 0; }
int main(int argc, char **argv) { int encrypt_opt = 0; int decrypt_opt = 0; int input_opt = 0; int output_opt = 0; char *input_filename = NULL; char *output_filename = NULL; int input_fd; int output_fd; off_t file_len; char *p; char buf[sizeof(image_header_t) + 3]; image_header_t *header; while (1) { static struct option long_options[] = { {"encrypt", no_argument, 0, 'e'}, {"decrypt", no_argument, 0, 'd'}, {"input", required_argument, 0, 'i'}, {"output", required_argument, 0, 'o'}, {0, 0, 0, 0 } }; int option_index = 0; int c = getopt_long(argc, argv, "dei:o:", long_options, &option_index); if (c == -1) break; switch (c) { case 'd': decrypt_opt++; if (decrypt_opt > 1) { fprintf(stderr, "%s: decrypt may only be specified once\n", argv[0]); show_usage(argv[0]); } break; case 'e': encrypt_opt++; if (encrypt_opt > 1) { fprintf(stderr, "%s: encrypt may only be specified once\n", argv[0]); show_usage(argv[0]); } break; case 'i': input_opt++; if (input_opt > 1) { fprintf(stderr, "%s: only one input file may be specified\n", argv[0]); show_usage(argv[0]); } if (strcmp("-", optarg) != 0) { input_filename = optarg; } break; case 'o': output_opt++; if (output_opt > 1) { fprintf(stderr, "%s: only one output file may be specified\n", argv[0]); show_usage(argv[0]); } if (strcmp("-", optarg) != 0) { output_filename = optarg; } break; case '?': exit(-1); default: abort(); } } if (decrypt_opt && encrypt_opt) { fprintf(stderr, "%s: decrypt and encrypt may not be used together\n", argv[0]); show_usage(argv[0]); } if (!decrypt_opt && !encrypt_opt) { fprintf(stderr, "%s: neither decrypt or encrypt were specified\n", argv[0]); show_usage(argv[0]); } temp_fd = fileno(tmpfile()); if (temp_fd < 0) { fprintf(stderr, "Can't create temporary file\n"); exit(EXIT_FAILURE); } atexit(exit_cleanup); DES_set_key_unchecked((const_DES_cblock *)DES_KEY, &schedule); if (input_filename) { input_fd = open(input_filename, O_RDONLY); if (input_fd < 0) { fprintf(stderr, "Can't open %s for reading: %s\n", input_filename, strerror(errno)); exit(EXIT_FAILURE); } copy_file(input_fd, temp_fd); close(input_fd); } else { copy_file(STDIN_FILENO, temp_fd); } file_len = lseek(temp_fd, 0, SEEK_CUR); if (file_len < 64) { fprintf(stderr, "Not enough data\n"); exit(EXIT_FAILURE); } p = mmap(0, file_len, PROT_READ|PROT_WRITE, MAP_SHARED, temp_fd, 0); if (p == MAP_FAILED) { fprintf(stderr, "mmap failed: %s\n", strerror(errno)); exit(EXIT_FAILURE); } if (encrypt_opt) { header = (image_header_t *)p; off_t len = min(file_len, ntohl(header->ih_size) + sizeof(image_header_t)); if (ntohl(header->ih_magic) != IH_MAGIC) { fprintf(stderr, "Header magic incorrect: " "expected 0x%08X, got 0x%08X\n", IH_MAGIC, ntohl(header->ih_magic)); munmap(p, file_len); exit(EXIT_FAILURE); } encrypt(p, len); munmap(p, file_len); if (len != file_len) { if (ftruncate(temp_fd, len) < 0) { fprintf(stderr, "ftruncate failed: %s\n", strerror(errno)); exit(EXIT_FAILURE); } } } if (decrypt_opt) { off_t header_len = min(file_len, sizeof(image_header_t) + 3); memcpy(buf, p, header_len); decrypt(buf, header_len); header = (image_header_t *)buf; if (ntohl(header->ih_magic) != IH_MAGIC) { fprintf(stderr, "Header magic incorrect: " "expected 0x%08X, got 0x%08X\n", IH_MAGIC, ntohl(header->ih_magic)); exit(EXIT_FAILURE); } decrypt(p, file_len); munmap(p, file_len); } lseek(temp_fd, 0, SEEK_SET); if (output_filename) { output_fd = creat(output_filename, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH); if (output_fd < 0) { fprintf(stderr, "Can't open %s for writing: %s\n", output_filename, strerror(errno)); exit(EXIT_FAILURE); } copy_file(temp_fd, output_fd); close(output_fd); } else { copy_file(temp_fd, STDOUT_FILENO); } exit(EXIT_SUCCESS); return 0; }
static int dosignencode(int dosign, int doencode, int dodecode, FILE *fpin, FILE *fpout, int argc, char **argv) { struct mimestack *boundary_stack=0; int iseof=0; while (!iseof) { static const char ct_s[]="content-type:"; struct header *h=read_headers(&boundary_stack, &iseof, fpin, fpout, dodecode ? 0:1), *hct; if (iseof && !h) continue; /* Artifact */ hct=find_header(h, ct_s); /* ** If this is a multipart MIME section, we can keep on ** truckin'. ** */ if (hct) { struct mime_header *mh= parse_mime_header(hct->header+ (sizeof(ct_s)-1)); const char *bv; if (strcasecmp(mh->header_name, "multipart/x-mimegpg") == 0) { /* Punt */ char *buf=malloc(strlen(hct->header)+100); const char *p; if (!buf) { free_mime_header(mh); free_header(h); perror("malloc"); exit(1); } strcpy(buf, "Content-Type: multipart/mixed"); p=strchr(hct->header, ';'); strcat(buf, p ? p:""); free(hct->header); hct->header=buf; mh=parse_mime_header(hct->header+ sizeof(ct_s)-1); } if (strncasecmp(mh->header_name, "multipart/", 10)==0 && (bv=get_mime_attr(mh, "boundary")) != 0 && (doencode & ENCODE_ENCAPSULATE) == 0 ) { struct header *p; push_mimestack(&boundary_stack, bv); if (dodecode) { if (strcasecmp(mh->header_name, "multipart/signed")==0 && (dodecode & DECODE_CHECKSIGN) && isgpg(mh)) { print_noncontent_headers(h, fpout ); free_mime_header(mh); checksign(&boundary_stack, &iseof, h, fpin, fpout, argc, argv); free_header(h); continue; } if (strcasecmp(mh->header_name, "multipart/encrypted") ==0 && (dodecode & DECODE_UNENCRYPT) && isgpg(mh)) { print_noncontent_headers(h, fpout ); free_mime_header(mh); decrypt(&boundary_stack, &iseof, h, fpin, fpout, argc, argv); free_header(h); continue; } } for (p=h; p; p=p->next) { fprintf(fpout, "%s", p->header); } putc('\n', fpout); free_header(h); free_mime_header(mh); find_boundary(&boundary_stack, &iseof, fpin, fpout, dodecode ? 0:1); continue; } free_mime_header(mh); } if (dodecode) { struct header *p; int is_message_rfc822=0; for (p=h; p; p=p->next) { fprintf(fpout, "%s", p->header); } putc('\n', fpout); /* ** If this is a message/rfc822 attachment, we can ** resume reading the next set of headers. */ hct=find_header(h, ct_s); if (hct) { struct mime_header *mh= parse_mime_header(hct->header+ (sizeof(ct_s)-1)); if (strcasecmp(mh->header_name, "message/rfc822") == 0) is_message_rfc822=1; free_mime_header(mh); } free_header(h); if (!is_message_rfc822) find_boundary(&boundary_stack, &iseof, fpin, fpout, 0); continue; } if (doencode) dogpgencrypt(&boundary_stack, h, &iseof, fpin, fpout, argc, argv, dosign); else dogpgsign(&boundary_stack, h, &iseof, fpin, fpout, argc, argv); free_header(h); } if (ferror(fpout)) return (1); return (0); }