He utilizado el siguiente código de OpenSSL para hacer un cifrado AES, que se descifra con éxito en el sitio web de Impuestos
openssl rand 48 > 48byterandomvalue.bin
hexdump /bare 48byterandomvalue.bin > 48byterandomvalue.txt
set /a counter=0
for /f "tokens=* delims= " %%i in (48byterandomvalue.txt) do (
set /a counter=!counter!+1
set var=%%i
if "!counter!"=="1" (set aes1=%%i)
if "!counter!"=="2" (set aes2=%%i)
if "!counter!"=="3" (set iv=%%i)
)
set result1=%aes1:~0,50%
set result1=%result1: =%
set result2=%aes2:~0,50%
set result2=%result2: =%
set aeskey=%result1%%result2%
set initvector=%iv:~0,50%
set initvector=%initvector: =%
openssl aes-256-cbc -e -in PAYLOAD.zip -out PAYLOAD -K %aeskey% -iv %initvector%
openssl rsautl -encrypt -certin -inkey test_public.cer -in
48byterandomvalue.bin -out 000000.00000.TA.840_Key
Pero quería hacer lo mismo este en Java como parte de la migración, así que utiliza los javax.crypto y java.security bibliotecas pero el descifrado está fallando al cargar el archivo en el sitio web de Impuestos
//creating the random AES-256 secret key
SecureRandom srandom = new SecureRandom();
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(256);
SecretKey secretKey = keyGen.generateKey();
byte[] aesKeyb = secretKey.getEncoded();
//creating the initialization vector
byte[] iv = new byte[128/8];
srandom.nextBytes(iv);
IvParameterSpec ivspec = new IvParameterSpec(iv);
byte[] encoded = Files.readAllBytes(Paths.get(filePath));
str = new String(encoded, StandardCharsets.US_ASCII);
//fetching the Public Key from certificate
FileInputStream fin = new FileInputStream("test_public.cer");
CertificateFactory f = CertificateFactory.getInstance("X.509");
X509Certificate certificate = (X509Certificate)f.generateCertificate(fin);
PublicKey pk = certificate.getPublicKey();
//encrypting the AES Key with Public Key
Cipher RSACipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
RSACipher.init(Cipher.ENCRYPT_MODE, pk);
byte[] RSAEncrypted = RSACipher.doFinal(aesKeyb);
FileOutputStream out = new FileOutputStream("000000.00000.TA.840_Key");
out.write(RSAEncrypted);
out.write(iv);
out.close();
Además, la clave AES generada en java es diferente de la generada a través de openssl. Pueden ustedes por favor ayuda.
EDIT 1: A continuación se muestra el código para AES encrpytion utilizado:
Cipher AESCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
AESCipher.init(Cipher.ENCRYPT_MODE, secretKey, ivspec);
byte[] AESEncrypted = AESCipher.doFinal(str.getBytes("UTF-8"));
String encryptedStr = new String(AESEncrypted);
Los datos que guión y cifrar Java de código con RSA difieren:
El script genera de forma aleatoria 48-bytes-secuencia y lo almacena en el archivo
48byterandomvalue.bin
. Los primeros 32 bytes se utilizan como clave AES, los últimos 16 bytes como IV. Clave y IV se utilizan para cifrar el archivoPAYLOAD.zip
con AES-256 en el modo CBC-y almacenarlo como archivoPAYLOAD
. El archivo48byterandomvalue.bin
está cifrado con RSA y se almacena como archivo000000.00000.TA.840_Key
.En el Java-código, un azar clave de 32 bytes AES y una aleatoria de 16 bytes de IV se generan. Ambos se utilizan para realizar el cifrado con AES-256 en CBC-mode. La clave AES se cifra con RSA, concatena con el IV no cifrado y el resultado se almacena en el archivo
000000.00000.TA.840_Key
.El contenido del archivo
000000.00000.TA.840_Key
es diferente para la escritura y Java de código. Para el Java de código para generar elfile 000000.00000.TA.840_Key
con el guión en la lógica, la no cifrado AES clave debe ser concatenado con el IV sin cifrar y este resultado debe ser encriptado con RSA:... //byte[] aesKeyb byte-array with random 32-bytes key //byte[] iv byte-array with random 16-bytes iv byte[] key_iv = new byte[aesKeyb.length + iv.length]; System.arraycopy(aesKeyb, 0, key_iv, 0, aesKeyb.length); System.arraycopy(iv, 0, key_iv, aesKeyb.length, iv.length); ... byte[] RSAEncrypted = RSACipher.doFinal(key_iv); FileOutputStream out = new FileOutputStream("000000.00000.TA.840_Key"); out.write(RSAEncrypted); out.close(); ...
Nota: El IV no tiene que ser secreto y por lo tanto no necesita ser cifrado. El cifrado sólo es necesario para generar el resultado de la secuencia de comandos en el código Java.
Otro problema se refiere a la conversión de los datos binarios arbitrarios en cadenas. En general, esto conduce a datos dañados si la codificación no es adecuado (por ejemplo ASCII o UTF8). Por lo tanto
... byte[] encoded = Files.readAllBytes(Paths.get(filePath)); str = new String(encoded, StandardCharsets.US_ASCII); // Doesn't work: ASCII (7-bit) unsuitable for arbitrary bytes, * ... byte[] AESEncrypted = AESCipher.doFinal(str.getBytes("UTF-8")); // Doesn't work: UTF-8 unsuitable for arbitrary bytes and additionally different from * String encryptedStr = new String(AESEncrypted); // Doesn't work: UTF-8 unsuitable for arbitrary bytes ...
debe sustituirse por
... byte[] encoded = Files.readAllBytes(Paths.get(filePath)); ... byte[] AESEncrypted = AESCipher.doFinal(encoded); FileOutputStream out = new FileOutputStream("PAYLOAD"); out.write(AESEncrypted); out.close(); ...
Una codificación adecuada para almacenar datos arbitraria en una cadena es, por ejemplo Base64, pero esto no es necesario en este caso, porque Base64-codificación no se utiliza en el guión tampoco.
Pruebe estos cambios. Si se producen otros problemas, lo mejor sería poner a prueba el cifrado AES, encriptación RSA, y
key_iv
-Generación separado . Esto hace que sea más fácil de errores aislados.