【问题标题】:Cross Platform Encryption and Decryption跨平台加解密
【发布时间】:2017-04-24 06:52:36
【问题描述】:

是否有任何支持 iOS(Swift) 和 C# 应用程序的跨平台 AES 256 加密和解密。除了 https://github.com/Pakhee/Cross-platform-AES-encryption.

我正在尝试加密和解密我的所有数据。

【问题讨论】:

    标签: ios encryption aes


    【解决方案1】:

    我在 C#、IOS 和 Android 中使用了相同的类 (https://github.com/Pakhee/Cross-platform-AES-encryption) 进行 AES 加密/解密。它适用于 C# 和 android,但不适用于 IOS。最后发现以下解决方案在 IOS 中运行良好。

    #import <CommonCrypto/CommonCryptor.h>
    
        - (void)viewDidLoad {
            [super viewDidLoad];
            // Do any additional setup after loading the view, typically from a nib.
    
            NSString *sData = @"Meet me at the secret location at 8pm";
            NSString *sIv = @"4QesEr03HwE5H1C+ICw7SA==";
            NSString *sKey = @"ovA6siPkyM5Lb9oNcnxLz676K6JK6FrJKk4efEUWBzg=";
    
            NSData *dData = [sData dataUsingEncoding:NSUTF8StringEncoding];
    
            NSData *dEncrypt = [self doCipher:dData key:sKey iv:sIv context:kCCEncrypt];
            NSData *base64 = [dEncrypt base64EncodedDataWithOptions:0];
            NSString *sBase64 = [[NSString alloc] initWithData:base64 encoding:NSUTF8StringEncoding];
            NSLog(@"Base64 String: %@",sBase64);
    
            NSData *dDecrypt= [self decrypt:dEncrypt key:sKey iv:sIv];
            NSString *sDecrypt = [[NSString alloc] initWithData:dDecrypt encoding:NSUTF8StringEncoding];
            NSLog(@"Decrypted Data: %@",sDecrypt);
        }
    
        - (NSData *)doCipher:(NSData *)plainText
                         key:(NSString *)key
                          iv:(NSString *)iv
                     context:(CCOperation)encryptOrDecrypt
        {
            NSUInteger dataLength = [plainText length];
    
            size_t buffSize = dataLength + kCCBlockSizeAES128;
            void *buff = malloc(buffSize);
    
            size_t numBytesEncrypted = 0;
    
            NSData *dIv = [iv dataUsingEncoding:NSUTF8StringEncoding];
            NSData *dKey = [key dataUsingEncoding:NSUTF8StringEncoding];
    
            CCCryptorStatus status = CCCrypt(encryptOrDecrypt,
                                             kCCAlgorithmAES128,
                                             kCCOptionPKCS7Padding,
                                             dKey.bytes, kCCKeySizeAES256,
                                             dIv.bytes,
                                             [plainText bytes], [plainText length],
                                             buff, buffSize,
                                             &numBytesEncrypted);
            if (status == kCCSuccess) {
                return [NSData dataWithBytesNoCopy:buff length:numBytesEncrypted];
            }
    
            free(buff);
            return nil;
        }
    

    有关更多详细信息,请查看此线程。 Decrypt a base64 string using C# generated by iOs CCCrypt function using AES

    【讨论】:

      【解决方案2】:

      在其中一个项目中,需要跨平台(C#、Android、IOS)AES 加密/解密。 我已经尝试过https://github.com/Pakhee/Cross-platform-AES-encryption,但它会导致 IOS 出现问题。 所以我已经实现了适用于 C#、IOS 和 Android 的 AES。

      C#

          public class AESCrypto
              {
                  /// <summary>
                  /// Encrpyts the sourceString, returns this result as an Aes encrpyted, BASE64 encoded string
                  /// </summary>
                  /// <param name="plainSourceStringToEncrypt">a plain, Framework string (ASCII, null terminated)</param>
                  /// <param name="passPhrase">The pass phrase.</param>
                  /// <returns>
                  /// returns an Aes encrypted, BASE64 encoded string
                  /// </returns>
                  public static string EncryptString(string plainSourceStringToEncrypt, string passPhrase)
                  {
                      //Set up the encryption objects
                      using (AesCryptoServiceProvider acsp = GetProvider(Encoding.Default.GetBytes(passPhrase)))
                      {
                          byte[] sourceBytes = Encoding.ASCII.GetBytes(plainSourceStringToEncrypt);
                          ICryptoTransform ictE = acsp.CreateEncryptor();
      
                          //Set up stream to contain the encryption
                          MemoryStream msS = new MemoryStream();
      
                          //Perform the encrpytion, storing output into the stream
                          CryptoStream csS = new CryptoStream(msS, ictE, CryptoStreamMode.Write);
                          csS.Write(sourceBytes, 0, sourceBytes.Length);
                          csS.FlushFinalBlock();
      
                          //sourceBytes are now encrypted as an array of secure bytes
                          byte[] encryptedBytes = msS.ToArray(); //.ToArray() is important, don't mess with the buffer
      
                          //return the encrypted bytes as a BASE64 encoded string
                          return Convert.ToBase64String(encryptedBytes);
                      }
                  }
      
      
                  /// <summary>
                  /// Decrypts a BASE64 encoded string of encrypted data, returns a plain string
                  /// </summary>
                  /// <param name="base64StringToDecrypt">an Aes encrypted AND base64 encoded string</param>
                  /// <param name="passphrase">The passphrase.</param>
                  /// <returns>returns a plain string</returns>
                  public static string DecryptString(string base64StringToDecrypt, string passphrase)
                  {
                      //Set up the encryption objects
                      using (AesCryptoServiceProvider acsp = GetProvider(Encoding.Default.GetBytes(passphrase)))
                      {
                          byte[] RawBytes = Convert.FromBase64String(base64StringToDecrypt);
                          ICryptoTransform ictD = acsp.CreateDecryptor();
      
                          //RawBytes now contains original byte array, still in Encrypted state
      
                          //Decrypt into stream
                          MemoryStream msD = new MemoryStream(RawBytes, 0, RawBytes.Length);
                          CryptoStream csD = new CryptoStream(msD, ictD, CryptoStreamMode.Read);
                          //csD now contains original byte array, fully decrypted
      
                          //return the content of msD as a regular string
                          return (new StreamReader(csD)).ReadToEnd();
                      }
                  }
      
                  private static AesCryptoServiceProvider GetProvider(byte[] key)
                  {
                      AesCryptoServiceProvider result = new AesCryptoServiceProvider();
                      result.BlockSize = 128;
                      result.KeySize = 128;
                      result.Mode = CipherMode.CBC;
                      result.Padding = PaddingMode.PKCS7;
      
                      result.GenerateIV();
                      result.IV = new byte[] {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
      
                      byte[] RealKey = GetKey(key, result);
                      result.Key = RealKey;
                     // result.IV = RealKey;
                      return result;
                  }
      
                  private static byte[] GetKey(byte[] suggestedKey, SymmetricAlgorithm p)
                  {
                      byte[] kRaw = suggestedKey;
                      List<byte> kList = new List<byte>();
      
                      for (int i = 0; i < p.LegalKeySizes[0].MinSize; i += 8)
                      {
                          kList.Add(kRaw[(i / 8) % kRaw.Length]);
                      }
                      byte[] k = kList.ToArray();
                      return k;
                  }   
              }
      
      **JAVA -Andorid**
      
      public class AESHelper {
      
          /*This method use to encript the sting  */
          public static String encrypt(String inputString) throws Exception {
              byte[] result = encrypt(inputString.getBytes());
              String result1 = Base64.encodeToString(result,
                      Base64.NO_WRAP);//Instead of Default
              return result1;
          }
      
          public static String decrypt(String encrypted) throws Exception {
              byte[] data = Base64.decode(encrypted, Base64.NO_WRAP);
              byte[] result = decrypt(data);
              String original = new String(result, "UTF-8");
      
              return new String(original);
          }
      
          /*This method return encrypted text with byte code*/
          private static byte[] encrypt( byte[] message) throws Exception {
              byte[] KEY = ConstantData.key.getBytes();//Key for encryption
      
              SecretKeySpec skeySpec = new SecretKeySpec(KEY, "AES");
              byte[] ivx =  new byte[] {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};//make same as web team
              IvParameterSpec ivSpec = new IvParameterSpec(ivx);
              Cipher ecipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
              ecipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivSpec);
      
              byte[] encrypted = ecipher.doFinal(message);
              return encrypted;
          }
      
          private static byte[] decrypt(byte[] encrypted) throws Exception {
              byte[] KEY = ConstantData.key.getBytes();//Key for decrypt
      
              SecretKeySpec skeySpec = new SecretKeySpec(KEY, "AES");
              Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
              byte[] ivx =  new byte[] {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};//make same as web team
              IvParameterSpec ivSpec = new IvParameterSpec(ivx);
      
              cipher.init(Cipher.DECRYPT_MODE, skeySpec,ivSpec);
              byte[] decrypted = cipher.doFinal(encrypted);
              return decrypted;
          }
      

      IOS文件少,无法在此处放代码。您可以从以下网址找到源代码。 https://drive.google.com/file/d/0B05dZSkNGcb-RXkxcjBNd21TNXc/view?usp=sharing

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-04
      • 1970-01-01
      • 1970-01-01
      • 2011-05-18
      • 1970-01-01
      • 1970-01-01
      • 2018-11-06
      • 1970-01-01
      相关资源
      最近更新 更多