[BEZ] cviceni 2

Odpovědět
Uživatelský avatar
Destroyer
VCKLAN TEAM
Příspěvky: 812
Registrován: čtv 13. srp 2009 13:50:15
Bydliště: Praha 12
Kontaktovat uživatele:

cviceni 2

Příspěvek od Destroyer » stř 11. bře 2015 3:01:28

Kód: Vybrat vše

sudo apt-get install libssl-dev
You're pro or you're a noob. That's life

Uživatelský avatar
Maple
VCKLAN TEAM
Příspěvky: 676
Registrován: úte 01. zář 2009 7:40:17
Bydliště: Babákova 2152, Praha 4
Kontaktovat uživatele:

Re: cviceni 2

Příspěvek od Maple » stř 11. bře 2015 16:04:04

Ukol 1

Kód: Vybrat vše

#include <stdio.h>
#include <string.h>
#include <openssl/evp.h>

void random_string(char *dest, size_t length) {
    char charset[] = "0123456789"
                     "abcdefghijklmnopqrstuvwxyz"
                     "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    while (length-- > 0) {
        size_t index = (double) rand() / RAND_MAX * (sizeof (charset) - 1);
        *dest++ = charset[index];
    }
    *dest = '\0';
}
 
int main(int argc, char *argv[]){
 
  int i;
  int n = 20;						// velikost stringu
  char text[n];						// string pro text
  char hashFunction[] = "sha256";   // zvolena hashovaci funkce ("sha1", "md5" ...)
 
  EVP_MD_CTX ctx;  // struktura kontextu
  const EVP_MD *type; // typ pouzite hashovaci funkce
  unsigned char hash[EVP_MAX_MD_SIZE]; // char pole pro hash - 64 bytu (max pro sha 512)
  int length;  // vysledna delka hashe
 
  /* Inicializace OpenSSL hash funkci */
  OpenSSL_add_all_digests();
  /* Zjisteni, jaka hashovaci funkce ma byt pouzita */
  type = EVP_get_digestbyname(hashFunction);
 
  /* Pokud predchozi prirazeni vratilo -1, tak nebyla zadana spravne hashovaci funkce */
  if(!type) {
    printf("Hash %s neexistuje.\n", hashFunction);
    exit(1);
  }
 
 while(1)
 	{
	  random_string(text,n);				// generovani nahodneho stringu o delce n

	  /* Provedeni hashovani */
	  EVP_DigestInit(&ctx, type);  // nastaveni kontextu
	  EVP_DigestUpdate(&ctx, text, strlen(text));  // zahashuje text a ulozi do kontextu
	  EVP_DigestFinal(&ctx, hash, (unsigned int *) &length);  // ziskani hashe z kontextu

	  /* Prubezny vypis testu - aby bylo videt, ze se neco deje */
	  printf("Zkousim text:\"%s\", hash:", text);
	  for(i = 0; i < length; i++)
		printf("%02x", hash[i]);
	  printf("\n");
	 
	  /* Kontrola hashe - pri splneni podminky vypis a ukonceni */
	 if ( hash[0] == 0xaa && hash[1] == 0xbb )
	  	{
		  /* Vypsani vysledneho hashe */
		  printf("\nNalezena hash: ");
		  for(i = 0; i < length; i++)
		  	printf("%02x", hash[i]);
		  printf("\n");
		  printf("Odpovida textu: \"%s\"\n", text);
		  printf("Text v hexadecimalni podobe: ");
          for(i = 0; i < n; i++)
            printf("%02x", text[i]);
          printf("\n\n");
          break;
		}
	}
 
  exit(0);
}

Ukol 2

Kód: Vybrat vše

#include <stdlib.h>
#include <openssl/evp.h>
#include <string.h>
 
