开发者

RijndaelEncryption with Java then Decryption with C# and EnterpriseLibrary 4.1

I believe when the EnterpriseLibrary tries to decrypt a RijndaelManaged encrypted string it expects the Initialization Vector to be prepended to the encrypted text. Currently with the code below. I can decrypt the message with out an exception, but I am getting weird characters like:

�猀漀椀搀㴀眀最爀甀戀攀㄀☀甀琀挀㴀㈀ ㄀ ⴀ㄀ ⴀ㈀㄀吀㄀㌀㨀㔀㈀㨀㄀㌀

What do I need to do to make开发者_如何学Python this work? Any help is greatly appreciated. Here is some of the code I have...

I have a C# application that decrypts data using the EnterpriseLibrary 4.1 (encryption: RijndaelManaged).

string message = "This encrypted message comes from Java Client";
Cryptographer.DecryptSymmetric("RijndaelManaged", message);

The client encryptes the message, implemented in Java.

public String encrypt(String auth) {
           try {
               String cipherKey = "Key as a HEX string";
               byte[] rawKey = hexToBytes(cipherKey);
               SecretKeySpec keySpec = new SecretKeySpec(rawKey, "AES");
               Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

               String cipherIV = "xYzF5AqA2cKLbvbfGzsMwg==";
               byte[] btCipherIV = Base64.decodeBase64(cipherIV.getBytes());

               cipher.init(Cipher.ENCRYPT_MODE, keySpec, new IvParameterSpec (btCipherIV));
               byte[] unencrypted = StringUtils.getBytesUtf16(auth);
               byte[] encryptedData = cipher.doFinal(unencrypted);
               String encryptedText = null;

               byte[] entlib = new byte[btCipherIV2.length + encryptedData.length];
               System.arraycopy(btCipherIV, 0, entlib, 0, btCipherIV.length);
               System.arraycopy(encryptedData, 0, entlib, btCipherIV.length, encryptedData.length);

               encryptedText = new String(encryptedData);
               encryptedText = Base64.encodeBase64String(encryptedData);               
               return encryptedText;

           } catch (Exception e) {
           }

           return "";
       }

    public static byte[] hexToBytes(String str) {
          if (str==null) {
             return null;
          } else if (str.length() < 2) {
             return null;
          } else {
             int len = str.length() / 2;
             byte[] buffer = new byte[len];
             for (int i=0; i<len; i++) {
                 buffer[i] = (byte) Integer.parseInt(
                    str.substring(i*2,i*2+2),16);
             }
             return buffer;
          }

       }


I found the answer. The problem in the above code:

StringUtils.getBytesUtf16(auth);

Instead the Enterprise Library is using Little Endian byte order. The function I was using doesn't. Instead I should have used:

StringUtils.getBytesUtf16Le(auth);

This solved my problem. Thanks for anyone who took a loot at this. I appreciate it!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