2013-02-08 1 views
0

Je dois chiffrer et déchiffrer une grande chaîne en utilisant la clé publique RSA et une clé privée. J'ai réussi à chiffrer un texte plus long en utilisant le code exemple suivantDéchiffrer un texte plus long en utilisant la clé privée RSA

public static string Encrypt(string publicKey, string data, RsaKeyLengths length) 
     { 
      // full array of bytes to encrypt 
      byte[] bytesToEncrypt; 

      // worker byte array 
      byte[] block; 

      // encrypted bytes 
      byte[] encryptedBytes; 

      // length of bytesToEncrypt 
      var dataLength = 0; 

      // number of bytes in key     
      var keySize = 0; 

      // maximum block length to encrypt   
      var maxLength = 0; 

      // how many blocks must we encrypt to encrypt entire message? 
      var iterations = 0; 

      // the encrypted data 
      var encryptedData = new StringBuilder(); 

      // instantiate the crypto provider with the correct key length 
      var rsaCryptoServiceProvider = new RSACryptoServiceProvider((int)length); 

      // initialize the RSA object from the given public key 
      rsaCryptoServiceProvider.FromXmlString(publicKey); 

      // convert data to byte array 
      bytesToEncrypt = Encoding.Unicode.GetBytes(data); 

      // get length of byte array 
      dataLength = bytesToEncrypt.Length; 

      // convert length of key from bits to bytes 
      keySize = (int)length/8; 

      // .NET RSACryptoServiceProvider uses SHA1 Hash function 
      // use this to work out the maximum length to encrypt per block 
      maxLength = ((keySize - 2) - (2 * SHA1.Create().ComputeHash(bytesToEncrypt).Length)); 

      // how many blocks do we need to encrypt? 
      iterations = dataLength/maxLength; 

      // encrypt block by block 
      for (int index = 0; index <= iterations; index++) 
      { 
       // is there more than one full block of data left to encrypt? 
       if ((dataLength - maxLength * index) > maxLength) 
       { 
        block = new byte[maxLength]; 
       } 
       else 
       { 
        block = new byte[dataLength - maxLength * index]; 
       } 

       // copy the required number of bytes from the array of bytes to encrypt to our worker array 
       Buffer.BlockCopy(bytesToEncrypt, maxLength * index, block, 0, block.Length); 

       // encrypt the current worker array block of bytes 
       encryptedBytes = rsaCryptoServiceProvider.Encrypt(block, true); 

       // RSACryptoServiceProvider reverses the order of encrypted bytesToEncrypt after encryption and before decryption. 
       // Undo this reversal for compatibility with other implementations 
       Array.Reverse(encryptedBytes); 

       // convert to base 64 string 
       encryptedData.Append(Convert.ToBase64String(encryptedBytes)); 

      } 
      return encryptedData.ToString(); 

     } 

Alors j'ai essayé de déchiffrer le texte plus en utilisant le code suivant

