2013-12-23 3 views
0

У меня есть следующие шифрования/дешифрования методов на JAVACipher, Java шифровать, C# расшифровать

private static final String ALGORITHM = "AES"; 

protected static String encrypt(String valueToEnc, byte[] keyValue) throws Exception { 
    Key key = generateKey(keyValue); 
    Cipher c = Cipher.getInstance(ALGORITHM); 
    c.init(Cipher.ENCRYPT_MODE, key); 
    byte[] encValue = c.doFinal(valueToEnc.getBytes()); 
    String encryptedValue = new BASE64Encoder().encode(encValue); 
    return encryptedValue; 
} 

protected static String decrypt(String encryptedValue, byte[] keyValue) throws Exception { 
    try 
    { 
     Key key = generateKey(keyValue); 
     Cipher c = Cipher.getInstance(ALGORITHM); 
     c.init(Cipher.DECRYPT_MODE, key); 
     byte[] decordedValue = new BASE64Decoder().decodeBuffer(encryptedValue); 
     byte[] decValue = c.doFinal(decordedValue); 
     String decryptedValue = new String(decValue); 
     return decryptedValue; 
    } 
    catch(Exception ex) 
    { 
     return ""; 
    } 
} 

private static Key generateKey(byte[] keyValue) throws Exception {   
    Key key = new SecretKeySpec(keyValue, ALGORITHM); 
    return key; 
} 

Что было бы эквивалентно дешифрования для (C#). NET ?. Я проверил некоторые примеры шифрования, которые я нашел, но ни один из них не возвращает то же, что и версия Java.

Спасибо.

+1

можно дублировать? http://stackoverflow.com/questions/19698272/encrypt-in-java-and-decrypt-in-c-sharp-for-aes-256-bit –

+0

ЕЦБ небезопасен. Вы должны использовать CBC и использовать случайный уникальный IV. – SLaks

+0

@ThiagoCustodio, если я использую этот пример, так как это исключение «Недопустимый символ в base64». – Ferite

ответ

0

Попробуйте это:

using System; 
using System.IO; 
using System.Security.Cryptography; 

namespace Aes_Example 
{ 
    class AesExample 
    { 
     public static void Main() 
     { 
      try 
      { 

       string original = "Here is some data to encrypt!"; 

       // Create a new instance of the AesCryptoServiceProvider 
       // class. This generates a new key and initialization 
       // vector (IV). 
       using (AesCryptoServiceProvider myAes = new AesCryptoServiceProvider()) 
       { 

        // Encrypt the string to an array of bytes. 
        byte[] encrypted = EncryptStringToBytes_Aes(original, myAes.Key, myAes.IV); 

        // Decrypt the bytes to a string. 
        string roundtrip = DecryptStringFromBytes_Aes(encrypted, myAes.Key, myAes.IV); 

        //Display the original data and the decrypted data. 
        Console.WriteLine("Original: {0}", original); 
        Console.WriteLine("Round Trip: {0}", roundtrip); 
       } 

      } 
      catch (Exception e) 
      { 
       Console.WriteLine("Error: {0}", e.Message); 
      } 
     } 
     static byte[] EncryptStringToBytes_Aes(string plainText, byte[] Key, byte[] IV) 
     { 
      // Check arguments. 
      if (plainText == null || plainText.Length <= 0) 
       throw new ArgumentNullException("plainText"); 
      if (Key == null || Key.Length <= 0) 
       throw new ArgumentNullException("Key"); 
      if (IV == null || IV.Length <= 0) 
       throw new ArgumentNullException("Key"); 
      byte[] encrypted; 
      // Create an AesCryptoServiceProvider object 
      // with the specified key and IV. 
      using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider()) 
      { 
       aesAlg.Key = Key; 
       aesAlg.IV = IV; 

       // Create a decrytor to perform the stream transform. 
       ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV); 

       // Create the streams used for encryption. 
       using (MemoryStream msEncrypt = new MemoryStream()) 
       { 
        using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) 
        { 
         using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) 
         { 

          //Write all data to the stream. 
          swEncrypt.Write(plainText); 
         } 
         encrypted = msEncrypt.ToArray(); 
        } 
       } 
      } 


      // Return the encrypted bytes from the memory stream. 
      return encrypted; 

     } 

     static string DecryptStringFromBytes_Aes(byte[] cipherText, byte[] Key, byte[] IV) 
     { 
      // Check arguments. 
      if (cipherText == null || cipherText.Length <= 0) 
       throw new ArgumentNullException("cipherText"); 
      if (Key == null || Key.Length <= 0) 
       throw new ArgumentNullException("Key"); 
      if (IV == null || IV.Length <= 0) 
       throw new ArgumentNullException("IV"); 

      // Declare the string used to hold 
      // the decrypted text. 
      string plaintext = null; 

      // Create an AesCryptoServiceProvider object 
      // with the specified key and IV. 
      using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider()) 
      { 
       aesAlg.Key = Key; 
       aesAlg.IV = IV; 

       // Create a decrytor to perform the stream transform. 
       ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV); 

       // Create the streams used for decryption. 
       using (MemoryStream msDecrypt = new MemoryStream(cipherText)) 
       { 
        using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) 
        { 
         using (StreamReader srDecrypt = new StreamReader(csDecrypt)) 
         { 

          // Read the decrypted bytes from the decrypting stream 
          // and place them in a string. 
          plaintext = srDecrypt.ReadToEnd(); 
         } 
        } 
       } 

      } 

      return plaintext; 

     } 
    } 
} 

Источник: http://msdn.microsoft.com/en-us/library/system.security.cryptography.aescryptoserviceprovider(v=vs.110).aspx

+0

Это хороший пример шифрования/дешифрования, все на .NET. Но мне нужна программа, которая может расшифровать строки, зашифрованные кодом JAVA, показанным выше. Благодарю. – Ferite

+0

@Ferite обратите внимание на мой код: // Расшифруйте байты до строки. string roundtrip = DecryptStringFromBytes_Aes (your_java_encrypted_string, myAes.Key, myAes.IV); –

+0

, поскольку приложение C# находится в Framework 2.0, я должен изменить AesCryptoServiceProvider для RijndaelManaged. Когда я тестировал код, «Длина данных для дешифрования недействительна». исключение. Входная зашифрованная строка была получена из приложения Java шифрования. Однако я должен сказать, что я не знаю, как должен быть создан вектор инициализации (я не вижу такого эквивалента векселя инициализации в коде Java). – Ferite

Смежные вопросы