0

我在 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
   }

}

4

1 回答 1

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)")

输出:

加密数据:8d88a2bc 00beb021 f37917c3 75b0ba1a
encryptedBase64:jYiivAC+sCHzeRfDdbC6Gg==

笔记:

不推荐使用 3DES、ECB 模式和 MD5,也不应该在新代码中使用,而是分别使用 AES、CBC 模式和随机 iv 和 PBKDF2。

于 2016-08-17T14:53:24.807 回答