CryptographicBuffer的使用技巧

本文介绍了如何使用CryptographicBuffer进行多种数据格式之间的转换,包括随机数生成、字符串与二进制数据互转、Base64与十六进制编码解码、字节数组复制等,并演示了如何比较不同格式缓冲区数据的一致性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.创建随机数

public string GenerateRandomData()
{
    // Define the length, in bytes, of the buffer.
    uint length = 32;

    // Generate random data and copy it to a buffer.
    IBuffer buffer = CryptographicBuffer.GenerateRandom(length);

    // Encode the buffer to a hexadecimal string (for display).
    string randomHex = CryptographicBuffer.EncodeToHexString(buffer);

    return public void CompareBuffers()
{
    // Create a hexadecimal string.
    String strHex = "30310aff";

    // Create a Base64 string that is equivalent to strHex.
    String strBase64v1 = "MDEK/w==";

    // Create a Base64 string that is not equivalent to strHex.
    String strBase64v2 = "KEDM/w==";

    // Decode strHex to a buffer.
    IBuffer buff1 = CryptographicBuffer.DecodeFromHexString(strHex);

    // Decode strBase64v1 to a buffer.
    IBuffer buff2 = CryptographicBuffer.DecodeFromBase64String(strBase64v1);

    // Decode strBase64v2 to a buffer.
    IBuffer buff3 = CryptographicBuffer.DecodeFromBase64String(strBase64v2);

    // Compare the hexadecimal-decoded buff1 to the Base64-decoded buff2.
    // The code points in the two buffers are equal, and the Boolean value
    // is true.
    Boolean bVal_1 = CryptographicBuffer.Compare(buff1, buff2);

    // Compare the hexadecimal-decoded buff1 to the Base64-decoded buff3.
    // The code points in the two buffers are not equal, and the Boolean value
    // is false.
    Boolean bVal_2 = CryptographicBuffer.Compare(buff1, buff3);
};
}

public uint GenerateRandomNumber()
{
    // Generate a random number.
    uint random = CryptographicBuffer.GenerateRandomNumber();
    return random;
}

2.比较缓存

public void CompareBuffers()
{
    // Create a hexadecimal string.
    String strHex = "30310aff";

    // Create a Base64 string that is equivalent to strHex.
    String strBase64v1 = "MDEK/w==";

    // Create a Base64 string that is not equivalent to strHex.
    String strBase64v2 = "KEDM/w==";

    // Decode strHex to a buffer.
    IBuffer buff1 = CryptographicBuffer.DecodeFromHexString(strHex);

    // Decode strBase64v1 to a buffer.
    IBuffer buff2 = CryptographicBuffer.DecodeFromBase64String(strBase64v1);

    // Decode strBase64v2 to a buffer.
    IBuffer buff3 = CryptographicBuffer.DecodeFromBase64String(strBase64v2);

    // Compare the hexadecimal-decoded buff1 to the Base64-decoded buff2.
    // The code points in the two buffers are equal, and the Boolean value
    // is true.
    Boolean bVal_1 = CryptographicBuffer.Compare(buff1, buff2);

    // Compare the hexadecimal-decoded buff1 to the Base64-decoded buff3.
    // The code points in the two buffers are not equal, and the Boolean value
    // is false.
    Boolean bVal_2 = CryptographicBuffer.Compare(buff1, buff3);
}

3.strings 和 binary转换

public void ConvertData()
{
    // Create a string to convert.
    String strIn = "Input String";

    // Convert the string to UTF16BE binary data.
    IBuffer buffUTF16BE = CryptographicBuffer.ConvertStringToBinary(strIn, BinaryStringEncoding.Utf16BE);

    // Convert the string to UTF16LE binary data.
    IBuffer buffUTF16LE = CryptographicBuffer.ConvertStringToBinary(strIn, BinaryStringEncoding.Utf16LE);

    // Convert the string to UTF8 binary data.
    IBuffer buffUTF8 = CryptographicBuffer.ConvertStringToBinary(strIn, BinaryStringEncoding.Utf8);
}

4.byte数组的复制

public void ByteArrayCopy()
{
    // Initialize a byte array.
    byte[] bytes = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

    // Create a buffer from the byte array.
    IBuffer buffer = CryptographicBuffer.CreateFromByteArray(bytes);

    // Encode the buffer into a hexadecimal string (for display);
    string hex = CryptographicBuffer.EncodeToHexString(buffer);

    // Copy the buffer back into a new byte array.
    byte[] newByteArray;
    CryptographicBuffer.CopyToByteArray(buffer, out newByteArray);
}

