Algorithm/📚 Concept

컴퓨터 알고리즘 실습2) 대칭 암호화 고전방식 / 확장된 유클리드

키깡 2019. 10. 9.
728x90

1. 문자열 "Hello, I love you. Please love Woongsup!!!"을 XOR을 사용한 암호화 방법으로 암호화 및 복호화 하는 프로그램을 구현하시오. 여기서 key 값은 0x5 (00000101)로 한다. 여기서 Woongsup은 여러분들의 영문 이름으로 대체하도록 한다.

//고전방법으로 문자열 암호화 하기 in C
#include <stdio.h>
#define MLENGTH 55

unsigned int do_XOR(unsigned int c, unsigned int key) //c가 문자, key가 비밀키
{return c^key;}

char message[] = {"Welcome to Algorithm Practices, this is Woongsup Kim!"};

unsigned int encryption[MLENGTH]; //encryptio이 암호화 하는 배열
char decryption[MLENGTH]; //decryption이 복호화 하는 배열

int key = 0x5; //비밀키 key 초기화

int main(void){
	int str;
	str=sizeof(message);
	char ch; //message
	int c; //전역변수 c

	int i;
	int xor; //xor결과

	for(i=0;i<str-1;i++)
	{
			ch=message[i];
			c=(unsigned int)ch;
			xor=do_XOR(c,key);
			encryption[i]=xor;
			}
	int k;
			printf("*encryption 배열*:");
			for(k=0;k<str-1;k++)
			printf("%d,",encryption[k]);
			printf("\n");
			for(i=0;i<str-1;i++)
	{int wd;
		wd=encryption[i];
		xor=do_XOR(wd,key);
		char word;
		word=(char) xor;
		decryption[i]=word;
			}
			printf("\n");
			printf("*decryption 배열*:");
			for(k=0;k<str-1;k++)
			printf("%c",decryption[k]);
		}

 
2. 키보드에서 두 수 a,b를 입력받아, x,y,d를 구하는 프로그램을 만드시오. (확장된 유클리드 방법 사용)

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

struct _node /*x,y,d저장 구조체*/
{
    int first;
    int second;
    int third;
};

struct _node *extended_Euclid(int a, int b)
{
    struct _node *n1, *n2, *n3;
    n1 = (struct _node *)malloc(sizeof(struct _node));
    n2 = (struct _node *)malloc(sizeof(struct _node));
    n3 = (struct _node *)malloc(sizeof(struct _node));
    int nc;
    if(b == 0) {
        n1->first = 1;
        n1->second = 0;
        n1->third = a;
        return n1;
    }
    else {
        n2=extended_Euclid(b,a%b);
        int c;
        c=a/b;
        n3->first=n2->second;
        n3->second=(n2->first)-(c*(n2->second));

        n2->first=n3->second;
        n2->second=n3->first-c*(n3->second);
        n3->third=n2->third;
        return n3;
}
}

void main(void)
{
    struct _node *n;
    int u; int v;

        printf("Type two positive integers -> ");
        scanf("%d %d", &u, &v);

        while(u < 0  ||  v < 0)
        {printf("Type two positive integers, please.");
            scanf("%d %d", &u, &v);// if inputs are invalid, then do nothing.
        }
        n = extended_Euclid(u, v);

        printf("x is %d, y is %d, and d is %d\n ", n->first, n->second, n->third);
}

댓글