Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
- package javaapplication9;
- import java.util.Scanner;
- /**
- *
- * @author sjors
- */
- public class JavaApplication9 {
- /**
- * @param args the command line arguments
- */
- public static void main(String[] args) {
- Scanner key = new Scanner(System.in);
- int Key = GenKey();
- int[] encrytedMessage;
- String Message, receivedMessage;
- System.out.println("The key used is: " + Key);
- System.out.println("message you whish to send:");
- Message = key.nextLine();
- System.out.println("Message before encryption: " + Message);
- encrytedMessage = Encrypt(Message, Key);
- System.out.println("Message after encryption: ");
- for(int i=0; i < encrytedMessage.length; i++){
- System.out.print(encrytedMessage[i]);
- }
- System.out.println();
- receivedMessage = Decrypt(encrytedMessage, Key);
- System.out.println("Decrypted message is: " + receivedMessage);
- }
- public static int GenKey(){
- double Key;
- do{
- Key = Math.random() * 9999;
- }while(Key < 1000 || Key % 2 == 0);//To ensure more safety on the encryption we make sure the random Key is above 1000, also we are making sure that the key is an odd number
- return (int) Key;
- }
- public static int[] Encrypt(String message, int Key){
- //First decode to message to numbers
- int encryptedMessage = 0;
- int length = message.length();
- int[] arrayMessage = new int[length];
- for (int i=0; i < length;i++){
- arrayMessage[i] = (int)message.charAt(i);
- //Encode each dataslot. add more operations(and more complicated operations) to increase security
- arrayMessage[i] *= Key;
- }
- return arrayMessage;
- }
- public static String Decrypt(int[] encryptedMessage, int Key){
- char[] decryptedMessage = new char[encryptedMessage.length];
- for (int i=0; i < encryptedMessage.length;i++){
- //Undo all the operations we did when we encrypted.
- encryptedMessage[i] /= Key;
- decryptedMessage[i] = (char)encryptedMessage[i];//cast int's back to chars
- }
- String str = String.valueOf(decryptedMessage);//return the array of chars into a string
- return str;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement