跨平台加密和解密

时间:2017-04-24 06:52:37

标签: ios encryption aes

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

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

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

<强> 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