Created
February 13, 2022 10:58
-
-
Save Anass-ABEA/7b4c6db9b4edc5ac5a8bc4924d186d81 to your computer and use it in GitHub Desktop.
DES
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(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment