package list1; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.KeyGenerator; import javax.crypto.NoSuchPaddingException; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; public class CW1 { public static byte[] getKey(int bytes) throws NoSuchAlgorithmException{ KeyGenerator kGen = KeyGenerator.getInstance("DES"); byte[] key = new byte[bytes]; int i = 0; while(i < bytes){ kGen.init(56); SecretKey sKey = kGen.generateKey(); byte[] rawKey = sKey.getEncoded(); for(int j = 0; (j < rawKey.length)&(j+i < key.length) ; j++){ key[j+i] = rawKey[j]; } i = i + 7; } return key; } public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { /* * d??ugo??Ä? wiadomo??Ä? musi byÄ? podzielna przez 8 * ??eby mo??na by??o u??yÄ? NoPadding */ byte[] input = "WiadomoscDoZakodowania!!".getBytes(); byte[] encrypted = null; byte[] decrypted = null; KeyGenerator kGen = KeyGenerator.getInstance("DES"); SecretKey sKey = kGen.generateKey(); byte[] keyBytes = sKey.getEncoded(); Cipher cipher = Cipher.getInstance("DES/ECB/NoPadding"); cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(keyBytes, "DES")); encrypted = cipher.doFinal(input); cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(keyBytes, "DES")); decrypted = cipher.doFinal(encrypted); print(input); print(encrypted); print(decrypted); System.out.println(Arrays.equals(input, decrypted)); } public static void print(byte[] b) { System.out.println(new String(b)); System.out.println("Length: " + b.length * 8); System.out.println("---------------"); } } |
Java Szyfrowanie DES/ECB/NoPadding
Napisz odpowiedź