在 SWIFT 中加密和解密

Encrypt and decrypt in SWIFT

我正在 SWIFT 中搜索加密和解密代码。

但我无法在 SWIFT 中找到解决方案。我需要在 MD5 中将密钥传递给 encrypt/decrypt 并在 ECB 模式下转换为 BASE64

我在 C# 中有这段代码:

public static string MD5Cripto(string texto, string chave)
{
  try
  {
     TripleDESCryptoServiceProvider sObCripto 
                      = new TripleDESCryptoServiceProvider();
     MD5CryptoServiceProvider sObjcriptoMd5 = new MD5CryptoServiceProvider();
     byte[] sByteHash, sByteBuff;
     string sTempKey = chave;

     sByteHash = sObjcriptoMd5.ComputeHash(ASCIIEncoding
                     .UTF8.GetBytes(sTempKey));
     sObjcriptoMd5 = null;
     sObCriptografaSenha.Key = sByteHash;
     sObCriptografaSenha.Mode = CipherMode.ECB;

     sByteBuff = ASCIIEncoding.UTF8.GetBytes(texto);
     return Convert.ToBase64String(sObCripto.CreateEncryptor()
                    .TransformFinalBlock(sByteBuff, 0, sByteBuff.Length));
  }
  catch (Exception ex)
  {
     return "Digite os valores Corretamente." + ex.Message;
  }
}

更新:

我试过了,但还是不行。我做错了什么? (忽略我的指纹..)

func myEncrypt(encryptData:String) -> NSData?
{
   let myKeyData : NSData = ("mykey" as NSString)
                     .dataUsingEncoding(NSUTF8StringEncoding)!
   let myKeyDataMD5 = "mykey".md5()
   let sArrayByte = myKeyDataMD5.hexToByteArray()
   let myRawData : NSData = encryptData.dataUsingEncoding(NSUTF8StringEncoding)!

   let buffer_size:size_t = myRawData.length + kCCBlockSize3DES
   let buffer = UnsafeMutablePointer<NSData>.alloc(buffer_size)
   var num_bytes_encrypted : size_t = 0

   let operation:CCOperation = UInt32(kCCEncrypt)
   let algoritm:CCAlgorithm = UInt32(kCCAlgorithm3DES)
   let options:CCOptions   = UInt32(kCCOptionECBMode + kCCOptionPKCS7Padding)
   let keyLength = size_t(kCCKeySize3DES)

   let Crypto_status: CCCryptorStatus = CCCrypt(operation, algoritm, 
           options, sArrayByte, keyLength, nil, 
           myRawData.bytes, myRawData.length, buffer, 
           buffer_size, &num_bytes_encrypted)

   if Int32(Crypto_status) == Int32(kCCSuccess)
   {
      let myResult: NSData = NSData(bytes: buffer, length: num_bytes_encrypted)
      print("buffer")

      let count = myResult.length / sizeof(UInt32)
      var array = [UInt32](count: count, repeatedValue: 0)
      myResult.getBytes(&array, length:count * sizeof(UInt32))

      print(array)

      free(buffer)
      print("myResult")
      print(myResult)

      let resultNSString = NSString(data: myResult, 
                    encoding: NSUnicodeStringEncoding)!
      let resultString = resultNSString as String
      print("resultString")
      print(resultString)
      let sBase64 = toBase64(String(resultString))
      print("sBase64")
      print(sBase64)

      let data : NSData! = resultNSString
                    .dataUsingEncoding(NSUnicodeStringEncoding)
      let count2 = data.length / sizeof(UInt32)
      var array2 = [UInt32](count: count, repeatedValue: 0)
      data.getBytes(&array2, length:count2 * sizeof(UInt32))
      print("array2")
      print(array2)

      return myResult
   }
   else
   {
      free(buffer)
      return nil
   }

}

示例问题代码已更新。
不确定问题中的输出格式化代码试图完成什么。

请注意,3DES 使用 24 字节的密钥(kCCKeySize3DES 为 24)而 MD5 提供 16 字节的结果(CC_MD5_DIGEST_LENGTH 为 16),因此密钥不匹配长度。

func encrypt(dataString:String, keyString:String) -> NSData?
{
    let keyData = md5(keyString)
    let data : NSData = dataString.dataUsingEncoding(NSUTF8StringEncoding)!
    var numBytesEncrypted : size_t = 0
    var encryptedData: NSMutableData! = NSMutableData(length: Int(data.length) + kCCBlockSize3DES)
    let encryptedPointer = UnsafeMutablePointer<UInt8>(encryptedData.mutableBytes)
    let encryptedLength  = size_t(encryptedData.length)

    let operation:CCOperation = UInt32(kCCEncrypt)
    let algoritm:CCAlgorithm = UInt32(kCCAlgorithm3DES)
    let options:CCOptions   = UInt32(kCCOptionECBMode + kCCOptionPKCS7Padding)
    let keyLength = size_t(kCCKeySize3DES)

    let status: CCCryptorStatus = CCCrypt(operation, algoritm, options,
                                          keyData, keyLength,
                                          nil,
                                          data.bytes, data.length,
                                          encryptedPointer, encryptedLength,
                                          &numBytesEncrypted)
    if Int32(status) == Int32(kCCSuccess) {
        encryptedData.length = Int(numBytesEncrypted)
    }
    else {
        encryptedData = nil
    }

    return encryptedData;
}

func md5(string: String) -> [UInt8] {
    var digest = [UInt8](count: Int(CC_MD5_DIGEST_LENGTH), repeatedValue: 0)
    if let data = string.dataUsingEncoding(NSUTF8StringEncoding) {
        CC_MD5(data.bytes, CC_LONG(data.length), &digest)
    }
    return digest
}

测试:

let dataString = "Now is the time"
let keyString  = "mykey"
let encryptedData = encrypt(dataString, keyString:keyString)
print("encryptedData: \(encryptedData!)")

let encryptedBase64 = encryptedData!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions())
print("encryptedBase64: \(encryptedBase64)")

输出:

encryptedData: 8d88a2bc 00beb021 f37917c3 75b0ba1a
encryptedBase64: jYiivAC+sCHzeRfDdbC6Gg==

注:

3DES, ECB mode and MD5 are not recommended and should not be used in new code, instead use AES, CBC mode with a random iv and PBKDF2 respetively.