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