Last active
October 2, 2021 19:13
-
-
Save kabinpokhrel/98cf87349e723cc096cd60ada33f7b62 to your computer and use it in GitHub Desktop.
DES Cipher
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import javax.crypto.*; | |
import javax.crypto.spec.DESKeySpec; | |
import java.security.InvalidKeyException; | |
import java.security.NoSuchAlgorithmException; | |
import java.security.spec.InvalidKeySpecException; | |
import java.util.Arrays; | |
import java.util.Scanner; | |
public class DesCrypto { | |
public static void main(String[] args) throws | |
NoSuchAlgorithmException, | |
NoSuchPaddingException, | |
InvalidKeyException, | |
IllegalBlockSizeException, | |
BadPaddingException, | |
InvalidKeySpecException { | |
// Declare Scanner object | |
Scanner sc = new Scanner(System.in); | |
System.out.println("Enter the password to encrypt the characters: "); | |
String password = sc.nextLine(); | |
// Create an array of bytes from the password | |
byte[] passwordBytes = password.getBytes(); | |
// Generate DESKeySpec object from the password bytes | |
DESKeySpec dks = new DESKeySpec(passwordBytes); | |
// Create an object of SecretKeyFactory for "DES" Encryption | |
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); | |
// generate the secretKey from the SecretKeyFactory using the DESKeySpec above | |
SecretKey sk = keyFactory.generateSecret(dks); | |
// Declare an object of the class Cipher for "DES" | |
Cipher desCipher = Cipher.getInstance("DES"); | |
// Setting the object into encryption mode | |
desCipher.init(Cipher.ENCRYPT_MODE, sk); | |
// Ask user for string of characters | |
System.out.println("Enter string of characters: "); | |
String userText = sc.nextLine(); | |
// convert the characters to bytes array | |
byte[] userTextByte = userText.getBytes(); | |
// encrypt the entered text from the byte array above | |
byte[] encryptedText = desCipher.doFinal(userTextByte); | |
System.out.println(Arrays.toString(encryptedText)); | |
// initialize the Cipher object to DECRYPT_MODE using the using above SecretKey object | |
desCipher.init(Cipher.DECRYPT_MODE, sk); | |
// decipher the encrypted text | |
byte[] decryptedText = desCipher.doFinal(encryptedText); | |
//System.out.println(Arrays.toString(decryptedText)); | |
System.out.println("Original Text: " + new String(decryptedText)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment