2009-05-14 5 views
6

Estoy compilando una aplicación de iPhone que usa servicios web C#. Mis servicios web C# toman los detalles del usuario y los valida contra mi DB y devuelve archivos xml.Cifrado de cadenas en C# y Objectivo c

Así que ahora el problema es cómo encriptar los detalles del usuario (el nombre de usuario y la contraseña son de 10 unidades cada uno) en el objetivo c y descifrar en C#.

Soy muy nuevo en criptografía, qué método es el mejor. será posible encriptar en el Objetivo c y Desencriptar en C#.

gracias ..

Respuesta

0

Su pregunta es muy vaga, pero en breve; Sí, es posible. Tendrá que averiguar cuáles son las expectativas de su criptografía (alta seguridad o alta velocidad?) Y luego sopesar los beneficios de varios algoritmos y sus dificultades de implementación en Objective-C y C#.

5

Suponiendo que está encriptando esta información para protegerla a través de la red, la mejor solución es conectarse a través de SSL. Esto resolverá el problema sin crear nuevas complejidades en el código. El manejo de SSL generalmente está disponible tanto en .NET como en Cocoa.

¿Hay algún otro motivo por el que intente encriptar esta información?

+2

SSL (en realidad, TLS) es definitivamente el camino a seguir. Las personas que son completamente nuevas en la criptografía no deberían intentar implementar un sistema de cifrado en el código de producción. Es muy fácil equivocarse y terminar con una falsa sensación de seguridad. TLS es una forma estándar y multiplataforma para cifrar el tráfico web, y es probable que las implementaciones de OS X y .NET hayan sido verificadas por personas altamente competentes. – user57368

1

Lo siguiente es del The CSharp Cookbook. Es tan sencillo como un ejemplo. Por supuesto, tendrá que portar la parte de cifrado al Objetivo C, pero siempre que use la misma Clave, debería generar el mismo resultado.

Es necesario utilizar Rijndael cifrado que está disponible here in ObjC compatible code

public static void EncDecString() 
     { 
      string encryptedString = CryptoString.Encrypt("MyPassword"); 
      Console.WriteLine("encryptedString: " + encryptedString); 
      // get the key and IV used so you can decrypt it later 
      byte [] key = CryptoString.Key; 
      byte [] IV = CryptoString.IV; 

      CryptoString.Key = key; 
      CryptoString.IV = IV; 
      string decryptedString = CryptoString.Decrypt(encryptedString); 
      Console.WriteLine("decryptedString: " + decryptedString); 

     } 

     public sealed class CryptoString 
     { 
      private CryptoString() {} 

      private static byte[] savedKey = null; 
      private static byte[] savedIV = null; 

      public static byte[] Key 
      { 
       get { return savedKey; } 
       set { savedKey = value; } 
      } 

      public static byte[] IV 
      { 
       get { return savedIV; } 
       set { savedIV = value; } 
      } 

      private static void RdGenerateSecretKey(RijndaelManaged rdProvider) 
      { 
       if (savedKey == null) 
       { 
        rdProvider.KeySize = 256; 
        rdProvider.GenerateKey(); 
        savedKey = rdProvider.Key; 
       } 
      } 

      private static void RdGenerateSecretInitVector(RijndaelManaged rdProvider) 
      { 
       if (savedIV == null) 
       { 
        rdProvider.GenerateIV(); 
        savedIV = rdProvider.IV; 
       } 
      } 

      public static string Encrypt(string originalStr) 
      { 
       // Encode data string to be stored in memory 
       byte[] originalStrAsBytes = Encoding.ASCII.GetBytes(originalStr); 
       byte[] originalBytes = {}; 

       // Create MemoryStream to contain output 
       MemoryStream memStream = new MemoryStream(originalStrAsBytes.Length); 

       RijndaelManaged rijndael = new RijndaelManaged(); 

       // Generate and save secret key and init vector 
       RdGenerateSecretKey(rijndael); 
       RdGenerateSecretInitVector(rijndael); 

       if (savedKey == null || savedIV == null) 
       { 
        throw (new NullReferenceException(
         "savedKey and savedIV must be non-null.")); 
       } 

       // Create encryptor, and stream objects 
       ICryptoTransform rdTransform = 
        rijndael.CreateEncryptor((byte[])savedKey.Clone(), 
              (byte[])savedIV.Clone()); 
       CryptoStream cryptoStream = new CryptoStream(memStream, rdTransform, 
        CryptoStreamMode.Write); 

       // Write encrypted data to the MemoryStream 
       cryptoStream.Write(originalStrAsBytes, 0, originalStrAsBytes.Length); 
       cryptoStream.FlushFinalBlock(); 
       originalBytes = memStream.ToArray(); 

       // Release all resources 
       memStream.Close(); 
       cryptoStream.Close(); 
       rdTransform.Dispose(); 
       rijndael.Clear(); 

       // Convert encrypted string 
       string encryptedStr = Convert.ToBase64String(originalBytes); 
       return (encryptedStr); 
      } 

      public static string Decrypt(string encryptedStr) 
      { 
       // Unconvert encrypted string 
       byte[] encryptedStrAsBytes = Convert.FromBase64String(encryptedStr); 
       byte[] initialText = new Byte[encryptedStrAsBytes.Length]; 

       RijndaelManaged rijndael = new RijndaelManaged(); 
       MemoryStream memStream = new MemoryStream(encryptedStrAsBytes); 

       if (savedKey == null || savedIV == null) 
       { 
        throw (new NullReferenceException(
         "savedKey and savedIV must be non-null.")); 
       } 

       // Create decryptor, and stream objects 
       ICryptoTransform rdTransform = 
        rijndael.CreateDecryptor((byte[])savedKey.Clone(), 
              (byte[])savedIV.Clone()); 
       CryptoStream cryptoStream = new CryptoStream(memStream, rdTransform, 
        CryptoStreamMode.Read); 

       // Read in decrypted string as a byte[] 
       cryptoStream.Read(initialText, 0, initialText.Length); 

       // Release all resources 
       memStream.Close(); 
       cryptoStream.Close(); 
       rdTransform.Dispose(); 
       rijndael.Clear(); 

       // Convert byte[] to string 
       string decryptedStr = Encoding.ASCII.GetString(initialText); 
       return (decryptedStr); 
      } 
     } 