int main(void) {
 
  unsigned char ot[1024] = "These are not the droids you are looking for";  // open text
  unsigned char st[1024];  // sifrovany text
  unsigned char key[EVP_MAX_KEY_LENGTH] = "Super strong key";  // klic pro sifrovani
  unsigned char iv[EVP_MAX_IV_LENGTH] = "inicial. vektor";  // inicializacni vektor
  const char cipherName[] = "RC4";
  const EVP_CIPHER * cipher;
 
  OpenSSL_add_all_ciphers();
  /* sifry i hashe by se nahraly pomoci OpenSSL_add_all_algorithms() */
  cipher = EVP_get_cipherbyname(cipherName);
  if(!cipher) {
    printf("Sifra %s neexistuje.\n", cipherName);
    exit(1);
  }
 
  int otLength = strlen((const char*) ot);
  int stLength = 0;
  int tmpLength = 0;
 
  EVP_CIPHER_CTX ctx; // struktura pro kontext
 
  printf("OT: %s\n", ot);
 
  /* Sifrovani */
  EVP_EncryptInit(&ctx, cipher, key, iv);  // nastaveni kontextu pro sifrovani
  EVP_EncryptUpdate(&ctx,  st, &tmpLength, ot, otLength);  // sifrovani ot
  stLength += tmpLength;
  EVP_EncryptFinal(&ctx, st + stLength, &tmpLength);  // dokonceni (ziskani zbytku z kontextu)
  stLength += tmpLength;
 
  printf ("Zasifrovano %d znaku.\n", stLength);
 
  /* Desifrovani */
  EVP_DecryptInit(&ctx, cipher, key, iv);  // nastaveni kontextu pro desifrovani
  EVP_DecryptUpdate(&ctx, ot, &tmpLength,  st, stLength);  // desifrovani st
  otLength += tmpLength;
  EVP_DecryptFinal(&ctx, ot + otLength, &tmpLength);  // dokonceni (ziskani zbytku z kontextu)
  otLength += tmpLength;
 
  /* Vypsani zasifrovaneho a rozsifrovaneho textu. */
  printf("ST: %s\nDT: %s\n", st, ot);

  /* Vypsanu v hexa */
  printf("ST v hexa: ");
  int i;
  for(i = 0; i < stLength; i++)
    {
      printf("%02x", st[i]);
    }

//------------------------------------------------------------------------------------------------
    printf("\n\n");
//------------------------------------------------------------------------------------------------
 
  unsigned char ot2[1024] = "abcdefghijklmnopqrstuvwxyz0123"; // open text
  unsigned char st2[1024];                                    // sifrovany text
  unsigned char iv2[EVP_MAX_IV_LENGTH] = "inicial. vektor2";  // inicializacni vektor
 
  int otLength2 = strlen((const char*) ot2);
  int stLength2 = 0;
  int tmpLength2 = 0;
 
  EVP_CIPHER_CTX ctx2; // struktura pro kontext
 
  printf("OT2: %s\n", ot2);
 
  /* Sifrovani */
  EVP_EncryptInit(&ctx2, cipher, key, iv2);  // nastaveni kontextu pro sifrovani
  EVP_EncryptUpdate(&ctx2,  st2, &tmpLength2, ot2, otLength2);  // sifrovani ot
  stLength2 += tmpLength2;
  EVP_EncryptFinal(&ctx2, st2 + stLength2, &tmpLength2);  // dokonceni (ziskani zbytku z kontextu)
  stLength2 += tmpLength2;
 
  printf ("Zasifrovano %d znaku.\n", stLength2);
 
  /* Desifrovani */
  EVP_DecryptInit(&ctx2, cipher, key, iv2);  // nastaveni kontextu pro desifrovani
  EVP_DecryptUpdate(&ctx2, ot2, &tmpLength2,  st2, stLength2);  // desifrovani st
  otLength2 += tmpLength2;
  EVP_DecryptFinal(&ctx2, ot2 + otLength2, &tmpLength2);  // dokonceni (ziskani zbytku z kontextu)
  otLength2 += tmpLength2;
 
  /* Vypsani zasifrovaneho a rozsifrovaneho textu. */
  printf("ST2: %s\nDT2: %s\n", st2, ot2);

  /* Vypsani v hexa */
  printf("ST2 v hexa: ");
  for(i = 0; i < stLength2; i++)
    {
      printf("%02x", st2[i]);
    }

//------------------------------------------------------------------------------------------------
  printf("\n\n");
  exit(0);
}

Kód: Vybrat vše

#include <stdio.h>
#include <stdlib.h>
#include <openssl/evp.h>
#include <string.h>

