Шифр цезаря программа java

Caesar Cipher Program in Java with Output

Caesar cipher technique was founded by Julius caesar. Before looking at the caesar cipher program in java with output for encryption and decryption, first, we need to understand the terms plaintext and ciphertext.

What is plaintext and ciphertext?

plaintext is the input message given by user. In other words, message that needs to be encrypted.

ciphertext is the encrypted message. In other words, message after applying the caesar cipher technique.

What is Caesar cipher?

Caesar cipher is one of the simplest encryption technique. It is also known as the shift cipher, Caesar’s cipher, Caesar shift or Caesar’s code. Caesar cipher is a type of substitution cipher.

By using this cipher technique we can replace each letter in the plaintext with different one a fixed number of places up or down the alphabet.

With right shift of 3:

With right shift of 2:

plaintext : Java Hungry Blog
ciphertext : Lcxc Jwpita Dnqi

As you can see for the above example «Java Hungry Blog» each character in plain text is shifted by 2 as J become L , a become c , v become x and so on.

Note : You can use either left shift or right shift but not both in same text.

If we want to see Caesar cipher in mathematical way, then formula to get encrypted letter will be :

where,
n is the number of positions we need to shift plaintext characters
x is the place value of original letter
e is the place value of encrypted letter

On the other hand, we will use the below formula to decrypt each letter.

  1. Input : String plaintext
  2. Input : An integer between 0 and 25 representing the right shift of the character or, an integer between -25 and -1 representing the left shift of the characters.
  3. Traverse each character in the plaintext one at a time
  4. Transform the given character depending on encryption or decryption.
  5. print the ciphertext.
import java.util.*; public class CaesarCipherProgram  public static void main(String args[])  Scanner sc = new Scanner(System.in); System.out.println(" Input the plaintext message : "); String plaintext = sc.nextLine(); System.out.println(" Enter the value by which each character in the plaintext message gets shifted : "); int shift = sc.nextInt(); String ciphertext = ""; char alphabet; for(int i=0; i  plaintext.length();i++)  // Shift one character at a time alphabet = plaintext.charAt(i); // if alphabet lies between a and z if(alphabet >= 'a' && alphabet  'z')  // shift alphabet alphabet = (char) (alphabet + shift); // if shift alphabet greater than 'z' if(alphabet > 'z')  // reshift to starting position alphabet = (char) (alphabet+'a'-'z'-1); > ciphertext = ciphertext + alphabet; > // if alphabet lies between 'A'and 'Z' else if(alphabet >= 'A' && alphabet  'Z')  // shift alphabet alphabet = (char) (alphabet + shift); // if shift alphabet greater than 'Z' if(alphabet > 'Z')  //reshift to starting position alphabet = (char) (alphabet+'A'-'Z'-1); > ciphertext = ciphertext + alphabet; > else  ciphertext = ciphertext + alphabet; > > System.out.println(" ciphertext : " + ciphertext); > > 

Input the plaintext message : Java Hungry Blog
Enter the value by which each character in the plaintext message gets shifted : 2
ciphertext : Lcxc Jwpita Dnqi

Simple Caesar Cipher Program in Java for Decryption

import java.util.*; public class CaesarCipherProgram  public static void main(String args[])  Scanner sc = new Scanner(System.in); System.out.println(" Input the ciphertext message : "); String ciphertext = sc.nextLine(); System.out.println(" Enter the shift value : "); int shift = sc.nextInt(); String decryptMessage = ""; for(int i=0; i  ciphertext.length();i++)  // Shift one character at a time char alphabet = ciphertext.charAt(i); // if alphabet lies between a and z if(alphabet >= 'a' && alphabet  'z')  // shift alphabet alphabet = (char) (alphabet - shift); // shift alphabet lesser than 'a' if(alphabet  'a')  //reshift to starting position alphabet = (char) (alphabet-'a'+'z'+1); > decryptMessage = decryptMessage + alphabet; > // if alphabet lies between A and Z else if(alphabet >= 'A' && alphabet  'Z')  // shift alphabet alphabet = (char) (alphabet - shift); //shift alphabet lesser than 'A' if (alphabet  'A')  // reshift to starting position alphabet = (char) (alphabet-'A'+'Z'+1); > decryptMessage = decryptMessage + alphabet; > else  decryptMessage = decryptMessage + alphabet; > > System.out.println(" decrypt message : " + decryptMessage); > > 

Input the ciphertext message : Lcxc Jwpita Dnqi
Enter the shift value : 2
decrypt message : Java Hungry Blog

That’s all for the post caesar cipher program in java with output. If you have any questions then please mention in the comments below.

Image Credits : Cepheus [Public domain], from Wikimedia Commons
Matt_Crypto [Public domain], via Wikimedia Commons

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

A Caesar Cipher Implementation in Java

mckeydonelly/caesar-s-cipher

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Утилита реализующая шифр Цезаря на java. Используемые фреймворки и библиотеки:

$ cd caesar-s-cipher $ mvn package 
$ java -jar ./target/caesar-s-cipher-1.0.jar 
  • Программа использует алфавит а-я, А-Я и знаки пунктуации (‘.’, ‘,’, ‘«’, ‘»’, ‘»‘, »’, ‘:’, ‘;’, ‘-‘, ‘!’, ‘?’, ‘ ‘).
  • Ключ может быть только положительным целым числом
  • Максимальный ключ ограничен Integer.MAX_VALUE

