Last active
February 13, 2022 10:48
-
-
Save Anass-ABEA/032c57914ffb4de289f5cf72e1c97623 to your computer and use it in GitHub Desktop.
DES algorithm in JAVA https://www.youtube.com/watch?v=XffVSIFRv3A&ab_channel=WhiteBatCodes
This file contains hidden or 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.Cipher; | |
import javax.crypto.KeyGenerator; | |
import javax.crypto.SecretKey; | |
import javax.crypto.spec.IvParameterSpec; | |
/** | |
* DES/CBC/NoPadding (56) | |
* DES/CBC/PKCS5Padding (56) * | |
* DES/ECB/NoPadding (56) | |
* DES/ECB/PKCS5Padding (56) * | |
*/ | |
public class DES { | |
private final SecretKey key; | |
private Cipher encCipher; | |
private Cipher decCipher; | |
public DES() throws Exception { | |
this.key = generateKey(); | |
initCiphers(); | |
} | |
public DES(SecretKey key) throws Exception { | |
this.key = key; | |
initCiphers(); | |
} | |
private void initCiphers() throws Exception { | |
encCipher = Cipher.getInstance("DES/CBC/PKCS5Padding"); | |
decCipher = Cipher.getInstance("DES/CBC/PKCS5Padding"); | |
encCipher.init(Cipher.ENCRYPT_MODE, key); | |
decCipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(encCipher.getIV())); | |
} | |
public byte[] encrypt(String message) throws Exception { | |
return encCipher.doFinal(message.getBytes()); | |
} | |
public String decryt(byte[] messsage) throws Exception { | |
return new String(decCipher.doFinal(messsage)); | |
} | |
public static SecretKey generateKey() throws Exception { | |
return KeyGenerator.getInstance("DES").generateKey(); | |
} | |
} |
This file contains hidden or 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.SecretKey; | |
import java.util.Base64; | |
public class Main { | |
public static void main(String[] args) throws Exception { | |
SecretKey key = DES.generateKey(); | |
System.out.print("Encrypt/Decrypt Key: "); | |
System.out.println(encode(key.getEncoded())); | |
System.out.println(); | |
String message = "The X Coders"; | |
DES des = new DES(key); | |
String encryptedMessage = encode(des.encrypt(message)); | |
System.out.println("Encrypted Message: " + encryptedMessage); | |
System.out.println("Decrypted Message: " + des.decryt(decoder(encryptedMessage))); | |
} | |
public static String encode(byte[] data) { | |
return Base64.getEncoder().encodeToString(data); | |
} | |
public static byte[] decoder(String data) { | |
return Base64.getDecoder().decode(data); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment