/// <summary> /// Exports a private key. /// </summary> /// <param name="Path">The path to export to.</param> /// <param name="PrivateKey">The key to export.</param> public static void ExportKey(string Path, CngKey PrivateKey) { using (BinaryWriter Writer = new BinaryWriter(File.Create(Path))) { Writer.Write((byte)PrivateKey.Export(CngKeyBlobFormat.EccPrivateBlob).Length); Writer.Write(PrivateKey.Export(CngKeyBlobFormat.EccPrivateBlob)); } }
internal ECDiffieHellmanCngPublicKey(CngKey key) : base(key.Export(CngKeyBlobFormat.EccPublicBlob)) { this.m_format = CngKeyBlobFormat.EccPublicBlob; new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert(); this.m_key = CngKey.Open(key.Handle, key.IsEphemeral ? CngKeyHandleOpenOptions.EphemeralKey : CngKeyHandleOpenOptions.None); CodeAccessPermission.RevertAssert(); }
public static void CreateKeys() { // 根据算法创建密钥对 aliceKeySignature = CngKey.Create(CngAlgorithm.ECDsaP256); // 导出密钥对中的公钥 alicePubKeyBlob = aliceKeySignature.Export(CngKeyBlobFormat.GenericPublicBlob); }
public override void Write(CngKey key, Stream stream) { int keySize; byte[] x; byte[] y; var keyBlob = key.Export(CngKeyBlobFormat.EccPublicBlob); unsafe { fixed(byte* pKeyBlob = keyBlob) { var pBcryptBlob = (BCRYPT_ECCKEY_BLOB*) pKeyBlob; var offset = Marshal.SizeOf(typeof (BCRYPT_ECCKEY_BLOB)); keySize = pBcryptBlob->KeySizeBytes; x = new byte[keySize]; y = new byte[keySize]; Buffer.BlockCopy(keyBlob, offset, x, 0, keySize); offset += keySize; Buffer.BlockCopy(keyBlob, offset, y, 0, keySize); } } WriteInternal(keySize, x, y, stream); }
private static void CreateKeys() { aliceKey = CngKey.Create(CngAlgorithm.ECDiffieHellmanP256); alicePubKeyBlod = aliceKey.Export(CngKeyBlobFormat.GenericPublicBlob); bobKey = CngKey.Create(CngAlgorithm.ECDiffieHellmanP256); bobPubKeyBlob = bobKey.Export(CngKeyBlobFormat.GenericPublicBlob); }
internal ECDiffieHellmanCngPublicKey(CngKey key) : base(key.Export(CngKeyBlobFormat.EccPublicBlob)) { this.m_format = CngKeyBlobFormat.EccPublicBlob; new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert(); this.m_key = CngKey.Open(key.Handle, key.IsEphemeral ? CngKeyHandleOpenOptions.EphemeralKey : CngKeyHandleOpenOptions.None); CodeAccessPermission.RevertAssert(); }
private int ComputeQLength() { CngKey key = Key; byte[] blob = key.Export(CngKeyBlobFormat.GenericPublicBlob); unsafe { if (blob.Length < sizeof(BCRYPT_DSA_KEY_BLOB_V2)) return(Sha1HashOutputSize); fixed(byte *pBlobBytes = blob) { BCRYPT_DSA_KEY_BLOB_V2 *pBlob = (BCRYPT_DSA_KEY_BLOB_V2 *)pBlobBytes; if (pBlob->dwMagic != KeyBlobMagicNumber.DsaPublicV2 && pBlob->dwMagic != KeyBlobMagicNumber.DsaPrivateV2) { // This is a V1 BCRYPT_DSA_KEY_BLOB, which hardcodes the Q length to 20 bytes. return(Sha1HashOutputSize); } return(pBlob->cbGroupSize); } } }
public static void CreateKey() { aliceKey = CngKey.Create(CngAlgorithm.ECDiffieHellmanP256); bobKey = CngKey.Create(CngAlgorithm.ECDiffieHellmanP256); alicePubKeyBlob = aliceKey.Export(CngKeyBlobFormat.EccPublicBlob); bobPubKeyBlob = bobKey.Export(CngKeyBlobFormat.EccPublicBlob); }
private static void WritePublicKeyValue(XmlWriter writer, CngKey key) { Contract.Requires(writer != null); Contract.Requires(key != null && (key.AlgorithmGroup == CngAlgorithmGroup.ECDsa || key.AlgorithmGroup == CngAlgorithmGroup.ECDiffieHellman)); writer.WriteStartElement(PublicKeyRoot); byte[] exportedKey = key.Export(CngKeyBlobFormat.EccPublicBlob); BigInteger x; BigInteger y; NCryptNative.UnpackEccPublicBlob(exportedKey, out x, out y); writer.WriteStartElement(XElement); writer.WriteAttributeString(ValueAttribute, x.ToString("R", CultureInfo.InvariantCulture)); writer.WriteAttributeString(XsiNamespacePrefix, XsiTypeAttribute, XsiNamespace, XsiTypeAttributeValue); writer.WriteEndElement(); // </X> writer.WriteStartElement(YElement); writer.WriteAttributeString(ValueAttribute, y.ToString("R", CultureInfo.InvariantCulture)); writer.WriteAttributeString(XsiNamespacePrefix, XsiTypeAttribute, XsiNamespace, XsiTypeAttributeValue); writer.WriteEndElement(); // </Y> writer.WriteEndElement(); // </PublicKey> }
private static byte[] ExportFullKeyBlob(CngKey key, bool includePrivateParameters) { CngKeyBlobFormat blobFormat = includePrivateParameters ? CngKeyBlobFormat.EccFullPrivateBlob : CngKeyBlobFormat.EccFullPublicBlob; return(key.Export(blobFormat)); }
private void CreateKeys() { _aliceKey = CngKey.Create(CngAlgorithm.ECDiffieHellmanP521); _bobKey = CngKey.Create(CngAlgorithm.ECDiffieHellmanP521); _alicePubKeyBlob = _aliceKey.Export(CngKeyBlobFormat.EccPublicBlob); _bobPubKeyBlob = _bobKey.Export(CngKeyBlobFormat.EccPublicBlob); }
/// <summary> /// Note! This can and likely will throw if the algorithm was given a hardware-based key. /// </summary> internal static byte[] GetSymmetricKeyDataIfExportable(this CngKey cngKey, string algorithm) { const int SizeOf_NCRYPT_KEY_BLOB_HEADER = sizeof(int) + sizeof(int) + sizeof(int) + sizeof(int); byte[] keyBlob = cngKey.Export(s_cipherKeyBlobFormat); using (MemoryStream ms = new MemoryStream(keyBlob)) { using (BinaryReader br = new BinaryReader(ms, Encoding.Unicode)) { // Read NCRYPT_KEY_BLOB_HEADER int cbSize = br.ReadInt32(); // NCRYPT_KEY_BLOB_HEADER.cbSize if (cbSize != SizeOf_NCRYPT_KEY_BLOB_HEADER) { throw new CryptographicException(SR.Cryptography_KeyBlobParsingError); } int ncryptMagic = br.ReadInt32(); // NCRYPT_KEY_BLOB_HEADER.dwMagic if (ncryptMagic != Interop.NCrypt.NCRYPT_CIPHER_KEY_BLOB_MAGIC) { throw new CryptographicException(SR.Cryptography_KeyBlobParsingError); } int cbAlgName = br.ReadInt32(); // NCRYPT_KEY_BLOB_HEADER.cbAlgName br.ReadInt32(); // NCRYPT_KEY_BLOB_HEADER.cbKey string algorithmName = new string(br.ReadChars((cbAlgName / 2) - 1)); if (algorithmName != algorithm) { throw new CryptographicException(SR.Format(SR.Cryptography_CngKeyWrongAlgorithm, algorithmName, algorithm)); } char nullTerminator = br.ReadChar(); if (nullTerminator != 0) { throw new CryptographicException(SR.Cryptography_KeyBlobParsingError); } // Read BCRYPT_KEY_DATA_BLOB_HEADER int bcryptMagic = br.ReadInt32(); // BCRYPT_KEY_DATA_BLOB_HEADER.dwMagic if (bcryptMagic != Interop.BCrypt.BCRYPT_KEY_DATA_BLOB_HEADER.BCRYPT_KEY_DATA_BLOB_MAGIC) { throw new CryptographicException(SR.Cryptography_KeyBlobParsingError); } int dwVersion = br.ReadInt32(); // BCRYPT_KEY_DATA_BLOB_HEADER.dwVersion if (dwVersion != Interop.BCrypt.BCRYPT_KEY_DATA_BLOB_HEADER.BCRYPT_KEY_DATA_BLOB_VERSION1) { throw new CryptographicException(SR.Cryptography_KeyBlobParsingError); } int keyLength = br.ReadInt32(); // BCRYPT_KEY_DATA_BLOB_HEADER.cbKeyData byte[] key = br.ReadBytes(keyLength); return(key); } } }
private static void WritePublicKeyValue(XmlWriter writer, CngKey key) { BigInteger integer; BigInteger integer2; writer.WriteStartElement("PublicKey"); NCryptNative.UnpackEccPublicBlob(key.Export(CngKeyBlobFormat.EccPublicBlob), out integer, out integer2); writer.WriteStartElement("X"); writer.WriteAttributeString("Value", integer.ToString("R", CultureInfo.InvariantCulture)); writer.WriteAttributeString("xsi", "type", "http://www.w3.org/2001/XMLSchema-instance", "PrimeFieldElemType"); writer.WriteEndElement(); writer.WriteStartElement("Y"); writer.WriteAttributeString("Value", integer2.ToString("R", CultureInfo.InvariantCulture)); writer.WriteAttributeString("xsi", "type", "http://www.w3.org/2001/XMLSchema-instance", "PrimeFieldElemType"); writer.WriteEndElement(); writer.WriteEndElement(); }
// Just for convenience. public static string[] ExportKey(CngKey key) { byte[] blob = key.Export(CngKeyBlobFormat.EccPublicBlob); if (blob.Length != 72) throw new Exception($"Unexpected key length: {blob.Length}, expected 72"); var data = BitConverter.ToString(blob); var x = blob.Skip(8).Take(32).ToArray(); var y = blob.Skip(40).Take(32).ToArray(); var xHex = Convert.ToBase64String(x); var yHex = Convert.ToBase64String(y); var keyParts = new string[] { xHex, yHex }; return keyParts; }
internal ECDiffieHellmanCngPublicKey(CngKey key) : base(key.Export(CngKeyBlobFormat.EccPublicBlob)) { Contract.Requires(key != null && key.AlgorithmGroup == CngAlgorithmGroup.ECDiffieHellman); Contract.Ensures(m_format != null); m_format = CngKeyBlobFormat.EccPublicBlob; // // We need to make a copy of the key to prevent the situation where the ECDiffieHellmanCng algorithm // object is disposed (this disposing its key) before the ECDiffieHellmanCngPublic key is disposed. // // Accessing the handle in partial trust is safe because we're not exposing it back out to user code // new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert(); // This looks odd, but .Handle returns a duplicate, so we need to dispose it using (SafeNCryptKeyHandle importKey = key.Handle) { m_key = CngKey.Open(importKey, key.IsEphemeral ? CngKeyHandleOpenOptions.EphemeralKey : CngKeyHandleOpenOptions.None); } CodeAccessPermission.RevertAssert(); }
internal static byte[] ExportKeyBlob( CngKey key, bool includePrivateParameters, out CngKeyBlobFormat format, out string?curveName) { curveName = key.GetCurveName(out _); bool forceGenericBlob = false; if (string.IsNullOrEmpty(curveName)) { // Normalize curveName to null. curveName = null; forceGenericBlob = true; format = includePrivateParameters ? CngKeyBlobFormat.EccFullPrivateBlob : CngKeyBlobFormat.EccFullPublicBlob; } else { format = includePrivateParameters ? CngKeyBlobFormat.EccPrivateBlob : CngKeyBlobFormat.EccPublicBlob; } byte[] blob = key.Export(format); // Importing a known NIST curve as explicit parameters NCryptExportKey may // cause it to export with the dwMagic of the known curve and a generic blob body. // This combination can't be re-imported. So correct the dwMagic value to allow it // to import. if (forceGenericBlob) { FixupGenericBlob(blob); } return(blob); }
internal ECDiffieHellmanCngPublicKey(CngKey key) : base(key.Export(CngKeyBlobFormat.EccPublicBlob)) { Contract.Requires(key != null && key.AlgorithmGroup == CngAlgorithmGroup.ECDiffieHellman); Contract.Ensures(m_format != null); m_format = CngKeyBlobFormat.EccPublicBlob; // // We need to make a copy of the key to prevent the situation where the ECDiffieHellmanCng algorithm // object is disposed (this disposing its key) before the ECDiffieHellmanCngPublic key is disposed. // // Accessing the handle in partial trust is safe because we're not exposing it back out to user code // new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert(); // This looks odd, but .Handle returns a duplicate, so we need to dispose it using (SafeNCryptKeyHandle importKey = key.Handle) { m_key = CngKey.Open(importKey, key.IsEphemeral ? CngKeyHandleOpenOptions.EphemeralKey : CngKeyHandleOpenOptions.None); } CodeAccessPermission.RevertAssert(); }
public byte[] CreatePriVKeys() { privKey = CngKey.Create(CngAlgorithm.ECDiffieHellmanP256); pubKeyBlob = privKey.Export(CngKeyBlobFormat.EccPublicBlob); return pubKeyBlob; }
public void InitAliceKeys() { _aliceKeySignature = CngKey.Create(CngAlgorithm.ECDsaP521); _alicePubKeyBlob = _aliceKeySignature.Export(CngKeyBlobFormat.GenericPublicBlob); }
private static void WritePublicKeyValue(XmlWriter writer, CngKey key) { Contract.Requires(writer != null); Contract.Requires(key != null && (key.AlgorithmGroup == CngAlgorithmGroup.ECDsa || key.AlgorithmGroup == CngAlgorithmGroup.ECDiffieHellman)); writer.WriteStartElement(PublicKeyRoot); byte[] exportedKey = key.Export(CngKeyBlobFormat.EccPublicBlob); BigInteger x; BigInteger y; NCryptNative.UnpackEccPublicBlob(exportedKey, out x, out y); writer.WriteStartElement(XElement); writer.WriteAttributeString(ValueAttribute, x.ToString("R", CultureInfo.InvariantCulture)); writer.WriteAttributeString(XsiNamespacePrefix, XsiTypeAttribute, XsiNamespace, XsiTypeAttributeValue); writer.WriteEndElement(); // </X> writer.WriteStartElement(YElement); writer.WriteAttributeString(ValueAttribute, y.ToString("R", CultureInfo.InvariantCulture)); writer.WriteAttributeString(XsiNamespacePrefix, XsiTypeAttribute, XsiNamespace, XsiTypeAttributeValue); writer.WriteEndElement(); // </Y> writer.WriteEndElement(); // </PublicKey> }
private static void WritePublicKeyValue(XmlWriter writer, CngKey key) { BigInteger integer; BigInteger integer2; writer.WriteStartElement("PublicKey"); NCryptNative.UnpackEccPublicBlob(key.Export(CngKeyBlobFormat.EccPublicBlob), out integer, out integer2); writer.WriteStartElement("X"); writer.WriteAttributeString("Value", integer.ToString("R", CultureInfo.InvariantCulture)); writer.WriteAttributeString("xsi", "type", "http://www.w3.org/2001/XMLSchema-instance", "PrimeFieldElemType"); writer.WriteEndElement(); writer.WriteStartElement("Y"); writer.WriteAttributeString("Value", integer2.ToString("R", CultureInfo.InvariantCulture)); writer.WriteAttributeString("xsi", "type", "http://www.w3.org/2001/XMLSchema-instance", "PrimeFieldElemType"); writer.WriteEndElement(); writer.WriteEndElement(); }
public static byte[] EncodeJwt(string username, CngKey newKey) { byte[] t = ImportECDsaCngKeyFromCngKey(newKey.Export(CngKeyBlobFormat.EccPrivateBlob)); CngKey tk = CngKey.Import(t, CngKeyBlobFormat.EccPrivateBlob); ECDiffieHellmanCng ecKey = new ECDiffieHellmanCng(newKey); ecKey.HashAlgorithm = CngAlgorithm.Sha256; ecKey.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash; string b64Key = Convert.ToBase64String(ecKey.PublicKey.GetDerEncoded()); long exp = DateTimeOffset.UtcNow.AddDays(1).ToUnixTimeMilliseconds(); CertificateData certificateData = new CertificateData { Exp = exp, Iat = exp, ExtraData = new ExtraData { DisplayName = username, //Identity = "af6f7c5e-fcea-3e43-bf3a-e005e400e579", Identity = Guid.NewGuid().ToString(), }, Iss = "self", IdentityPublicKey = b64Key, CertificateAuthority = true, Nbf = exp, RandomNonce = new Random().Next(), }; // string txt = $@"{{ // ""exp"": 1467508449, // ""extraData"": {{ // ""displayName"": ""gurunxx"", // ""identity"": ""4e0199c6-7cfd-3550-b676-74398e0a5f1a"" // }}, // ""identityPublicKey"": ""{b64Key}"", // ""nbf"": 1467508448 //}}"; string val = JWT.Encode(certificateData, tk, JwsAlgorithm.ES384, new Dictionary<string, object> {{"x5u", b64Key}}); Log.Warn(JWT.Payload(val)); Log.Warn(string.Join(";", JWT.Headers(val))); //val = "eyJhbGciOiJFUzM4NCIsIng1dSI6Ik1IWXdFQVlIS29aSXpqMENBUVlGSzRFRUFDSURZZ0FFREVLck5xdk93Y25iV3I5aUtVQ0MyeklFRmZ6Q0VnUEhQdG5Kd3VEdnZ3VjVtd1E3QzNkWmhqd0g0amxWc2RDVTlNdVl2QllQRktCTEJkWU52K09ZeW1MTFJGTU9odVFuSDhuZFRRQVV6VjJXRTF4dHdlVG1wSVFzdXdmVzRIdzAifQo.eyJleHAiOjE0Njc1MDg0NDksImV4dHJhRGF0YSI6eyJkaXNwbGF5TmFtZSI6Imd1cnVueHgiLCJpZGVudGl0eSI6IjRlMDE5OWM2LTdjZmQtMzU1MC1iNjc2LTc0Mzk4ZTBhNWYxYSJ9LCJpZGVudGl0eVB1YmxpY0tleSI6Ik1IWXdFQVlIS29aSXpqMENBUVlGSzRFRUFDSURZZ0FFREVLck5xdk93Y25iV3I5aUtVQ0MyeklFRmZ6Q0VnUEhQdG5Kd3VEdnZ3VjVtd1E3QzNkWmhqd0g0amxWc2RDVTlNdVl2QllQRktCTEJkWU52K09ZeW1MTFJGTU9odVFuSDhuZFRRQVV6VjJXRTF4dHdlVG1wSVFzdXdmVzRIdzAiLCJuYmYiOjE0Njc1MDg0NDh9Cg.jpCqzTo8nNVEW8ArK1NFBaqLx6kyJV6wPF8cAU6UGav6cfMc60o3m5DjwspN-JcyC14AlcNiPdWX8TEm1QFhtScb-bXo4WOJ0dNYXV8iI_eCTCcXMFjX4vgIHpb9xfjv"; val = $@"{{ ""chain"": [""{val}""] }}"; return Encoding.UTF8.GetBytes(val); }
/// <summary> /// Imports an X.509 v3 certificate of a public key. /// </summary> /// <param name="client">DLMS client that is used to generate action.</param> /// <param name="key">Public key.</param> /// <returns>Generated action.</returns> public byte[][] Import(GXDLMSClient client, CngKey key) { return ImportCertificate(client, key.Export(CngKeyBlobFormat.EccPublicBlob)); }
private void InitAliceKeys() { _aliceKey = CngKey.Create(CngAlgorithm.Rsa); _alicePubKeyBlob = _aliceKey.Export(CngKeyBlobFormat.GenericPublicBlob); }
public static byte[] EncodeSkinJwt(CngKey newKey) { byte[] t = ImportECDsaCngKeyFromCngKey(newKey.Export(CngKeyBlobFormat.EccPrivateBlob)); CngKey tk = CngKey.Import(t, CngKeyBlobFormat.EccPrivateBlob); ECDiffieHellmanCng ecKey = new ECDiffieHellmanCng(newKey); ecKey.HashAlgorithm = CngAlgorithm.Sha256; ecKey.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash; var b64Key = Base64Url.Encode(ecKey.PublicKey.GetDerEncoded()); Skin skin = new Skin { Slim = false, Texture = Encoding.Default.GetBytes(new string('Z', 8192)), SkinType = "Standard_Custom" }; string skin64 = Convert.ToBase64String(skin.Texture); string skinData = $@" {{ ""ClientRandomId"": {new Random().Next()}, ""ServerAddress"": ""pe.mineplex.com:19132"", ""SkinData"": ""{skin64}"", ""SkinId"": ""{skin.SkinType}"" }}"; string val = JWT.Encode(skinData, tk, JwsAlgorithm.ES384, new Dictionary<string, object> { { "x5u", b64Key } }); return Encoding.UTF8.GetBytes(val); }
/// <summary> /// Экспорт двоичных данных ключа /// </summary> /// <param name="cngKey">Оригинальный ключ.</param> /// <param name="isPublic">Ключ является публичным?</param> /// <returns>Двоичные данные ключа.</returns> private byte[] ExportKeyBinData(CngKey cngKey, bool isPublic) { // Экспортируем все доступные данные ключа byte[] cngKeyLongBinData = cngKey.Export(isPublic ? CngKeyBlobFormat.EccPublicBlob : CngKeyBlobFormat.EccPrivateBlob); // Вычисляем длину ключа, укороченного на префикс int cngKeyShortBinLength = (cngKeyLongBinData.Length - CNG_KEY_PREFIX_LEN); // Наполняем укороченный ключ... var cngKeyShortBin = new byte[cngKeyShortBinLength]; Array.Copy(cngKeyLongBinData, CNG_KEY_PREFIX_LEN, cngKeyShortBin, 0, cngKeyShortBinLength); //...и возвращаем его return cngKeyShortBin; }