Criptografia AES com chave estática

0 respostas
S

Oi. Venho tentando fazer JCE funcionar com o exemplo a seguir usando AES em modo ECB (sim, ECB não deveria ser usado, por ser fraco, mas é o que eu devo utilizar): dado um String representado pelos bytes (em hex) 546578746F2070617261207465737465 e uma chave 6573736173656E686165686672616361, o programa deve prover os bytes criptografados A506A19333F306AC2C62CBE931963AE7. Eu usei um serviço online de criptografia para confirmar que o descrito acima está correto. Entretanto, não consigo fazer dar certo em Java:

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
 
public class AESTest {
	public static String asHex(byte buf[]) {
		StringBuffer strbuf = new StringBuffer(buf.length * 2);
		int i;
 
		for (i = 0; i < buf.length; i++) {
			if (((int) buf[i] & 0xff) < 0x10) {
				strbuf.append("0");
			}
 
			strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
		}
 
		return strbuf.toString();
	}
 
	public static void main(String[] args) throws Exception {
		String keyString = "Texto para teste";
		// 546578746F2070617261207465737465 (Hex)
		byte[] key = keyString.getBytes("UTF-8");
		System.out.println(asHex(key).toUpperCase());
 
		String clearText = "essasenhaehfraca";
		// ZXNzYXNlbmhhZWhmcmFjYQ== (Base64)
		// 6573736173656E686165686672616361 (Hex)
		byte[] clear = clearText.getBytes("UTF-8");
		System.out.println(asHex(clear).toUpperCase());
 
		SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
		// PKCS5Padding or NoPadding
		Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
		cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
 
		byte[] encrypted = cipher.doFinal(clear);
		System.out.println(asHex(encrypted).toUpperCase());
	}
}

Os exemplos que eu encontrei geram uma chave ao invés de utilizarem uma chave estática pré-definida. Isso não deveria estar sendo um problema, mas pelo resultado obtido não ser o "correto", está.

Alguém pode me ajudar? Obrigado.

Criado 7 de junho de 2007
Respostas 0
Participantes 1