Шифр Цезаря — это шифр подстановки: в нем каждый символ в открытом тексте заменяют на символ, который находится на некотором постоянном числе позиций левее или правее него в алфавите.

Допустим, мы устанавливаем сдвиг на 3. В таком случае А заменится на Г, Б станет Д, и так далее.

В корневом пакете проекта com.caesar находится класс Main, содержащий в себе точку входа в приложение.

В пакете crypto содержатся классы:

CaesarCypher — контроллер, который принимает все команды утилиты и внутренние вспомогательные:

CryptoType — перечисление, содержащее тип действия для вычисления смещения

Описание внешнего программного интерфейса

Для шифрования текста необходимо выполнить команду:

java -jar caesar-s-cipher-1.0.jar encrypt

  • файл с текстом для шифрования
  • путь к файлу для сохранения зашифрованного текста
  • — ключ для шифрования

java -jar caesar-s-cipher-1.0.jar encrypt ./testData/encrypt/testSrc.txt ./testData/encrypt/testDst.txt 158

Start encryption. Validating source or representative file. Validating desination file. Encryption is successfully ended. 

При возникновении проблем с доступом к файлам программа сообщит об ошибке.

Для расшифровки текста необходимо выполнить команду:

java -jar caesar-s-cipher-1.0.jar decrypt

  • файл с зашифрованным текстом
  • путь к файлу для сохранения расшифрованного текста
  • — ключ для расшифровки

java -jar caesar-s-cipher-1.0.jar decrypt ./testData/encrypt/testSrc.txt ./testData/encrypt/testDst.txt 158

Start decryption. Validating source or representative file. Validating desination file. Decryption is successfully ended. 

При возникновении проблем с доступом к файлам программа сообщит об ошибке.

При использовании данной опции программа перебирает все возможные ключи и сравниваем кол-во вхождений на каждом круге со словарем, сформированным из репрезентативного текста.

Для выполнения взлома ключа зашифрованного текста необходимо выполнить команду: java -jar caesar-s-cipher-1.0.jar brute-force

  • файл с зашифрованным текстом
  • файл с незашифрованным репрезентативным текстом
  • путь к файлу для сохранения расшифрованного текста

java -jar caesar-s-cipher-1.0.jar brute-force ./testData/brute-force/testSrc.txt ./testData/brute-force/testRepresentative.txt ./testData/brute-force/testDst.txt

Start brute-force. Validating source or representative file. Validating source or representative file. Validating desination file. Fill dictionary from representative file. Start brute-force by all keys. Print matches by key: Key: 0. Matches: 0 Key: 1. Matches: 0 Key: 2. Matches: 123 Key: 3. Matches: 6 Key: 4. Matches: 0 Key: 5. Matches: 0 Key: 6. Matches: 0 Key: 7. Matches: 0 Key: 8. Matches: 1 Key: 9. Matches: 0 Key: 10. Matches: 0 Key: 11. Matches: 1 Key: 12. Matches: 1 Key: 13. Matches: 0 Key: 14. Matches: 2 Key: 15. Matches: 1 Key: 16. Matches: 0 Key: 17. Matches: 0 Key: 18. Matches: 3 Key: 19. Matches: 0 Key: 20. Matches: 0 Key: 21. Matches: 1 Key: 22. Matches: 2 Key: 23. Matches: 2 Key: 24. Matches: 0 Key: 25. Matches: 0 Key: 26. Matches: 0 Key: 27. Matches: 0 Key: 28. Matches: 0 Key: 29. Matches: 0 Key: 30. Matches: 0 Key: 31. Matches: 0 Key: 32. Matches: 0 Key: 33. Matches: 0 Key: 34. Matches: 3 Key: 35. Matches: 0 Key: 36. Matches: 0 Key: 37. Matches: 0 Key: 38. Matches: 0 Key: 39. Matches: 0 Key: 40. Matches: 0 Key: 41. Matches: 0 Key: 42. Matches: 0 Key: 43. Matches: 0 Key: 44. Matches: 0 Key: 45. Matches: 0 Key: 46. Matches: 0 Key: 47. Matches: 0 Key: 48. Matches: 0 Key: 49. Matches: 0 Key: 50. Matches: 0 Key: 51. Matches: 0 Key: 52. Matches: 0 Key: 53. Matches: 0 Key: 54. Matches: 0 Key: 55. Matches: 0 Key: 56. Matches: 0 Key: 57. Matches: 0 Key: 58. Matches: 0 Key: 59. Matches: 0 Key: 60. Matches: 0 Key: 61. Matches: 0 Key: 62. Matches: 0 Key: 63. Matches: 0 Key: 64. Matches: 0 Key: 65. Matches: 0 Key: 66. Matches: 0 Key: 67. Matches: 0 Key: 68. Matches: 0 Key: 69. Matches: 0 Key: 70. Matches: 0 Key: 71. Matches: 0 Key: 72. Matches: 0 Key: 73. Matches: 0 Key: 74. Matches: 0 Key: 75. Matches: 0 Key: 76. Matches: 0 Key: 77. Matches: 0 Key: 78. Matches: 0 Best key: 2. Using this key for the final decryption. Start decryption. Validating source or representative file. Validating desination file. Decryption is successfully ended. Brute-force is successfully ended. 

При возникновении проблем с доступом к файлам программа сообщит об ошибке.

Источник

Читайте также:  Java проверить существует ли директория
Оцените статью