public static bool ValidatePubKey(ICollection <tbl_PublicKey> userKeys, SshPublicKey loginKey) { var loginStream = new MemoryStream(); loginKey.SavePublicKey(loginStream, SshPublicKeyFormat.Pkcs8); var loginValue = Encoding.ASCII.GetString(loginStream.ToArray()); foreach (var userKey in userKeys) { var pubKeyBytes = Encoding.ASCII.GetBytes(userKey.KeyValue); var pubKeyInfo = new PublicKeyInfo(); pubKeyInfo.Load(new MemoryStream(pubKeyBytes)); var pubStream = new MemoryStream(); var pubKey = new SshPublicKey(pubKeyInfo); pubKey.SavePublicKey(pubStream, SshPublicKeyFormat.Pkcs8); var pubKeyValue = Encoding.ASCII.GetString(pubStream.ToArray()); if (loginValue == pubKeyValue) { return(true); } } return(false); }
public PublicKeyInfo GetPublicKey() { PublicKeyInfo info = new PublicKeyInfo(); info.Fingerprint = _cert.Thumbprint; info.Key = Convert.ToBase64String(_cert.Export(X509ContentType.Cert)); return(info); }
public static void ResolvePublicKey(ICoreObject cardReaderSlot, uint paomVersionID, string paomVersionIdString, out PublicKeyInfo publicKeyInfo) { OmsSessionConfigurator.ResolvePublicKey(cardReaderSlot, paomVersionID, paomVersionIdString, out publicKeyInfo); }
//public override void OnActionExecuting(ActionExecutingContext context) //{ // ICryptoRSA encryption = (ICryptoRSA)context.HttpContext.RequestServices.GetService(typeof(ICryptoRSA)); // using (HttpClient httpClient = new HttpClient()) // { // httpClient.BaseAddress = new Uri("http://localhost:51049/api/"); // httpClient.DefaultRequestHeaders.Accept.Clear(); // httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // HttpResponseMessage httpResponseMessage = httpClient.GetAsync("security").Result; // httpResponseMessage.EnsureSuccessStatusCode(); // string json = httpResponseMessage.Content.ReadAsStringAsync().Result; // PublicKeyInfo publicKeyInfo = JsonConvert.DeserializeObject<PublicKeyInfo>(json); // encryption.ImportBinaryKeys(Convert.FromBase64String(publicKeyInfo.PublicKey)); // } //} public override void OnActionExecuting(ActionExecutingContext context) { SecurityRequester securityRepository = (SecurityRequester)context.HttpContext.RequestServices.GetService(typeof(SecurityRequester)); ICryptoRSA cryptoRSA = (ICryptoRSA)context.HttpContext.RequestServices.GetService(typeof(ICryptoRSA)); PublicKeyInfo publicKeyInfo = securityRepository.Get(); cryptoRSA.ImportBinaryKeys(Convert.FromBase64String(publicKeyInfo.PublicKey)); }
public PublicKeyInfo Get() { PublicKeyInfo publicKeyInfo = new PublicKeyInfo() { PublicKey = Convert.ToBase64String(_cryptoService.BinaryPublicKey) }; return(publicKeyInfo); }
/* * openssh uses base64 and special formatting for public keys like with "authorized_keys" * https://man.openbsd.org/ssh-keygen */ public static StringBuilder ExportPubKeyBase64(tbl_User user, ICollection <tbl_PublicKey> keys) { var callPath = $"{MethodBase.GetCurrentMethod().DeclaringType.Name}.{MethodBase.GetCurrentMethod().Name}"; var sb = new StringBuilder(); foreach (var key in keys) { var pubBytes = Encoding.ASCII.GetBytes(key.KeyValue); var pubKeyInfo = new PublicKeyInfo(); pubKeyInfo.Load(new MemoryStream(pubBytes)); var pubStream = new MemoryStream(); var pubKey = new SshPublicKey(pubKeyInfo); pubKey.SavePublicKey(pubStream, SshPublicKeyFormat.Pkcs8); var algo = string.Empty; switch (pubKey.KeyAlgorithm) { case SshHostKeyAlgorithm.DSS: algo = "ssh-dsa"; break; case SshHostKeyAlgorithm.RSA: algo = "ssh-rsa"; break; //case SshHostKeyAlgorithm.ECDsaNistP256: // algo = "ecdsa-sha2-nistp256"; // break; //case SshHostKeyAlgorithm.ECDsaNistP384: // algo = "ecdsa-sha2-nistp384"; // break; //case SshHostKeyAlgorithm.ECDsaNistP521: // algo = "ecdsa-sha2-nistp521"; // break; //case SshHostKeyAlgorithm.ED25519: // algo = "ssh-ed25519"; // break; default: { Log.Warning($"'{callPath}' '{user.IdentityAlias}' algorithm {pubKey.KeyAlgorithm} not supported"); continue; } } sb.AppendLine($"{algo} {Convert.ToBase64String(pubKey.GetPublicKey())} {key.Comment}"); } return(sb); }
public static SubjectIdentifierOrKey ToSubjectIdentifierOrKey(this CERT_PUBLIC_KEY_INFO publicKeyInfo) { int keyLength = Interop.Crypt32.CertGetPublicKeyLength(MsgEncodingType.All, ref publicKeyInfo); string oidValue = publicKeyInfo.Algorithm.pszObjId.ToStringAnsi(); AlgorithmIdentifier algorithmId = new AlgorithmIdentifier(Oid.FromOidValue(oidValue, OidGroup.PublicKeyAlgorithm), keyLength); byte[] keyValue = publicKeyInfo.PublicKey.ToByteArray(); PublicKeyInfo pki = new PublicKeyInfo(algorithmId, keyValue); return(new SubjectIdentifierOrKey(SubjectIdentifierOrKeyType.PublicKeyInfo, pki)); }
public static byte[] ExportPubKey(tbl_PublicKey key, SshPublicKeyFormat pubKeyFormat) { var pubBytes = Encoding.ASCII.GetBytes(key.KeyValue); var pubKeyInfo = new PublicKeyInfo(); pubKeyInfo.Load(new MemoryStream(pubBytes)); var pubStream = new MemoryStream(); var pubKey = new SshPublicKey(pubKeyInfo); pubKey.SavePublicKey(pubStream, pubKeyFormat); return(pubStream.ToArray()); }
public static void TestKeyAgreeOriginatorIdentifierOrKey_RoundTrip() { KeyAgreeRecipientInfo recipient = EncodeKeyAgreel(); SubjectIdentifierOrKey originator = recipient.OriginatorIdentifierOrKey; Assert.Equal(SubjectIdentifierOrKeyType.PublicKeyInfo, originator.Type); object value = originator.Value; Assert.True(value is PublicKeyInfo); PublicKeyInfo pki = (PublicKeyInfo)value; AlgorithmIdentifier a = pki.Algorithm; Assert.Equal(Oids.Dh, a.Oid.Value); byte[] key = pki.KeyValue; Assert.NotNull(key); // Key is randomly generated (and encoding makes the length unpredictable) so not much we can do here. Assert.NotEmpty(key); }
private void Validate() { if (Issuer.IsNull()) { throw new InvalidOperationException("Issuer is empty"); } if (Subject.IsNull()) { throw new InvalidOperationException("Issuer is empty"); } if (PublicKeyInfo.IsNull()) { throw new InvalidOperationException("PublicKeyInfo is empty"); } }
public static void TestKeyAgreeOriginatorIdentifierOrKey_FixedValue() { KeyAgreeRecipientInfo recipient = FixedValueKeyAgree1(); SubjectIdentifierOrKey originator = recipient.OriginatorIdentifierOrKey; Assert.Equal(SubjectIdentifierOrKeyType.PublicKeyInfo, originator.Type); object value = originator.Value; Assert.True(value is PublicKeyInfo); PublicKeyInfo pki = (PublicKeyInfo)value; AlgorithmIdentifier a = pki.Algorithm; Assert.Equal(Oids.Dh, a.Oid.Value); byte[] key = pki.KeyValue; byte[] expectedKey = ("0281806F96EF8C53A6919CC976E88B8F426696E7B7970ABC6BD4ABBDCF4CF34F89CEB6E8EF675000FAD2ECA3CAF9D0E51B00" + "4FD19A943F1779748F343FE2059E6E8208D64CB2A5BF33B2C41C20F4AE950D8F8BD720F5747D7930AF86C612088747B5315A" + "E68159A5AE8A80E928AA71F4E889CB2D581845EDC8F79DA5894CB7A40F9FBE").HexToByteArray(); Assert.Equal(expectedKey, key); }
public byte[] Get() { try { var path = Path.Combine(Directory.GetCurrentDirectory(), "Certificates\\DevCertRootCA.pfx"); Certificate ca = Certificate.LoadPfx(path, "", KeySetOptions.MachineKeySet); // prepare certificate info var info = new CertificateInfo(); // specify certificate validity range info.EffectiveDate = DateTime.Now.AddDays(-1); info.ExpirationDate = info.EffectiveDate.AddYears(1); // specify certificate subject for a client certificate info.Subject = new DistinguishedName("CN=Sample Certificate"); // specify certificate usage for a client certificate info.Usage = KeyUses.DigitalSignature | KeyUses.KeyEncipherment | KeyUses.DataEncipherment; // specify certificate extended usage for a client certificate info.SetExtendedUsage(ExtendedUsageOids.ClientAuthentication, ExtendedUsageOids.EmailProtection); // sets a unique serial number info.SetSerialNumber(Guid.NewGuid().ToByteArray()); // use SHA-256 signature algorithm info.SignatureHashAlgorithm = HashingAlgorithmId.SHA256; // generate a 2048-bit RSA key for the certificate PrivateKeyInfo privateKey; using (var alg = new AsymmetricKeyAlgorithm()) { alg.GenerateKey(AsymmetricKeyAlgorithmId.RSA, 2048); privateKey = alg.GetPrivateKey(); } // create the certificate signed by the CA certificate PublicKeyInfo publicKey = privateKey.GetPublicKey(); Certificate certificate = CertificateIssuer.Issue(ca, info, publicKey); // associate the private key with the certificate certificate.Associate(privateKey); using (CertificateStore store = new CertificateStore(CertificateStoreName.My, CertificateStoreLocation.LocalMachine)) { store.Add(certificate); } using (CertificateStore store = new CertificateStore(CertificateStoreName.TrustedPeople, CertificateStoreLocation.LocalMachine)) { store.Add(certificate); } var memoryStream = new MemoryStream(); certificate.Save(memoryStream, CertificateFormat.Pfx); return(memoryStream.ToArray()); } catch (Exception ex) { _logger.LogError(ex.Message); throw ex; } }
public static void ResolvePublicKey(ICoreObject target, out PublicKeyInfo publicKeyInfo) { OmsSessionConfigurator.ResolvePublicKey(target, out publicKeyInfo); }