Similar ans (Help): B.3 The field of cryptography is concerned with coding data
ID: 3799380 • Letter: S
Question
Similar ans (Help):
B.3 The field of cryptography is concerned with coding data to make it difficult for unauthorized users to read. Consider a TEA algorithm to encode and decode a message. The JAVA program should 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 first digit with the third, and swap the second digit with the fourth and print the encrypted integer Develop a JAVA program to encode and decode any given four digit number and verify with the original message. What are the limitations of your program? Example: Original message 1 2 3 4 Encoded message: 0189 Decoded message: 1 2 3 4 B3.1 Introduction and problem definition B3.2 Problem solving approach B3.3 Implementation B3.4 Results and Analysis B3.5 ConclusionExplanation / Answer
String encode(String pText) {
if (pText.length() == 4 && isNum(pText)) {
String cText ="";
for(int i=0; i<4; i++) {
int temp = ((int)(pText.charAt(0)-'0')+7)%10;
cText += temp;
}
char[] carr = cText.ToCharArray();
char tmp = carr[0];
carr[0] = carr[2];
carr[2] = tmp;
tmp = = carr[1];
carr[1] = carr[3];
carr[3] = tmp;
return new String(carr);
}
return null;
}
String decode(String cText) {
if (cText.length() == 4 && isNum(cText)) {
String pText ="";
for(int i=0; i<4; i++) {
int temp = ((int)(cText.charAt(0)-'0')+3)%10;
pText += temp;
}
char[] carr = pText.ToCharArray();
char tmp = carr[0];
carr[0] = carr[2];
carr[2] = tmp;
tmp = = carr[1];
carr[1] = carr[3];
carr[3] = tmp;
return new String(carr);
}
return null;
}
boolean isNum(String num) {
try {
Integer.parseInt(num);
} catch (Exception e) {
return false;
}
return true;
}
Limitation:
cannot parse number with blank spaces in between.
Problem-solving approach:
to check if the string is a number, We try to parse it to Integer and if we get no exception, we return true, else we return false;
next as said in question we add 7 and extract the last digit during encoding. During decoding the simplest way is to add 3 and extract the last digit. This is exact inverse function of the encoding process.
in java string class we cannot manipulate characters, so we convert it to char array.
Implementation:
public static void main(String[] args) {
cText = class.encode("1597");
//consume cText;
pText = class.decode(cText);
if (pText.equals("1597"))
//success;
}
Result and analysis:
you try it
Conclusion:
Works well with strings of length four and that can be parsed to Integer.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.