int main(void) {

  unsigned char ot[1024] = "abcdefghijklmnopqrstuvwxyz0123";  	  // znamy text
  unsigned char sthash[1024] = "06fb7405eba8d9e94fb1f28f0dd21fdec55fd54750ee84d95ecccf2b1b48";
  unsigned char st[1024];    // sifrovany text znameho textu
  const char cipherName[] = "RC4";
  const EVP_CIPHER * cipher;
 
  OpenSSL_add_all_ciphers();
  /* sifry i hashe by se nahraly pomoci OpenSSL_add_all_algorithms() */
  cipher = EVP_get_cipherbyname(cipherName);
  if(!cipher) {
    printf("Sifra %s neexistuje.\n", cipherName);
    exit(1);
  }
 
  char st2hash[1024] = "33f6630eaea4dba152baf38d019c04cbc759c94544fb9a815dc68d7b5f1a";
  unsigned char st2[1024];

  /* Prevod hexadecimalniho zapisu do znakoveho (sthash-st, st2hash-st2) */
  int i,j;
  for (i = 0, j = 0; i < strlen(sthash); i++, j+=2)
      sscanf(&sthash[j], "%02hhx", &st[i]);
  for (i = 0, j = 0; i < strlen(st2hash); i++, j+=2)
      sscanf(&st2hash[j], "%02hhx", &st2[i]);  

  int length = strlen(ot);
  unsigned char newVariable[length + 1];
  memcpy(newVariable, st2, length + 1);
           
  unsigned char * right = (unsigned char *)malloc(sizeof(unsigned char) * (length + 1));
  right[length] = '\0';
  for ( i = 0; i < length; i++)
    {
      right[i] = ( (st[i]) ^ (ot[i]));  // XOR is its own inverse
      right[i] ^= newVariable[i];
    }
  printf("Desifrovany tajny text: \"%s\"\n", right);

  free(right);
  exit(0);
}

crish
Příspěvky: 4
Registrován: stř 12. bře 2014 0:13:40

Re: cviceni 2

Příspěvek od crish » pát 13. bře 2015 14:12:40

tady mate vyreseny 2 ulohy :)

Kód: Vybrat vše

#include <stdio.h>
#include <string.h>
#include <openssl/evp.h>

#define MAX_SIZE 128
#define MSG_LENGTH 32


