Java Szyfrowanie DES/ECB/NoPadding

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("---------------");
	}
}

Dodaj komentarz

Twój adres e-mail nie zostanie opublikowany. Pola, których wypełnienie jest wymagane, są oznaczone symbolem *

Możesz użyć następujących tagów oraz atrybutów HTML-a: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>