Java coding and .NET decoding

Encryption is in java:


String salt = "DC14DBE5F917C7D03C02CD5ADB88FA41";
String password = "25623F17-0027-3B82-BB4B-B7DD60DCDC9B";

char[] passwordChars = new char[password.length()];
password.getChars(0,password.length(), passwordChars, 0);

SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
KeySpec spec = new PBEKeySpec(passwordChars, salt.getBytes(), 2, 256);
SecretKey sKey = factory.generateSecret(spec);
byte[] raw = _sKey.getEncoded();

String toEncrypt = "The text to be encrypted.";

Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
cipher.init(Cipher.ENCRYPT_MODE, skey);

AlgorithmParameters params = cipher.getParameters();
byte[] initVector = params.getParameterSpec(IvParameterSpec.class).getIV();

byte[] encryptedBytes = cipher.doFinal(toEncrypt.getBytes());

While decryption is in C #:


string hashAlgorithm = "SHA1";
int passwordIterations = 2;
int keySize = 256;

byte[] saltValueBytes = Encoding.ASCII.GetBytes( salt );
byte[] cipherTextBytes = Convert.FromBase64String( cipherText );

PasswordDeriveBytes passwordDB = new PasswordDeriveBytes(password, saltValueBytes, hashAlgorithm  passwordIterations );

byte[] keyBytes = passwordDB.GetBytes( keySize / 8 );

RijndaelManaged symmetricKey = new RijndaelManaged();
symmetricKey.Mode = CipherMode.CBC;
ICryptoTransform decryptor = symmetricKey.CreateDecryptor( keyBytes, initVector );

MemoryStream memoryStream = new MemoryStream( cipherTextBytes );

CryptoStream cryptoStream = new CryptoStream( memoryStream, decryptor, CryptoStreamMode.Read );

byte[] plainTextBytes = new byte[ cipherTextBytes.Length ];

int decryptedByteCount = cryptoStream.Read( plainTextBytes, 0, plainTextBytes.Length );

memoryStream.Close();
cryptoStream.Close();

string plainText = Encoding.UTF8.GetString( plainTextBytes, 0, decryptedByteCount );

Decryption failed. "Filling is invalid and cannot be deleted."

Any idea what could be the problem?

+5
source share
1 answer

This means that decryption failed. I suggest you check the output of the key generation functions to see if you are really using the same key. For example, I noticed that Java code implies that you use SHA1-based HMAC, while .NET code means that you use a SHA1 keyless hash to generate the key.

, . , PaddingMode PKCS7 .NET.

+5

All Articles