No puedo hablar acerca de la aplicación Objective C de Rijndael cifrado, pero he utilizado este (C#) código de la base de la parte de la producción trabajo y ha funcionado maravillosamente.

0

No sé Objetivo C, pero para el descifrado de C#, busque en los diversos proveedores de CryptoService en System.Security.Cryptography.

Aquí es un ejemplo que escribí usando TripleDES:

public class TripleDES 
{ 
    private byte[] mbKey; 
    private byte[] mbIV; 
    private TripleDESCryptoServiceProvider tdProvider = new TripleDESCryptoServiceProvider(); 
    private UTF8Encoding UTEncode = new UTF8Encoding(); 

    // Key: **YOUR KEY** 
    // Project IV: **YOUR IV** 
    public TripleDES(string strKey, string strIV) 
    { 
     mbKey = UTEncode.GetBytes(strKey); 
     mbIV = UTEncode.GetBytes(strIV);   
    } 

    public TripleDES() 
    { 
     // 
     // TODO: Add constructor logic here 
     // 
    } 


    public string EncryptToString(string strInput) 
    {   
     return Convert.ToBase64String(this.EncryptToBytes(strInput));   
    } 

    public byte[] EncryptToBytes(string strInput) 
    { 
     byte[] bInput = UTEncode.GetBytes(strInput); 
     byte[] bOutput = ProcessInput(bInput, tdProvider.CreateEncryptor(mbKey, mbIV)); 
     return bOutput; 
    } 

    public string DecryptToString(string strInput) 
    { 
     return UTEncode.GetString(DecryptToBytes(strInput)); 
    } 

    public byte[] DecryptToBytes(string strInput) 
    { 
     byte[] bInput = Convert.FromBase64String(strInput); 
     byte[] bOutput = ProcessInput(bInput, tdProvider.CreateDecryptor(mbKey, mbIV)); 
     return bOutput; 
    } 

    private byte[] ProcessInput(byte[] input, ICryptoTransform ctProcessor) 
    { 
     MemoryStream memStream = new MemoryStream(); 
     CryptoStream crpStream = new CryptoStream(memStream, ctProcessor, CryptoStreamMode.Write); 

     crpStream.Write(input, 0, input.Length); 
     crpStream.FlushFinalBlock(); 

     memStream.Position = 0; 

     byte[] output; 
     output = new byte[memStream.Length]; 

     memStream.Read(output, 0, output.Length); 

     memStream.Close(); 
     crpStream.Close(); 

     return output; 
    } 
} 

}