char * rand_string(char * res, size_t size)
{
    const char charset[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    res[size - 1] = '\0';
    if (size) {
        --size;
        for (size_t n = 0; n < size; n++) {
            int key = rand() % strlen(charset);
            res[n] = charset[key];
        }
    }
    return res;
}

void firstTask(int len)
{
    if ( len < 3 )
    {
        printf("Zvolte delku retezce alespon 3.");
        return;
    }
    int i;
    char * text = (char *)malloc(sizeof(char) * (len + 1));
    char hashFunction[] = "sha256";  // zvolena hashovaci funkce ("sha1", "md5" ...)
    EVP_MD_CTX ctx;  // struktura kontextu
    const EVP_MD *type; // typ pouzite hashovaci funkce
    unsigned char hash[EVP_MAX_MD_SIZE]; // char pole pro hash - 64 bytu (max pro sha 512)
    int length;  // vysledna delka hashe
    
    /* Inicializace OpenSSL hash funkci */
    OpenSSL_add_all_digests();
    /* Zjisteni, jaka hashovaci funkce ma byt pouzita */
    type = EVP_get_digestbyname(hashFunction);
    
    /* Pokud predchozi prirazeni vratilo -1, tak nebyla zadana spravne hashovaci funkce */
    if(!type) {
        printf("Hash %s neexistuje.\n", hashFunction);
        exit(1);
    }
    
    while ( 1 )
    {
        
        text = rand_string(text, len + 1);
        EVP_DigestInit(&ctx, type);  // nastaveni kontextu
        EVP_DigestUpdate(&ctx, text, strlen(text));  // zahashuje text a ulozi do kontextu
        EVP_DigestFinal(&ctx, hash, (unsigned int *) &length);  // zjiskani hashe z kontextu
        if ( hash[0] == 0xaa && hash[1] == 0xbb )
            break;
    }
    
    /* Vypsani vysledneho hashe */
    printf("Hash textu \"%s\" je: ", text);
    for(i = 0; i < length; i++){
        printf("%02x", hash[i]);
    }
    printf("\n");
    
    free(text);
    
}

void secondTask (void )
{
    unsigned char publicMessage[MSG_LENGTH + 1] = "abcdefghijklmnopqrstuvwxyz0123\0";
    unsigned char secretMessage[MSG_LENGTH + 1] = "myVerySecretMessageNoOneWillGe\0";
    unsigned char publicCrypted[1024];  // sifrovany text
    unsigned char secretCrypted[1024];
    unsigned char key[EVP_MAX_KEY_LENGTH] = "really_secret_key256";  // klic pro sifrovani
    unsigned char iv[EVP_MAX_IV_LENGTH] = "secretVector";  // inicializacni vektor
    const char cipherName[] = "RC4";
    const EVP_CIPHER * cipher;
    
    OpenSSL_add_all_ciphers();
    /* sifry i hashe by se nahraly pomoci OpenSSL_add_all_algorithms() */
    cipher = EVP_get_cipherbyname(cipherName);
    if(!cipher) {
        printf("Sifra %s neexistuje.\n", cipherName);
        exit(1);
    }
    
    int otLength = (int)strlen((const char*) publicMessage);
    int stLength = 0;
    int tmpLength = 0;
    
    EVP_CIPHER_CTX ctx; // struktura pro kontext
    
    
    /* Sifrovani */
    EVP_EncryptInit(&ctx, cipher, key, iv);  // nastaveni kontextu pro sifrovani
    EVP_EncryptUpdate(&ctx,  publicCrypted, &tmpLength, publicMessage, otLength);  // sifrovani ot
    stLength += tmpLength;
    EVP_EncryptFinal(&ctx, publicCrypted + stLength, &tmpLength);  // dokonceni (ziskani zbytku z kontextu)
    stLength += tmpLength;
    
    printf("Public Message - Open Text: %s\nPublic Message - crypted: %s\n", publicMessage, publicCrypted);
    
    otLength = (int)strlen((const char*) secretMessage);
    stLength = 0;
    tmpLength = 0;
    
    /* Sifrovani  2*/
    EVP_EncryptInit(&ctx, cipher, key, iv);  // nastaveni kontextu pro sifrovani
    EVP_EncryptUpdate(&ctx,  secretCrypted, &tmpLength, secretMessage, otLength);  // sifrovani ot
    stLength += tmpLength;
    EVP_EncryptFinal(&ctx, secretCrypted + stLength, &tmpLength);  // dokonceni (ziskani zbytku z kontextu)
    stLength += tmpLength;
    
    printf("secret Message - Crypted: %s\n", secretCrypted);
    
    unsigned char newVariable[MSG_LENGTH + 1];
    memcpy(newVariable, secretCrypted, MSG_LENGTH + 1);
    
    unsigned char * right = (unsigned char *)malloc(sizeof(unsigned char) * (MSG_LENGTH + 1));
    right[MSG_LENGTH] = '\0';
    for ( int i = 0; i < MSG_LENGTH; i++)
    {
        right[i] = ( (publicCrypted[i]) ^ (publicMessage[i]));  // XOR is its own inverse
        right[i] ^= newVariable[i];
    }
    
    printf("Deciphered secret text: %s\n", right);
    
    if ( strcmp((const char *)right, (const char *)secretMessage) == 0)
    {
        printf("\n0 - Text was successfully deciphered!\n");
    }
    free(right);
    return;
    
}



int main(int argc, char *argv[]){
    printf("Prvni uloha:\n");
    firstTask(20);
    
    printf("\nDruha uloha:\n");
    secondTask();
    
    
    return 0;
}

Uživatelský avatar
Destroyer
VCKLAN TEAM
Příspěvky: 812
Registrován: čtv 13. srp 2009 13:50:15
Bydliště: Praha 12
Kontaktovat uživatele:

Re: cviceni 2

Příspěvek od Destroyer » stř 18. bře 2015 4:25:28

Kód: Vybrat vše

// BEZ-hex_to_ascii.cpp : Should work, give it a shot and report any bugs  FrankerZ
//

#include <string>
#include <cstdlib>
int main(int argc, char * argv[])
{
	char  hexa[64] = "6b61707061";
	unsigned char ascii[128];

	for (int i = 0, j = 0; i < strlen(hexa); i++, j+=2)
		sscanf(&hexa[j], "%02hhx", &ascii[i]);

	printf("%s\n", ascii);


// windows only
	system("PAUSE");
// end
	return 0;
}
You're pro or you're a noob. That's life

Uživatelský avatar
Destroyer
VCKLAN TEAM
Příspěvky: 812
Registrován: čtv 13. srp 2009 13:50:15
Bydliště: Praha 12
Kontaktovat uživatele:

Re: cviceni 2

Příspěvek od Destroyer » pon 23. bře 2015 3:58:09

Kód: Vybrat vše

#include <stdlib.h>
#include <openssl/evp.h>
#include <string.h>
//   gcc ukol2-zadani.c -std=c99 -Wall -lcrypto
int main(void) {
  unsigned char ot1[128] = "abcdefghijklmnopqrstuvwxyz0123";  // open text
  unsigned char st1[128];  // sifrovany text
  unsigned char ot2[128] = "oh gr8 b8 m8 i r8 8 of 8 no h8";  // open text max 30 znaku
  unsigned char st2[128];  // sifrovany text
  unsigned char key[EVP_MAX_KEY_LENGTH] = "klickterejnikdonikdyneprolomihahaha";  // klic pro sifrovani
  unsigned char iv[EVP_MAX_IV_LENGTH] = "strasnejvektor";  // inicializacni vektor
  const char cipherName[] = "RC4";
  const EVP_CIPHER * cipher;
 
  OpenSSL_add_all_ciphers();
  /* sifry i hashe by se nahraly pomoci OpenSSL_add_all_algorithms() */
  cipher = EVP_get_cipherbyname(cipherName);
  if(!cipher) {
    printf("Sifra %s neexistuje.\n", cipherName);
    exit(1);
  }
 
  int otLength = strlen((const char*) ot1);
  int stLength = 0;
  int tmpLength = 0;
 
  EVP_CIPHER_CTX ctx; // struktura pro kontext
 
  printf("OT: %s\n", ot1);
 
  /* Sifrovani */
  EVP_EncryptInit(&ctx, cipher, key, iv);  // nastaveni kontextu pro sifrovani
  EVP_EncryptUpdate(&ctx,  st1, &tmpLength, ot1, otLength);  // sifrovani ot
  stLength += tmpLength;
  EVP_EncryptFinal(&ctx, st1 + stLength, &tmpLength);  // dokonceni (ziskani zbytku z kontextu)
  stLength += tmpLength;
 
 
  /* Vypsani zasifrovaneho a rozsifrovaneho textu. */
  printf("ST: ");
  for(int i = 0; i < stLength; printf("%02x", st1[i]),i++);
      printf("\n");
 // ----
  printf("OT: %s\n", ot2);
  otLength = strlen((const char*) ot2);
  stLength = 0;
  tmpLength = 0;
    /* Sifrovani */
  EVP_EncryptInit(&ctx, cipher, key, iv);  // nastaveni kontextu pro sifrovani
  EVP_EncryptUpdate(&ctx,  st2, &tmpLength, ot2, otLength);  // sifrovani ot
  stLength += tmpLength;
  EVP_EncryptFinal(&ctx, st2 + stLength, &tmpLength);  // dokonceni (ziskani zbytku z kontextu)
  stLength += tmpLength;


  /* Vypsani zasifrovaneho a rozsifrovaneho textu. */
  printf("ST: ");
    for(int i = 0; i < stLength; printf("%02x", st2[i]),i++);
      printf("\n");
  exit(0);
}

Kód: Vybrat vše

#include <stdio.h>
#include <string.h>
#define ARRAY_SIZE 128
//   gcc ukol2-desifrovani.c -std=c99 -Wall
int main(void) {
  unsigned char ot[ARRAY_SIZE] = "abcdefghijklmnopqrstuvwxyz0123";      // znamy text
  char sthash[ARRAY_SIZE]; // hash znameho textu
  unsigned char st[ARRAY_SIZE];    // sifrovany text znameho textu

  char st2hash[ARRAY_SIZE]; // hash neznameho textu
  unsigned char st2[ARRAY_SIZE]; // sifrovany text neznameho textu

  printf("Zadejte sifru znameho textu:\n");
  fgets(sthash,ARRAY_SIZE,stdin);
  printf("Zadejte sifru neznameho textu:\n");
  fgets(st2hash,ARRAY_SIZE,stdin);
  /* Prevod hexadecimalniho zapisu do znakoveho (sthash-st, st2hash-st2) */
  for (int i = 0, j = 0; i < strlen(sthash); i++, j+=2)
      sscanf(&sthash[j], "%02hhx", &st[i]);
  for (int i = 0, j = 0; i < strlen(st2hash); i++, j+=2)
      sscanf(&st2hash[j], "%02hhx", &st2[i]);  
 
  int length = strlen((char *)ot);
  unsigned char * decrypted = (unsigned char *)calloc(sizeof(unsigned char) * (length + 1),sizeof(unsigned char));
  for (int i = 0; i < length; i++)
    {
      decrypted[i] = ( (st[i]) ^ (ot[i]));
      decrypted[i] ^= st2[i];
    }
  printf("Desifrovany tajny text: \"%s\"\n", decrypted);
 
  free(decrypted);
  return 0;
}
You're pro or you're a noob. That's life

Odpovědět