protected virtual void Dispose(bool disposing) { lock (_lock) { if (_disposed) { return; } _disposed = true; } if (disposing) { // free managed objects } // free unmanaged objects if (_encryptCtx != IntPtr.Zero) { OpenSSL.EVP_CIPHER_CTX_free(_encryptCtx); _encryptCtx = IntPtr.Zero; } if (_decryptCtx != IntPtr.Zero) { OpenSSL.EVP_CIPHER_CTX_free(_decryptCtx); _decryptCtx = IntPtr.Zero; } }
public override void cipherEncrypt(byte[] plaintext, uint plen, byte[] ciphertext, ref uint clen) { OpenSSL.SetCtxNonce(_encryptCtx, _encNonce, true); // buf: all plaintext // outbuf: ciphertext + tag int ret; int tmpLen = 0; clen = 0; var tagBuf = new byte[tagLen]; ret = OpenSSL.EVP_CipherUpdate(_encryptCtx, ciphertext, out tmpLen, plaintext, (int)plen); if (ret != 1) { throw new CryptoErrorException("openssl: fail to encrypt AEAD"); } clen += (uint)tmpLen; // For AEAD cipher, it should not output anything ret = OpenSSL.EVP_CipherFinal_ex(_encryptCtx, ciphertext, ref tmpLen); if (ret != 1) { throw new CryptoErrorException("openssl: fail to finalize AEAD"); } if (tmpLen > 0) { throw new System.Exception("openssl: fail to finish AEAD"); } OpenSSL.AEADGetTag(_encryptCtx, tagBuf, tagLen); Array.Copy(tagBuf, 0, ciphertext, clen, tagLen); clen += (uint)tagLen; }
public void RSASignAndVerify2048() { string sign = OpenSSL.RSASign("ABCDeFGH", _private2048Key); bool valid = OpenSSL.RSAVerify("ABCDeFGH", sign, _public2048Key); Assert.True(valid); }
protected override void initCipher(byte[] iv, bool isEncrypt) { base.initCipher(iv, isEncrypt); IntPtr cipherInfo = OpenSSL.GetCipherInfo(_innerLibName); if (cipherInfo == IntPtr.Zero) { throw new System.Exception("openssl: cipher not found"); } IntPtr ctx = OpenSSL.EVP_CIPHER_CTX_new(); if (ctx == IntPtr.Zero) { throw new System.Exception("fail to create ctx"); } if (isEncrypt) { _encryptCtx = ctx; } else { _decryptCtx = ctx; } byte[] realkey; if (_method == "rc4-md5") { byte[] temp = new byte[keyLen + ivLen]; realkey = new byte[keyLen]; Array.Copy(_key, 0, temp, 0, keyLen); Array.Copy(iv, 0, temp, keyLen, ivLen); realkey = MbedTLS.MD5(temp); } else { realkey = _key; } var ret = OpenSSL.EVP_CipherInit_ex(ctx, cipherInfo, IntPtr.Zero, null, null, isEncrypt ? OpenSSL.OPENSSL_ENCRYPT : OpenSSL.OPENSSL_DECRYPT); if (ret != 1) { throw new System.Exception("openssl: fail to set key length"); } ret = OpenSSL.EVP_CIPHER_CTX_set_key_length(ctx, keyLen); if (ret != 1) { throw new System.Exception("openssl: fail to set key length"); } ret = OpenSSL.EVP_CipherInit_ex(ctx, IntPtr.Zero, IntPtr.Zero, realkey, _method == "rc4-md5" ? null : iv, isEncrypt ? OpenSSL.OPENSSL_ENCRYPT : OpenSSL.OPENSSL_DECRYPT); if (ret != 1) { throw new System.Exception("openssl: cannot set key and iv"); } OpenSSL.EVP_CIPHER_CTX_set_padding(ctx, 0); }
public void RSAEntry() { string mask = OpenSSL.RSAEncrypt("ABCDeFGH", _publicKey); string opened = OpenSSL.RSADecrypt(mask, _privateKey); Assert.Equal("ABCDeFGH", opened); }
/// <summary> /// Generar certificado nuevo /// </summary> /// <param name="address">Dirección IP</param> public static string AutoGenerateCertificate(IPAddress address) { bool usePipe = RuntimeInformation.IsOSPlatform(OSPlatform.Windows); string baseName = address.ToString(); Debug.WriteLine("SSLAutogen", "Generando llave para nuevo certificado de IP: " + address, VerbosityLevel.Debug); string key = OpenSSL.GenerateKey(GetCert(OpenSSL.FilenamePrivateKey(baseName)), maxWait: 10000); Debug.WriteLine("SSLAutogen", "Generando solicitud de firmado para nuevo certificado de IP: " + address, VerbosityLevel.Debug); string csr = OpenSSL.GenerateCsr(GetCert(OpenSSL.FilenameCsr(baseName)), key, new CertificateSubject { CommonName = baseName, Country = "MX", State = "Aguascalientes", Locality = "Aguascalientes", Organization = "Veteris de Aguascalientes", OrganizationUnit = "Automated Server Deployment" }, maxWait: 10000); string ca = GetCert(FILENAME_CA + OpenSSL.EXT_CERTIFICATE_AUTHORITY); string caKey = GetCert(FILENAME_CA + OpenSSL.EXT_PRIVATE_KEY); Debug.WriteLine("SSLAutogen", "Generando certificado de IP: " + address, VerbosityLevel.Debug); string crt = OpenSSL.GenerateCrt(GetCert(OpenSSL.FilenameCrt(baseName)), csr, ca, caKey, PASSWORD_DEFAULT_CA, maxWait: 10000, usePipe: usePipe).Result; Debug.WriteLine("SSLAutogen", "Convirtiendo certificado de IP: " + address + ", a formato PKCS12", VerbosityLevel.Debug); string pfx = OpenSSL.ConvertToPkcs12(GetCert(OpenSSL.FilenamePkcs12(baseName)), crt, key, PASSWORD_DEFAULT_CA, maxWait: 10000, usePipe: usePipe).Result; Debug.WriteLine("SSLAutogen", "Se creo el certificado PKCS12 de IP: " + address, VerbosityLevel.Debug); return(pfx); }
public override void InitCipher(byte[] salt, bool isEncrypt, bool isUdp) { base.InitCipher(salt, isEncrypt, isUdp); _cipherInfoPtr = OpenSSL.GetCipherInfo(_innerLibName); if (_cipherInfoPtr == IntPtr.Zero) { throw new System.Exception("openssl: cipher not found"); } IntPtr ctx = OpenSSL.EVP_CIPHER_CTX_new(); if (ctx == IntPtr.Zero) { throw new System.Exception("openssl: fail to create ctx"); } if (isEncrypt) { _encryptCtx = ctx; } else { _decryptCtx = ctx; } DeriveSessionKey(isEncrypt ? _encryptSalt : _decryptSalt, _Masterkey, isEncrypt ? _opensslEncSubkey : _opensslDecSubkey); var ret = OpenSSL.EVP_CipherInit_ex(ctx, _cipherInfoPtr, IntPtr.Zero, null, null, isEncrypt ? OpenSSL.OPENSSL_ENCRYPT : OpenSSL.OPENSSL_DECRYPT); if (ret != 1) { throw new System.Exception("openssl: fail to init ctx"); } ret = OpenSSL.EVP_CIPHER_CTX_set_key_length(ctx, keyLen); if (ret != 1) { throw new System.Exception("openssl: fail to set key length"); } ret = OpenSSL.EVP_CIPHER_CTX_ctrl(ctx, OpenSSL.EVP_CTRL_AEAD_SET_IVLEN, nonceLen, IntPtr.Zero); if (ret != 1) { throw new System.Exception("openssl: fail to set AEAD nonce length"); } ret = OpenSSL.EVP_CipherInit_ex(ctx, IntPtr.Zero, IntPtr.Zero, isEncrypt ? _opensslEncSubkey : _opensslDecSubkey, null, isEncrypt ? OpenSSL.OPENSSL_ENCRYPT : OpenSSL.OPENSSL_DECRYPT); if (ret != 1) { throw new System.Exception("openssl: cannot set key"); } OpenSSL.EVP_CIPHER_CTX_set_padding(ctx, 0); }
private void GenerateKeyBtn_Click(object sender, RoutedEventArgs e) { if (!ValidateCreateCAKey()) { return; } if (!MatchRetypePassword()) { return; } // genrsa -des3 -passout pass:yourpassword -out /path/to/your/key_file 1024 // Process user inputs to create CA key string _OpenSSLUIPATHEnvVar = OpenSSLEnvVarProvider.GetOPENSSLUIPATHEnvVar(); if (string.IsNullOrEmpty(_OpenSSLUIPATHEnvVar)) { System.Windows.MessageBox.Show("OPENSSL_UI_PATH is not set, Please set the path before continue!", "Error", MessageBoxButton.OK, MessageBoxImage.Error); } else { // Variable is available, Run OpenSSL string _KeyName = _CaKeyNameTF.Text; string _KeyLocation = _KeyLocationTF.Text; string _BitLength = _BitLengthCmb.Text; string _Password = PasswordRetypeTF.Password; if (string.IsNullOrEmpty(_BitLength)) { _BitLength = OpenSSLConfig.DEFAULT_BIT_LENGTH; } string _InvocationParameters; // Flag to distinguise whether user has keyed in password fields if (PassPhraseProvided()) { // Execute openssl command to create a key with passphrase _InvocationParameters = COMMAND_GENRSA + " -aes128 -passout pass:"******" -out \"" + Path.Combine(_KeyLocation, _KeyName + " " + _BitLength) + "\""; } else { // Create a key without a passphase _InvocationParameters = COMMAND_GENRSA + " -out \"" + Path.Combine(_KeyLocation, _KeyName + " " + _BitLength) + "\""; } // Start an OpenSSL process with descriptive error if not found OpenSSL.TryOpenSSL(_InvocationParameters); } }
protected override void cipherUpdate(bool isCipher, int length, byte[] buf, byte[] outbuf) { if (_disposed) { throw new ObjectDisposedException(ToString()); } var ret = OpenSSL.EVP_CipherUpdate(isCipher ? _encryptCtx : _decryptCtx, outbuf, out var outlen, buf, length); if (ret != 1) { throw new Exception($@"ret is {ret}"); } Debug.Assert(outlen == length); }
protected override void cipherUpdate(bool isEncrypt, int length, byte[] buf, byte[] outbuf) { // C# could be multi-threaded if (_disposed) { throw new ObjectDisposedException(this.ToString()); } var ret = OpenSSL.EVP_CipherUpdate(isEncrypt ? _encryptCtx : _decryptCtx, outbuf, out var outlen, buf, length); if (ret != 1) { throw new CryptoErrorException($"ret is {ret}"); } Debug.Assert(outlen == length); }
public static API.ECDH_Struct GetECDHKeys2() { API.ECDH_Struct ECDH = new API.ECDH_Struct(); byte[] Sharekey = new byte[16]; byte[] SvrPubKey = new byte[] { 0x4, 0xBF, 0x47, 0xA1, 0xCF, 0x78, 0xA6, 0x29, 0x66, 0x8B, 0xB, 0xC3, 0x9F, 0x8E, 0x54, 0xC9, 0xCC, 0xF3, 0xB6, 0x38, 0x4B, 0x8, 0xB8, 0xAE, 0xEC, 0x87, 0xDA, 0x9F, 0x30, 0x48, 0x5E, 0xDF, 0xE7, 0x67, 0x96, 0x9D, 0xC1, 0xA3, 0xAF, 0x11, 0x15, 0xFE, 0xD, 0xCC, 0x8E, 0xB, 0x17, 0xCA, 0xCF }; ECDH.PublicKey = new byte[25]; ECDH.Sharekey = new byte[16]; var eckey = OpenSSL.EC_KEY_new_by_curve_name(711); var ec_group = OpenSSL.EC_KEY_get0_group(eckey); var ec_point = OpenSSL.EC_POINT_new(ec_group); OpenSSL.EC_KEY_generate_key(eckey); OpenSSL.EC_POINT_point2oct(ec_group, (System.IntPtr)OpenSSL.EC_KEY_get0_public_key(eckey), 2, ECDH.PublicKey, 25, (System.IntPtr) 0); OpenSSL.EC_POINT_oct2point(ec_group, ec_point, SvrPubKey, 49, (System.IntPtr) 0); OpenSSL.ECDH_compute_key(ECDH.Sharekey, 16, ec_point, eckey, (System.IntPtr) 0); ECDH.Sharekey = API.MD5Hash(Sharekey); return(ECDH); }
public static API.ECDH_Struct GetECDHKeys() { API.ECDH_Struct ECDH = new API.ECDH_Struct(); byte[] PrivateKey = new byte[1024]; byte[] PublicKey = new byte[1024]; byte[] Sharekey = new byte[16]; byte[] SvrPubKey = API.HexStrToByteArray("04EBCA94D733E399B2DB96EACDD3F69A8BB0F74224E2B44E3357812211D2E62EFBC91BB553098E25E33A799ADC7F76FEB208DA7C6522CDB0719A305180CC54A82E"); var eckey = OpenSSL.EC_KEY_new_by_curve_name(415); if (eckey == IntPtr.Zero) { return(ECDH); } var res = OpenSSL.EC_KEY_generate_key(eckey); var ec_group = OpenSSL.EC_KEY_get0_group(eckey); var ec_point = OpenSSL.EC_KEY_get0_public_key(eckey); var PublicKeyLen = OpenSSL.EC_POINT_point2oct(ec_group, (System.IntPtr)ec_point, 4, PublicKey, 65, (System.IntPtr) 0); Array.Resize(ref PublicKey, PublicKeyLen); ECDH.PublicKey = PublicKey; ec_point = (int)OpenSSL.EC_KEY_get0_private_key(eckey); var PrivateKeyLen = OpenSSL.BN_bn2mpi((System.IntPtr)ec_point, PrivateKey); Array.Resize(ref PrivateKey, (System.Int32)PrivateKeyLen); ECDH.PrivateKey = PrivateKey; eckey = OpenSSL.EC_KEY_new_by_curve_name(415); if (eckey == IntPtr.Zero) { return(ECDH); } var bn = OpenSSL.BN_new(); OpenSSL.BN_mpi2bn(ECDH.PrivateKey, ECDH.PrivateKey.Length, bn); OpenSSL.EC_KEY_set_private_key(eckey, bn); OpenSSL.BN_free(bn); ec_group = OpenSSL.EC_KEY_get0_group(eckey); ec_point = (int)OpenSSL.EC_POINT_new(ec_group); OpenSSL.EC_POINT_oct2point(ec_group, (System.IntPtr)ec_point, SvrPubKey, SvrPubKey.Length, (System.IntPtr) 0); OpenSSL.ECDH_compute_key(Sharekey, 16, (System.IntPtr)ec_point, eckey, IntPtr.Zero); ECDH.Sharekey = API.MD5Hash(Sharekey); return(ECDH); }
public static byte[] GetECDHKeysEx(byte[] peerRawPublicKey, byte[] PublicKey, byte[] PrivateKey) { API.ECDH_Struct ECDH = new API.ECDH_Struct(); //Dim PrivateKey(1023) As Byte // Dim PublicKey(1023) As Byte //Dim Sharekey(15) As Byte var ec_key = OpenSSL.EC_KEY_new_by_curve_name(415); var bn = OpenSSL.BN_new(); OpenSSL.BN_mpi2bn(PrivateKey, PrivateKey.Length, bn); OpenSSL.EC_KEY_set_private_key(ec_key, bn); OpenSSL.BN_free(bn); var ec_group = OpenSSL.EC_KEY_get0_group(ec_key); var ec_point = OpenSSL.EC_POINT_new(ec_group); OpenSSL.EC_POINT_oct2point(ec_group, ec_point, peerRawPublicKey, peerRawPublicKey.Length, (System.IntPtr) 0); OpenSSL.ECDH_compute_key(PublicKey, 16, ec_point, ec_key, (System.IntPtr) 0); return(API.MD5Hash(PublicKey)); }
public override void cipherDecrypt(byte[] ciphertext, uint clen, byte[] plaintext, ref uint plen) { OpenSSL.SetCtxNonce(_decryptCtx, _decNonce, false); // buf: ciphertext + tag // outbuf: plaintext int ret; int tmpLen = 0; plen = 0; // split tag byte[] tagbuf = new byte[tagLen]; Array.Copy(ciphertext, (int)(clen - tagLen), tagbuf, 0, tagLen); OpenSSL.AEADSetTag(_decryptCtx, tagbuf, tagLen); ret = OpenSSL.EVP_CipherUpdate(_decryptCtx, plaintext, out tmpLen, ciphertext, (int)(clen - tagLen)); if (ret != 1) { throw new CryptoErrorException("openssl: fail to decrypt AEAD"); } plen += (uint)tmpLen; // For AEAD cipher, it should not output anything ret = OpenSSL.EVP_CipherFinal_ex(_decryptCtx, plaintext, ref tmpLen); if (ret <= 0) { // If this is not successful authenticated throw new CryptoErrorException($"ret is {ret}"); } if (tmpLen > 0) { throw new System.Exception("openssl: fail to finish AEAD"); } }
/// <summary> /// Obtener ruta a un certificado generado automaticamente /// </summary> /// <param name="address">Dirección IP utilizada</param> public static string GetAutogenCertFilepath(IPAddress address) { return(DIRECTORY_CERTS + OpenSSL.FilenamePkcs12(address.ToString())); }
private async Task LoadConfigurationDataAsync(ZookeeperClient client, bool firstLoad, string path) { try { var data = (await client.GetDataAsync(path)).ToArray(); if (firstLoad) { await client.SubscribeDataChange(path, this.OnNodeDataChangeAsync); } if (data != null) { LoadKey(); data = OpenSSL.RSADecrypt(data, _key); //data = OpenSSL.RSADecrypt(data, _key); string json = String.Empty; if (data.Length <= 3) { throw new Exception("配置中心返回了错误的配置数据"); } if (data[0] == 0xef && data[1] == 0xbb && data[2] == 0xbf) { json = new UTF8Encoding(false).GetString(data, 3, data.Length - 3); } else { json = Encoding.UTF8.GetString(data); } var parser = new JsonConfigurationParser(); //配置中心不能影响本地的用于构造配置节点路径的配置,否则将造成拉取错误配置。 this.Data = parser.Parse(json, ConfigurationPath.Combine("Schubert", "Group"), ConfigurationPath.Combine("Schubert", "AppSystemName"), ConfigurationPath.Combine("Schubert", "Version"), ConfigurationPath.Combine("Schubert", "Env"), ConfigurationPath.Combine("Schubert", "Configuration")); OnReload(); //Microsoft.Extensions.Configuration.FileConfigurationProvider的源码有这个代码OnReload() //OnReload会让GetReloadToken通知ChangeToken.OnChange去调用changeTokenConsumer的委托 //changeTokenConsumer的委托中如果走load等同逻辑的代码,机会再次调用OnReload,然后就挂 //ChangeToken.OnChange方案的用处是用来做外置事件源的处理,不能做内部事件调用 //Action reload = OnReload; //reload(); //不加OnReload,完全不起作用,但是为什么叫OnReload } } catch (TimeoutException ex) { string error = $"连接到配置中心(zk_server: {client.Options.ConnectionString })超时。"; HandleError(firstLoad, error, ex); } catch (FormatException ex) { string error = $"从配置中心加载配置发生错误,可能由于配置文件格式错误(zk_server: {client.Options.ConnectionString }, paht:{path})超时。"; HandleError(firstLoad, error, ex); } }