5.base64的压缩与解压

public void EncodeDecodeBase64()
{
    // Define a Base64 encoded string.
    String strBase64 = "uiwyeroiugfyqcajkds897945234==";

    // Decoded the string from Base64 to binary.
    IBuffer buffer = CryptographicBuffer.DecodeFromBase64String(strBase64);

    // Encode the buffer back into a Base64 string.
    String strBase64New = CryptographicBuffer.EncodeToBase64String(buffer);
}

public void EncodeDecodeHex()
{
    // Define a hexadecimal string.
    String strHex = "30310AFF";

    // Decode a hexadecimal string to binary.
    IBuffer buffer = CryptographicBuffer.DecodeFromHexString(strHex);

    // Encode the buffer back into a hexadecimal string.
    String strHexNew = CryptographicBuffer.EncodeToHexString(buffer);
}
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Windows.Devices.Bluetooth; using Windows.Devices.Bluetooth.Advertisement; using Windows.Devices.Bluetooth.GenericAttributeProfile; using Windows.Devices.Enumeration; using Windows.Foundation; using Windows.Security.Cryptography; namespace BLETest { public class LanBle { public static BluetoothLEDevice Device = null; //存储检测到的主服务。 public static GattDeviceService Service = null; //存储检测到的写特征对象。 public static GattCharacteristic WriteCharacteristic = null; //存储检测到的通知特征对象。 public static GattCharacteristic NotifyCharacteristic = null; public static GattCharacteristic NotifyCharacteristicForData = null;//主动上报服务 public static bool UseDataNotify = false; public static List<ScanResult> ScanResults = new List<ScanResult>(); public static object LockerForScanResults = new object(); public static List<byte> ReceivedData = new List<byte>(); public static object LockerForReceivedData = new object(); public static List<byte> ReceivedData2 = new List<byte>();//主动上报服务数据 public static object LockerForReceivedData2 = new object();//主动上报服务数据 static bool doScan = false; public static bool ScanState = false; public static bool ConnState = false; public static bool DoReceive = false; public static bool NewDevFlg = false; public static bool DisConnect() { NotifyCharacteristic = null; WriteCharacteristic = null; NotifyCharacteristicForData = null; Service?.Dispose(); Service = null; Device?.Dispose(); Device = null; ConnState = false; return true; } public static void Stop() { doScan = false; } public static void Scan(int timeOut = 10) { if (ScanState) return; lock (LockerForScanResults) { ScanResults.Clear(); } BluetoothLEAdvertisementWatcher bleWatcher = new BluetoothLEAdvertisementWatcher() { ScanningMode = BluetoothLEScanningMode.Active // 主动扫描 }; bleWatcher.Received += BleWatcher_Received; bleWatcher.Stopped += BleWatcher_Stopped; doScan = true; ScanState = true; Task.Factory.StartNew(() => { while (true) { if (!doScan) { bleWatcher.Stop(); return; } else { Thread.Sleep(50); } } }); bleWatcher.Start(); } private static void BleWatcher_Received(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args) { if (string.IsNullOrEmpty(args.Advertisement.LocalName)) return; string name = args.Advertisement.LocalName; CommData.Msgs.Add($"发现 BLE 设备: {name ?? "未知"}"); if (name.Length > 6 && name.Substring(2, 4).ToUpper().Equals("-PL-")) { var rssi = args.RawSignalStrengthInDBm; if (rssi < -80) return; string mac = GetMacString(args.BluetoothAddress); string s1 = $"rssi[{rssi}] { (args.Advertisement.LocalName).PadLeft(30, ' ')} {mac}"; Console.WriteLine(s1); CommData.Msgs.Add(s1); lock (LockerForScanResults) { var m = ScanResults.Find(o => o.Mac == mac); if (m == null) { ScanResults.Add(new ScanResult { Mac = mac, Name = name }); NewDevFlg = true; } else if (m.Name != name) { m.Name = name; NewDevFlg = true; } } } } private static string GetMacString(ulong mac) { string res = ""; string s = mac.ToString("x12"); for (int i = 0; i < 12; i += 2) { res += s.Substring(i, 2) + ":"; } res = res.Remove(res.Length - 1); return res; } private static void BleWatcher_Stopped(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementWatcherStoppedEventArgs args) { ScanState = false; } public static async Task<int> Connect(string mac) { try { DateTime dt0 = DateTime.Now; mac = mac.ToLower(); int connected = -1; ulong macval = ulong.Parse(mac.Replace(":", ""), System.Globalization.NumberStyles.HexNumber); BluetoothLEDevice.FromBluetoothAddressAsync(macval).Completed = async (asyncInfo2, asyncStatus2) => { try { CommData.Msgs.Add($"BluetoothLEDevice.FromBluetoothAddressAsync('{mac}') Completed"); System.Diagnostics.Debug.WriteLine("dt2: " + DateTime.Now.Subtract(dt0).TotalSeconds.ToString()); if (asyncStatus2 == AsyncStatus.Completed) { Device = asyncInfo2.GetResults(); if (Device != null) { var serviceUuids = (await Device.GetGattServicesAsync()) .Services .Select(service => service.Uuid); // 输出所有 UUID foreach (var uuid in serviceUuids) { CommData.Msgs.Add($"Service UUID: {uuid}"); } Device.GetGattServicesForUuidAsync(new Guid(CommData.Config.ServiceUUID)).Completed = (asyncInfo3, asyncStatus3) => { try { CommData.Msgs.Add($"Device.GetGattServicesForUuidAsync('{CommData.Config.ServiceUUID}') Completed"); System.Diagnostics.Debug.WriteLine("dt3: " + DateTime.Now.Subtract(dt0).TotalSeconds.ToString()); if (asyncStatus3 == AsyncStatus.Completed) { IReadOnlyList<GattDeviceService> lists = asyncInfo3.GetResults().Services; CommData.Msgs.Add($"Device.Services.Count: {lists.Count()}"); if (lists != null && lists.Count() > 0) { Service = lists[0]; Service.GetCharacteristicsForUuidAsync(new Guid(CommData.Config.WriteUUID)).Completed = (asyncInfo4, asyncStatus4) => { try { CommData.Msgs.Add($"Service.GetCharacteristicsForUuidAsync('{CommData.Config.WriteUUID}') Completed"); System.Diagnostics.Debug.WriteLine("dt4: " + DateTime.Now.Subtract(dt0).TotalSeconds.ToString()); if (asyncStatus4 == AsyncStatus.Completed) { IReadOnlyList<GattCharacteristic> list2 = asyncInfo4.GetResults().Characteristics; CommData.Msgs.Add($"Characteristics.Count(): {list2.Count()}"); if (list2 != null && list2.Count() > 0) { WriteCharacteristic = list2[0]; Service.GetCharacteristicsForUuidAsync(new Guid(CommData.Config.ReadUUID)).Completed = (asyncInfo5, asyncStatus5) => { try { CommData.Msgs.Add($"Service.GetCharacteristicsForUuidAsync('{CommData.Config.ReadUUID}') Completed"); System.Diagnostics.Debug.WriteLine("dt5: " + DateTime.Now.Subtract(dt0).TotalSeconds.ToString()); if (asyncStatus5 == AsyncStatus.Completed) { IReadOnlyList<GattCharacteristic> list3 = asyncInfo5.GetResults().Characteristics; CommData.Msgs.Add($"Characteristics.Count(): {list3.Count()}"); if (list3 != null && list3.Count() > 0) { NotifyCharacteristic = list3[0]; NotifyCharacteristic.ProtectionLevel = GattProtectionLevel.Plain; NotifyCharacteristic.ValueChanged += Characteristic_ValueChanged; NotifyCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify).Completed = (asyncInfo6, asyncStatus6) => { CommData.Msgs.Add($"NotifyCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync(Notify) Completed"); System.Diagnostics.Debug.WriteLine("dt6: " + DateTime.Now.Subtract(dt0).TotalSeconds.ToString()); if (UseDataNotify==false) { Service.GetCharacteristicsForUuidAsync(new Guid(CommData.Config.DataUUID)).Completed = (asyncInfo7, asyncStatus7) => { try { CommData.Msgs.Add($"Service.GetCharacteristicsForUuidAsync('{CommData.Config.DataUUID}') Completed"); System.Diagnostics.Debug.WriteLine("dt7: " + DateTime.Now.Subtract(dt0).TotalSeconds.ToString()); if (asyncStatus7 == AsyncStatus.Completed) { IReadOnlyList<GattCharacteristic> list4 = asyncInfo7.GetResults().Characteristics; CommData.Msgs.Add($"Characteristics.Count(): {list4.Count()}"); if (list4 != null && list4.Count() > 0) { NotifyCharacteristicForData = list4[0]; NotifyCharacteristicForData.ProtectionLevel = GattProtectionLevel.Plain; NotifyCharacteristicForData.ValueChanged += Characteristic_ValueChanged2; NotifyCharacteristicForData.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify).Completed = (asyncInfo8, asyncStatus8) => { CommData.Msgs.Add($"NotifyCharacteristicForData.WriteClientCharacteristicConfigurationDescriptorAsync(Notify) Completed"); System.Diagnostics.Debug.WriteLine("dt8: " + DateTime.Now.Subtract(dt0).TotalSeconds.ToString()); connected = 0; ConnState = true; }; } else { connected = -11; } } else { connected = -10; } } catch (Exception ex) { CommData.Msgs.Add("Error:" + ex.Message); connected = -1001; } }; } else { connected = 0; ConnState = true; } }; } else { connected = -9; } } else { connected = -8; } } catch (Exception ex) { CommData.Msgs.Add("Error:" + ex.Message); connected = -801; } }; } else { connected = -7; } } else { connected = -6; } } catch (Exception ex) { CommData.Msgs.Add("Error:" + ex.Message); connected = -601; } }; } else { connected = -5; } } else { connected = -4; } } catch (Exception ex) { CommData.Msgs.Add("Error:" + ex.Message); connected = -401; } }; } else { connected = -3; } }// else { connected = -2; } } catch (Exception ex) { CommData.Msgs.Add("Error:" + ex.Message); connected = -201; } }; while (connected == -1) { await Task.Delay(500); } System.Diagnostics.Debug.WriteLine("dt7: " + DateTime.Now.Subtract(dt0).TotalSeconds.ToString()); if (ConnState) CommData.Msgs.Add("Connect OK"); else CommData.Msgs.Add("Connect NG:" + connected); return connected; } catch { return -99; } } private static void Characteristic_ValueChanged2(GattCharacteristic sender, GattValueChangedEventArgs args) { try { byte[] data; CryptographicBuffer.CopyToByteArray(args.CharacteristicValue, out data); lock (LockerForReceivedData2) { ReceivedData2.AddRange(data); } CommData.Msgs.Add("收<<<【电池上报数据】 " + ByteToHex(data)); } catch { } } /// <summary> /// 发送数据接口 /// </summary> /// <param name="characteristic"></param> /// <param name="data"></param> /// <returns></returns> public static async Task<bool> Write(byte[] data) { bool r = false; string msg = "发>>> " + ByteToHex(data); if (WriteCharacteristic != null) { try { GattCommunicationStatus status = await WriteCharacteristic.WriteValueAsync(CryptographicBuffer.CreateFromByteArray(data), GattWriteOption.WriteWithoutResponse); r = status == GattCommunicationStatus.Success; msg += r ? " 【发送成功】" : " 【发送失败】"; } catch (Exception ex) { Console.WriteLine(ex.Message.ToString()); msg += " 【Error】:" + ex.Message; } } else { msg += " 【Error】:WriteCharacteristic NULL"; } return r; } private static void Characteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args) { try { byte[] data; CryptographicBuffer.CopyToByteArray(args.CharacteristicValue, out data); if (DoReceive) { lock (LockerForReceivedData) { ReceivedData.AddRange(data); } } CommData.Msgs.Add("收<<< " + ByteToHex(data)); } catch { } } private static string ByteToHex(byte[] b, bool space = true) { if (b == null) { return ""; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < b.Length; i++) { sb.Append(b[i].ToString("X2") + (space ? " " : "")); } return sb.ToString(); } } public class ScanResult { public string Name { get; set; } public string Mac { get; set; } public string ID { get; set; } public ScanResult() { } public ScanResult(string name, string id) { this.Name = name; if (string.IsNullOrEmpty(Name)) { Name = "未知"; } this.ID = id; string[] s1 = id.Split('-'); if (s1.Length == 2) { this.Mac = s1[1]; } else { this.Mac = ""; } } public ScanResult(string name, string mac, string id) { this.Name = name; if (string.IsNullOrEmpty(Name)) { Name = "未知"; } this.ID = id; this.Mac = mac; } public override string ToString() { //return $"{Name}\t{Mac}\t{ID}"; return $"{Name}\t{Mac}"; } } public class BleEventArgs : EventArgs { public byte[] Data { get; set; } public BleEventArgs(byte[] data) { this.Data = data; } } } 这段代码能否接收蓝牙上传的报文
07-30
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值