Advertisement
Guest User

Untitled

a guest
Apr 29th, 2016
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.55 KB | None | 0 0
  1. /*
  2. * To change this license header, choose License Headers in Project Properties.
  3. * To change this template file, choose Tools | Templates
  4. * and open the template in the editor.
  5. */
  6.  
  7. package javaapplication9;
  8.  
  9. import java.util.Scanner;
  10.  
  11. /**
  12. *
  13. * @author sjors
  14. */
  15. public class JavaApplication9 {
  16.  
  17. /**
  18. * @param args the command line arguments
  19. */
  20. public static void main(String[] args) {
  21. Scanner key = new Scanner(System.in);
  22. int Key = GenKey();
  23. int[] encrytedMessage;
  24. String Message, receivedMessage;
  25. System.out.println("The key used is: " + Key);
  26. System.out.println("message you whish to send:");
  27. Message = key.nextLine();
  28. System.out.println("Message before encryption: " + Message);
  29. encrytedMessage = Encrypt(Message, Key);
  30. System.out.println("Message after encryption: ");
  31. for(int i=0; i < encrytedMessage.length; i++){
  32. System.out.print(encrytedMessage[i]);
  33.  
  34. }
  35. System.out.println();
  36. receivedMessage = Decrypt(encrytedMessage, Key);
  37. System.out.println("Decrypted message is: " + receivedMessage);
  38. }
  39. public static int GenKey(){
  40. double Key;
  41. do{
  42. Key = Math.random() * 9999;
  43. }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
  44.  
  45. return (int) Key;
  46.  
  47. }
  48. public static int[] Encrypt(String message, int Key){
  49. //First decode to message to numbers
  50. int encryptedMessage = 0;
  51. int length = message.length();
  52. int[] arrayMessage = new int[length];
  53. for (int i=0; i < length;i++){
  54. arrayMessage[i] = (int)message.charAt(i);
  55. //Encode each dataslot. add more operations(and more complicated operations) to increase security
  56. arrayMessage[i] *= Key;
  57. }
  58. return arrayMessage;
  59.  
  60. }
  61. public static String Decrypt(int[] encryptedMessage, int Key){
  62. char[] decryptedMessage = new char[encryptedMessage.length];
  63. for (int i=0; i < encryptedMessage.length;i++){
  64. //Undo all the operations we did when we encrypted.
  65. encryptedMessage[i] /= Key;
  66. decryptedMessage[i] = (char)encryptedMessage[i];//cast int's back to chars
  67. }
  68. String str = String.valueOf(decryptedMessage);//return the array of chars into a string
  69. return str;
  70. }
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement