从iOS向.NET发送加密字符串,可以通过以下步骤实现:
CommonCrypto
库提供的函数来进行加密操作。加密过程中需要指定密钥、加密模式和填充方式等参数。System.Security.Cryptography
命名空间下的类来实现解密操作。下面是一个示例,演示如何在iOS端使用AES算法加密字符串,并通过HTTP请求发送给.NET后端,然后在.NET后端解密字符串:
iOS端代码示例:
import Foundation
import CommonCrypto
// 加密函数
func encryptString(text: String, key: String, iv: String) -> String? {
let data = text.data(using: .utf8)!
let keyData = key.data(using: .utf8)!
let ivData = iv.data(using: .utf8)!
let cryptData = NSMutableData(length: Int(data.count) + kCCBlockSizeAES128)!
let keyLength = size_t(kCCKeySizeAES128)
let operation = CCOperation(kCCEncrypt)
let algoritm = CCAlgorithm(kCCAlgorithmAES)
let options = CCOptions(kCCOptionPKCS7Padding)
var numBytesEncrypted: size_t = 0
let cryptStatus = CCCrypt(operation, algoritm, options,
(keyData as NSData).bytes, keyLength,
ivData.bytes,
(data as NSData).bytes, data.count,
cryptData.mutableBytes, cryptData.length,
&numBytesEncrypted)
if UInt32(cryptStatus) == UInt32(kCCSuccess) {
cryptData.length = Int(numBytesEncrypted)
let base64cryptString = cryptData.base64EncodedString(options: .lineLength64Characters)
return base64cryptString
} else {
return nil
}
}
// 发送加密字符串给.NET后端
func sendEncryptedStringToServer(encryptedString: String) {
let url = URL(string: "https://yourdotnetserver.com/api/decrypt")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = encryptedString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if let error = error {
print("Error: \(error)")
} else if let data = data {
if let decryptedString = String(data: data, encoding: .utf8) {
print("Decrypted string: \(decryptedString)")
}
}
}
task.resume()
}
// 调用示例
let originalString = "Hello, .NET!"
let key = "YourEncryptionKey"
let iv = "YourEncryptionIV"
if let encryptedString = encryptString(text: originalString, key: key, iv: iv) {
sendEncryptedStringToServer(encryptedString: encryptedString)
}
.NET后端代码示例(C#):
using System;
using System.Security.Cryptography;
using System.Text;
// 解密函数
string decryptString(string encryptedString, string key, string iv)
{
byte[] encryptedData = Convert.FromBase64String(encryptedString);
byte[] keyData = Encoding.UTF8.GetBytes(key);
byte[] ivData = Encoding.UTF8.GetBytes(iv);
using (Aes aes = Aes.Create())
{
aes.Key = keyData;
aes.IV = ivData;
ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
using (MemoryStream ms = new MemoryStream(encryptedData))
using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
using (StreamReader reader = new StreamReader(cs))
{
return reader.ReadToEnd();
}
}
}
// 接收加密字符串的API
[HttpPost("api/decrypt")]
public IActionResult DecryptString([FromBody] string encryptedString)
{
string key = "YourEncryptionKey";
string iv = "YourEncryptionIV";
string decryptedString = decryptString(encryptedString, key, iv);
return Ok(decryptedString);
}
以上代码仅作为示例,实际使用时需要根据具体情况进行适当的修改和优化。
推荐的腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云