In: Computer Science
Playing with encryption:
Write a program that will read a four-digit integer entered by the user and encrypt it as follows: Replace each digit with the result of adding 7 to the digit and getting the remainder after dividing the new value by 10. Then swap the second digit with the fourth. Finally, print the original number and its encrypted one. Now reverse the process. Read an encrypted integer and decrypt it by reversing the algorithm to obtain the original number. Print out both the encrypted and decrypted integer.
Programming Language is not Mentioned so I am doing it in c :
C Language Code:
#include<stdio.h>
int main(){
int num,rem,option,dNum,oNum=0,n=1000,sec,four;
//variables for storing the number,remainder , reading
option and duplicate number dNum for storing num output number
oNum
printf("Enter 1.Encryption 2.Decryption");
//reading which thing we do encryption or
decryption
scanf("%d",&option);
printf("Enter four digit Number");
scanf("%d",&num);
dNum=num;
if(option==1){
while(dNum!=0){
//getting the
first number and add 7 to it and get remainter after that when
divided by 10
rem=dNum/n;
rem=(rem+7)%10;
oNum=oNum*10+rem;
dNum=dNum%n;
if(n==100){
//storing second number
sec=rem;
}else
if(n==1){
//storing fourth number
four=rem;
}
n=n/10;
}
printf("%d\t
%d",sec,four);
printf(" Number is
%d\n",oNum);
//making the second number zero and
making fourth number there in that place
oNum=oNum-(sec*100)+(four*100);
//making the fourth number zero and
making second number there in that place
oNum=oNum-(four*1)+sec;
printf("Original Number
%d\n",num);
printf("Encrypted Number is
%d",oNum);
}else{
while(dNum!=0){
//getting the
first number and add 7 to it and get remainter after that when
divided by 10
rem=dNum/n;
//reason for
adding the +3 and substracting seven is explained in the pic
if(rem>=7)
rem=(rem-7)%10;
else{
rem=rem+3;
}
oNum=oNum*10+rem;
dNum=dNum%n;
if(n==100){
//storing second number
sec=rem;
}else
if(n==1){
//storing fourth number
four=rem;
}
n=n/10;
}
//making the second number zero and
making fourth number there in that place
oNum=oNum-(sec*100)+(four*100);
//making the fourth number zero and
making second number there in that place
oNum=oNum-(four*1)+sec;
printf("Decrypted Number
%d\n",num);
printf("Original Number is
%d",oNum);
}
return 0;
}
Reason for adding +3 and substracting -7 Explanation:
OUTPUT:
DECRYPTION OUTPUT: