加密在java和解密在C#为AES 256位 [英] Encrypt in java and Decrypt in C# For AES 256 bit

查看:99
本文介绍了加密在java和解密在C#为AES 256位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  /// Java Class 
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;

public class Crypt {

public static String key =xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx;
public static byte [] key_Array = Base64.decodeBase64(key);

public static String encrypt(String strToEncrypt)
{
try
{
// Cipher _Cipher = Cipher.getInstance(AES);
// Cipher _Cipher = Cipher.getInstance(AES / ECB / PKCS5PADDING);
// Cipher _Cipher = Cipher.getInstance(AES / CBC / PKCS5PADDING);

密钥SecretKey =新的SecretKeySpec(key_Array,AES);

密码_Cipher = Cipher.getInstance(AES);
_Cipher.init(Cipher.ENCRYPT_MODE,SecretKey);

返回Base64.encodeBase64String(_Cipher.doFinal(strToEncrypt.getBytes()));
}
catch(异常e)
{
System.out.println([Exception]:+ e.getMessage());
}
返回null;
}

public static void main(String [] args){
StringBuilder sb = new StringBuilder();
sb.append(xml file string ...);

String EncryptedString = encrypt(sb.toString());
System.out.println([EncryptedString]:+ EncryptedString);
}
}

2.我有c#函数解密消息由java函数加密。

  /// C#函数
private static string Decrypt(string encryptedText )
{
RijndaelManaged aesEncryption = new RijndaelManaged();
aesEncryption.BlockSize = 256;
//aesEncryption.KeySize = 256;
//aesEncryption.Mode = CipherMode.CBC;
//aesEncryption.Padding = PaddingMode.PKCS7;

string keyStr =xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx;
// string ivStr =xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx;

byte [] keyArr = Convert.FromBase64String(keyStr);
// byte [] ivArr = Convert.FromBase64String(ivStr);

aesEncryption.Key = keyArr;
//aesEncryption.IV = ivArr;

ICryptoTransform decrypto = aesEncryption.CreateDecryptor();

byte [] encryptedBytes = Convert.FromBase64CharArray(encryptedText.ToCharArray(),0,encryptedText.Length);
byte [] decryptptedData = decrypto.TransformFinalBlock(encryptedBytes,0,encryptedBytes.Length); /// CryptographicException:要解密的数据长度无效。
返回ASCIIEncoding.UTF8.GetString(decryptptedData);
}

Java加密功能很好。但问题是C#函数,
当我解密时我收到以下错误消息

  CryptographicException:要解密的数据长度是无效的。 

我通过使用下面的引用搜索解决方案


  1. Java中的AES加密和解密在C#

  2. C#/ Java | AES256加密/解密

  3. C#和Java中的Encyption / Decryption

但我仍然面临同样的错误。任何人给我建议。



更新



我只是更改我的C#加密功能。以下是我的更改列表


  1. 块大小为128

  2. 密钥大小为256

  3. IV尺寸到16

  4. 按键大小为32



  ///更新的解密函数
private static string Decrypt(string encryptedText)
{
RijndaelManaged aesEncryption = new RijndaelManaged();
aesEncryption.BlockSize = 128;
aesEncryption.KeySize = 256;

//aesEncryption.Mode = CipherMode.CBC;
aesEncryption.Padding = PaddingMode.None;

string keyStr =xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx;
string ivStr =xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx;

byte [] ivArr = Convert.FromBase64String(ivStr);
byte [] IVkey16BytesValue = new byte [16];
Array.Copy(ivArr,IVkey16BytesValue,16);

byte [] keyArr = Convert.FromBase64String(keyStr);
byte [] KeyArr32BytesValue = new byte [32];
Array.Copy(keyArr,KeyArr32BytesValue,32);

aesEncryption.IV = IVkey16BytesValue;
aesEncryption.Key = KeyArr32BytesValue;

ICryptoTransform decrypto = aesEncryption.CreateDecryptor();

byte [] encryptedBytes = Convert.FromBase64CharArray(encryptedText.ToCharArray(),0,encryptedText.Length);
byte [] decryptptedData = decrypto.TransformFinalBlock(encryptedBytes,0,encryptedBytes.Length);
返回ASCIIEncoding.UTF8.GetString(decryptptedData);
}

此时,不会发生错误。但是我收到了我无法读取的解密消息。

  g: \0 \td  Y\\\ \\符O    \rL  W wHm >f \au    %  0  \.......... 

请让我再次提出你的建议。

解决方案

我相信blockSize应该是128,keysize是256. keyStr应该是32个字符长,而IVstr应该是16个字符长这可能有助于它描述为什么128位必须用于块大小以及密钥大小可以是什么。 csrc.nist.gov/publications/fips/fips197/fips-197.pdf



你在解密方法中有这个。

  aesEncryption.Padding = PaddingMode.None; 

我相信你也需要加密方法。



另外为什么不使用这个方法的键和IV。

  aes.Key = ASCIIEncoding.ASCII.GetBytes(keyStr); 
aes.IV = ASCIIEncoding.ASCII.GetBytes(ivStr);


1.I have java function which encrypt xml file and return encrypted String.

/// Java Class 
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;

public class Crypt {

    public static String key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
    public static byte[] key_Array = Base64.decodeBase64(key);

    public static String encrypt(String strToEncrypt)
    {       
        try
        {   
            //Cipher _Cipher = Cipher.getInstance("AES");
            //Cipher _Cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
            //Cipher _Cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");      

            Key SecretKey = new SecretKeySpec(key_Array, "AES");

            Cipher _Cipher = Cipher.getInstance("AES");     
            _Cipher.init(Cipher.ENCRYPT_MODE, SecretKey);       

            return Base64.encodeBase64String(_Cipher.doFinal(strToEncrypt.getBytes()));     
        }
        catch (Exception e)
        {
            System.out.println("[Exception]:"+e.getMessage());
        }
        return null;
    }

    public static void main(String[] args) {        
        StringBuilder sb = new StringBuilder();
        sb.append("xml file string ...");

        String EncryptedString = encrypt(sb.toString());        
        System.out.println("[EncryptedString]:"+EncryptedString);
    }
}

2.I have c# function which decrypt the message which is encrypted by java function.

/// C# Function
private static string Decrypt(string encryptedText)
{
    RijndaelManaged aesEncryption = new RijndaelManaged();            
    aesEncryption.BlockSize = 256;
    //aesEncryption.KeySize = 256;
    //aesEncryption.Mode = CipherMode.CBC;
    //aesEncryption.Padding = PaddingMode.PKCS7;

    string keyStr = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
    //string ivStr = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";        

    byte[] keyArr = Convert.FromBase64String(keyStr);
    //byte[] ivArr = Convert.FromBase64String(ivStr);

    aesEncryption.Key = keyArr;
    //aesEncryption.IV = ivArr;

    ICryptoTransform decrypto = aesEncryption.CreateDecryptor();

    byte[] encryptedBytes = Convert.FromBase64CharArray(encryptedText.ToCharArray(), 0, encryptedText.Length);  
    byte[] decryptedData = decrypto.TransformFinalBlock(encryptedBytes, 0, encryptedBytes.Length); /// CryptographicException: Length of the data to decrypt is invalid.    
    return ASCIIEncoding.UTF8.GetString(decryptedData); 
}

Java encrypt function is work well. But the problem is C# function,
when I decrypt I get below error message

CryptographicException: Length of the data to decrypt is invalid.

I searched solutions by using below ref

  1. AES Encryption in Java and Decryption in C#
  2. C# / Java | AES256 encrypt/decrypt
  3. Encyption/Decryption in C# and Java

but I still face the same error.Could anyone give me suggestion please.

Updated

I Just change my C# crypto function. Below is my change lists

  1. Block Size to 128
  2. Key Size to 256
  3. IV Size to 16
  4. Key Size to 32

/// Updated decrypt function
private static string Decrypt(string encryptedText)
{
    RijndaelManaged aesEncryption = new RijndaelManaged();            
    aesEncryption.BlockSize = 128;
    aesEncryption.KeySize = 256;

    //aesEncryption.Mode = CipherMode.CBC;
    aesEncryption.Padding = PaddingMode.None;

    string keyStr = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
    string ivStr = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";           

    byte[] ivArr = Convert.FromBase64String(ivStr);
    byte[] IVkey16BytesValue = new byte[16];
    Array.Copy(ivArr, IVkey16BytesValue, 16);

    byte[] keyArr = Convert.FromBase64String(keyStr);
    byte[] KeyArr32BytesValue = new byte[32];
    Array.Copy(keyArr, KeyArr32BytesValue, 32);

    aesEncryption.IV = IVkey16BytesValue;
    aesEncryption.Key = KeyArr32BytesValue; 

    ICryptoTransform decrypto = aesEncryption.CreateDecryptor();

    byte[] encryptedBytes = Convert.FromBase64CharArray(encryptedText.ToCharArray(), 0, encryptedText.Length);
    byte[] decryptedData = decrypto.TransformFinalBlock(encryptedBytes, 0, encryptedBytes.Length); 
    return ASCIIEncoding.UTF8.GetString(decryptedData);
}

In this time, no error occur. But I get decrypted message which i cannot read.

g:�\0�\td��Y\\符O����\rL��W�wHm�>f�\au����%��0��\ ..........

Please let me get your suggestion again.

解决方案

I believe the blockSize should be 128 and the keysize be 256. The keyStr should be 32 characters long and the IVstr should be 16 characters long. This may help as it describes why 128 bits have to be used for block size and what the key sizes can be. csrc.nist.gov/publications/fips/fips197/fips-197.pdf

You have this in the decrypt method.

    aesEncryption.Padding = PaddingMode.None; 

I believe you need to put that in the encrypt method also.

Also why not use this method for the key and IV.

    aes.Key = ASCIIEncoding.ASCII.GetBytes(keyStr); 
    aes.IV = ASCIIEncoding.ASCII.GetBytes(ivStr);

这篇关于加密在java和解密在C#为AES 256位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