//
// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄
// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █
// █__ --█ █__ --█ ◄█ - █
// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█
// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉
// │ Copyright (c) JP Dillingham.
// │
// │ This program is free software: you can redistribute it and/or modify
// │ it under the terms of the GNU Affero General Public License as published
// │ by the Free Software Foundation, version 3.
// │
// │ This program is distributed in the hope that it will be useful,
// │ but WITHOUT ANY WARRANTY; without even the implied warranty of
// │ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// │ GNU Affero General Public License for more details.
// │
// │ You should have received a copy of the GNU Affero General Public License
// │ along with this program. If not, see https://www.gnu.org/licenses/.
// │
// │ This program is distributed with Additional Terms pursuant to Section 7
// │ of the AGPLv3. See the LICENSE file in the root directory of this
// │ project for the complete terms and conditions.
// │
// │ https://slskd.org
// │
// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌
// │ SPDX-FileCopyrightText: JP Dillingham
// │ SPDX-License-Identifier: AGPL-3.0-only
// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈
//
namespace slskd.Cryptography
{
using System;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
///
/// X509 utility methods.
///
public static class X509
{
///
/// Generates an X509 certificate for the specified .
///
/// The certificate subject.
/// The optional password for the certificate.
/// The optional key storage flags for the certificate.
/// The generated certificate.
public static X509Certificate2 Generate(string subject, string password = null, X509KeyStorageFlags x509KeyStorageFlags = X509KeyStorageFlags.MachineKeySet)
{
password ??= Guid.NewGuid().ToString();
using RSA rsa = RSA.Create(2048);
var request = new CertificateRequest(
new X500DistinguishedName($"CN={subject}"),
rsa,
HashAlgorithmName.SHA256,
RSASignaturePadding.Pkcs1);
var certificate = request.CreateSelfSigned(
new DateTimeOffset(DateTime.UtcNow.AddDays(-1)),
new DateTimeOffset(DateTime.UtcNow.AddDays(36500)));
return X509CertificateLoader.LoadPkcs12(certificate.Export(X509ContentType.Pkcs12, password), password, x509KeyStorageFlags);
}
///
/// Validates an X509 certificate given a PFX and optional .
///
/// The path to the PFX certificate file to validate.
/// The optional password for the certificate.
/// The error message, if the certificate is invalid.
/// A value indicating whether the certificate is valid.
public static bool TryValidate(string fileName, string password, out string result)
{
result = null;
try
{
_ = X509CertificateLoader.LoadPkcs12FromFile(fileName, password);
return true;
}
catch (Exception ex)
{
result = ex.Message;
return false;
}
}
}
}