在SWIFT中加密和解密

时间:2016-08-16 17:43:14

标签: swift encryption base64 md5 ecb

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

但我无法在SWIFT中找到解决方案。我需要传递密钥才能在 MD5 中加密/解密,并在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
   }

}

1 个答案:

答案 0 :(得分:0)

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

请注意,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模式和MD5,不应在新代码中使用,而是使用AES,CBC模式和随机iv和PBKDF2分别使用。