/// <summary> 
     /// Encrypt an arbitrary string of data under the supplied public key 
     /// </summary> 
     /// <param name="publicKey">The public key to encrypt under</param> 
     /// <param name="data">The data to encrypt</param> 
     /// <param name="length">The bit length or strength of the public key: 1024, 2048 or 4096 bits. This must match the 
     /// value actually used to create the publicKey</param> 
     /// <returns></returns> 
     public static string Decrypt(string privateKey, string data, RsaKeyLengths length) 
     { 
      // full array of bytes to encrypt 
      byte[] bytesToDecrypt; 

      // worker byte array 
      byte[] block; 

      // encrypted bytes 
      byte[] decryptedBytes; 

      // length of bytesToEncrypt 
      var dataLength = 0; 

      // number of bytes in key     
      var keySize = 0; 

      // maximum block length to encrypt   
      var maxLength = 0; 

      // how many blocks must we encrypt to encrypt entire message? 
      var iterations = 0; 

      // the encrypted data 
      var decryptedData = new StringBuilder(); 

      // instantiate the crypto provider with the correct key length 
      var rsaCryptoServiceProvider = new RSACryptoServiceProvider((int)length); 

      // initialize the RSA object from the given public key 
      rsaCryptoServiceProvider.FromXmlString(privateKey); 

      // convert data to byte array 
      bytesToDecrypt = Encoding.Unicode.GetBytes(data); 

      // get length of byte array 
      dataLength = bytesToDecrypt.Length; 

      // convert length of key from bits to bytes 
      keySize = (int)length/8; 

      // .NET RSACryptoServiceProvider uses SHA1 Hash function 
      // use this to work out the maximum length to encrypt per block 
      //maxLength = ((keySize - 2) - (2 * SHA1.Create().ComputeHash(bytesToDecrypt).Length)); 
      maxLength = ((keySize/8) % 3 != 0) ? 
       (((keySize/8)/3) * 4) + 4 : ((keySize/8)/3) * 4; ; 

      // how many blocks do we need to encrypt? 
      iterations = dataLength/maxLength; 

      // encrypt block by block 
      for (int index = 0; index <= iterations; index++) 
      { 
       // is there more than one full block of data left to encrypt? 
       if ((dataLength - maxLength * index) > maxLength) 
       { 
        block = new byte[maxLength]; 
       } 
       else 
       { 
        block = new byte[dataLength - maxLength * index]; 
       } 

       // copy the required number of bytes from the array of bytes to encrypt to our worker array 
       Buffer.BlockCopy(bytesToDecrypt, maxLength * index, block, 0, block.Length); 

       // encrypt the current worker array block of bytes 
       decryptedBytes = rsaCryptoServiceProvider.Decrypt(block, true); 

       // RSACryptoServiceProvider reverses the order of encrypted bytesToEncrypt after encryption and before decryption. 
       // Undo this reversal for compatibility with other implementations 
       Array.Reverse(decryptedBytes); 

       // convert to base 64 string 
       decryptedData.Append(Convert.ToBase64String(decryptedBytes)); 

      } 
      return decryptedData.ToString(); 
     } 

En fait, le cryptage se passe en douceur. Pas de problème avec ça. Mais quand j'essaie de le décrypter. Je reçois l'exception suivante

Exception non gérée: System.Security.Cryptography.CryptographicException: Une erreur est survenue lors du décodage remplissage OAEP.

Quelqu'un peut-il me aider?

+1

J'ai qu'effleurer le code jusqu'à présent, mais il semble que la dernière étape de cryptage est base64 codant pour la sortie, mais l'entrée n'est pas base64 décodé avant le déchiffrement. – shambulator

Répondre

1

Utilisez stream cipher à la place et ne chiffrent cette clé pour ce chiffrement avec RSA. Cela peut aider si vous avez besoin de RSA en raison de sa logique de clé publique-privée et que vous voulez utiliser les différentes clés pour le chiffrement et le décryptage. Avec le chiffrement de flux, vous pouvez chiffrer et déchiffrer des gigaoctets de données sans problème.

RSA est normalement pas utilisé pour des quantités très grandes de données.

+0

En fait, vous avez vraiment raison. Mais pour ma situation, je veux utiliser asymétrique. J'ai donc besoin d'une logique de clé publique-privée. Alors qu'est-ce que je cherche une solution. – Selvakumar

+1

Vous avez toujours toute la logique de clé publique-privée. L'expéditeur crypte la clé de chiffrement avec la clé privée et décrypte le destinataire avec la clé publique. La clé de chiffrement doit être générée de manière aléatoire pour chaque message et ne jamais être réutilisée. Son utilisation n'a aucun effet sur la logique. – h22

+0

J'ai finalement trouvé la réponse. J'ai découpé le message en longueurs de données maximales en fonction de la longueur de la clé. – Selvakumar

Questions connexes