• NeonSDK
  • NeonKUBE
Search Results for

    Show / Hide Table of Contents
    • Neon
      • Build
    • Neon.Blazor
      • BlazorHelper
      • BodyOutlet
      • ClientRenderContext
      • DOMRectReadOnly
      • EventHandlers
      • FileDownloader
      • HtmlElement
      • IRenderContext
      • IntersectionChangedEventArgs
      • IntersectionObserver
      • IntersectionObserverContext
      • MobileDetector
      • NeonBlazorExtensions
      • ServerRenderContext
      • SwipeDirection
      • SwipeHandler
    • Neon.Blazor.Analyzers
      • SvgGenerator
      • SvgGenerator.Svg
    • Neon.BuildInfo
      • ThisAssembly
      • ThisAssembly.Git
      • ThisAssembly.Git.BaseVersion
      • ThisAssembly.Git.SemVer
    • Neon.CSharp
      • CSharpHelper
      • CompilerErrorException
      • MetadataReferences
    • Neon.Cassandra
      • KeyspaceStatus
      • RowSetExtensions
      • SchemaManager
      • SchemaManagerException
      • SchemaStatus
      • SessionExtensions
    • Neon.Collections
      • ArgDictionary
      • Bits
      • IObjectDictionary
      • NiceDictionary<TKey, TValue>
      • ObjectDictionary
    • Neon.Common
      • AppDomainExtensions
      • Block
      • BlockArray
      • ByteEncoding
      • ByteUnits
      • CommandLine
      • CommandLine.OptionDefinition
      • CommandLine.Redactor
      • CpuArchitecture
      • Credentials
      • DateTimeExtensions
      • EnumExtensions
      • EnvironmentParser
      • EnvironmentParser.Parser<T>
      • EnvironmentParser.Validator<T>
      • EnvironmentParser.VariableSource
      • ExceptionExtensions
      • ExecuteException
      • ExecuteResponse
      • GlobPattern
      • HexDumpOption
      • HttpClientExtensions
      • HttpResponseMessageExtensions
      • IEnumerableExtensions
      • ILabeled
      • IOExtensions
      • IServiceContainer
      • IStaticDirectoryExtensions
      • LabelSelector
      • LabelSelectorOptions
      • LabelSelector<TItem>
      • NeonAssemblyExtensions
      • NeonExtendedHelper
      • NeonHelper
      • NetFramework
      • NewtonsoftExtensions
      • NotReadyException
      • ProcessExtensions
      • ProgramEntrypoint
      • ProgramEntrypointAsync
      • ProgramExitException
      • ProgramRunner
      • RandomExtensions
      • ReflectionExtensions
      • SemanticVersion
      • ServiceContainer
      • StaticZipOptions
      • StringBuilderExtensions
      • StringExtensions
      • Stub
      • Stub.Value
      • TaskExtensions
      • TimeSpanExtensions
      • ToolException
      • TriState
      • WeakEventController
      • WindowsEdition
      • WindowsFeatureStatus
      • YamlDotNetExtensions
    • Neon.Cryptography
      • AesCipher
      • CryptoExtensions
      • CryptoHelper
      • NeonVault
      • Wildcard
    • Neon.Csv
      • CsvReader
      • CsvTableReader
      • CsvTableWriter
      • CsvWriter
    • Neon.Data
      • DateTimeJsonConverter
      • DateTimeOffsetJsonConverter
      • IEnhancedJsonConverter
      • IGeneratedServiceClient
      • IPersistableType
      • IPersistableType<T>
      • IRoundtripData
      • IntegerEnumConverter<TEnum>
      • NotifyPropertyChanged
      • RoundtripDataFactory
      • RoundtripDataHelper
      • TimeSpanJsonConverter
      • VersionJsonConverter
    • Neon.Deployment
      • AwsCli
      • DeploymentException
      • DeploymentHelper
      • DownloadManifest
      • DownloadPart
      • DownloadProgressDelegate
      • DownloadProgressType
      • GitHub
      • GitHubActionsApi
      • GitHubPackage
      • GitHubPackageApi
      • GitHubPackageType
      • GitHubPackageVersion
      • GitHubPackageVisibility
      • GitHubReleaseApi
      • GitHubRepoPath
      • GitHubTagApi
      • IProfileClient
      • IProfileRequest
      • IProfileResponse
      • MaintainerProfile
      • NotifyClient
      • OnePassword
      • OnePasswordException
      • ProfileException
      • ProfileHandlerResult
      • ProfileRequest
      • ProfileResponse
      • ProfileServer
      • ProfileStatus
      • XenServer
    • Neon.Deployment.CodeSigning
      • AzureProfile
      • CodeSigner
      • UsbTokenProfile
    • Neon.Diagnostics
      • AssertException
      • ConfigExtensions
      • ConsoleJsonLogExporter
      • ConsoleJsonLogExporterOptions
      • ConsoleTextLogExporter
      • ConsoleTextLogExporterOptions
      • ExceptionInfo
      • FileLogExporter
      • FileLogExporterFormat
      • FileLogExporterOptions
      • LogAsTraceProcessor
      • LogAsTraceProcessorOptions
      • LogAttributeNames
      • LogAttributes
      • LogEvent
      • LogEventInterceptor
      • LoggerExtensions
      • NullLogger
      • TelemetryHub
      • TelemetrySpanEventNames
      • TelemetrySpanExtensions
    • Neon.Docker
      • DockerClient
      • DockerNetwork
      • DockerNetworkContainer
      • DockerNetworkIpam
      • DockerNode
      • DockerNodeManagerStatus
      • DockerResponse
      • DockerSettings
      • DockerVolume
      • NetworkCreateResponse
      • ServiceBindOptions
      • ServiceConfig
      • ServiceContainerSpec
      • ServiceCredentialSpec
      • ServiceDetails
      • ServiceDiscreteResourceSpec
      • ServiceDnsConfig
      • ServiceEndpoint
      • ServiceEndpointMode
      • ServiceEndpointPortConfig
      • ServiceEndpointSpec
      • ServiceFile
      • ServiceGenericResources
      • ServiceGlobalSchedulingMode
      • ServiceHealthCheck
      • ServiceIsolationMode
      • ServiceListResponse
      • ServiceLogDriver
      • ServiceMode
      • ServiceMount
      • ServiceMountBindPropagation
      • ServiceMountConsistency
      • ServiceMountType
      • ServiceNamedResourceSpec
      • ServiceNetwork
      • ServicePlacement
      • ServicePlacementPreferences
      • ServicePlacementSpreadSettings
      • ServicePlatform
      • ServicePortMode
      • ServicePortProtocol
      • ServicePrivileges
      • ServiceReplicatedSchedulingMode
      • ServiceResourceSettings
      • ServiceResources
      • ServiceRestartCondition
      • ServiceRestartPolicy
      • ServiceRollbackConfig
      • ServiceRollbackFailureAction
      • ServiceRollbackOrder
      • ServiceSELinuxContext
      • ServiceSchedulingMode
      • ServiceSecret
      • ServiceSpec
      • ServiceTaskTemplate
      • ServiceTmpfsOptions
      • ServiceUpdateConfig
      • ServiceUpdateFailureAction
      • ServiceUpdateOrder
      • ServiceUpdateState
      • ServiceUpdateStatus
      • ServiceVersion
      • ServiceVirtualIP
      • ServiceVolumeDriverConfig
      • ServiceVolumeOptions
      • VolumeListResponse
    • Neon.GitHub
      • GitExtensions
      • GitHubCredentials
      • GitHubRepo
      • LocalRepoApi
      • NoLocalRepositoryException
      • RemoteRepoApi
      • RemoteRepoBranchApi
      • RemoteRepoIssueApi
      • RemoteRepoIssueCommentApi
      • RemoteRepoPath
      • RemoteRepoReleaseApi
      • RemoteRepoTagApi
    • Neon.HyperV
      • HyperVClient
      • HyperVDriverType
      • HyperVException
      • NetAdapter
      • VirtualDrive
      • VirtualIPAddress
      • VirtualMachine
      • VirtualMachineNetworkAdapter
      • VirtualMachineState
      • VirtualNat
      • VirtualSwitch
      • VirtualSwitchType
    • Neon.IO
      • BlockStream
      • FixedLengthStream
      • IStaticDirectory
      • IStaticFile
      • LineEnding
      • LinuxPath
      • LinuxPermissions
      • PreprocessReader
      • RelayStream
      • StaticDirectoryBase
      • StaticFileBase
      • SubStream
      • TempFile
      • TempFolder
    • Neon.JsonConverters
      • JsonDateTimeConverter
      • JsonGenericConverter<T>
      • JsonNullableDateTimeConverter
    • Neon.ModelGen
      • ActionResult<T>
      • ApiVersion
      • ApiVersionAttribute
      • BodyStreamAttribute
      • ControllerValidationAttribute
      • DataModelAttribute
      • EnumMember
      • FromBodyAttribute
      • FromHeaderAttribute
      • FromQueryAttribute
      • FromRouteAttribute
      • GeneratedClientAttribute
      • GeneratedMethodAttribute
      • GeneratedParamAttribute
      • HashSourceAttribute
      • HttpAttribute
      • HttpDeleteAttribute
      • HttpGetAttribute
      • HttpHeadAttribute
      • HttpOptionsAttribute
      • HttpPatchAttribute
      • HttpPostAttribute
      • HttpPutAttribute
      • IActionResult
      • ModelGenerator
      • ModelGeneratorOutput
      • ModelGeneratorSettings
      • NoCodeGenAttribute
      • NoControllerValidationAttribute
      • PassAs
      • PersistableAttribute
      • PersistableKeyAttribute
      • RouteAttribute
      • ServiceModelAttribute
      • TargetAttribute
      • UxFrameworks
    • Neon.Net
      • HttpApiException
      • HttpException
      • JsonClient
      • JsonClientPayload
      • JsonResponse
      • Jwt
      • LocalHostSection
      • NetConst
      • NetHelper
      • NetworkCidr
      • NetworkConfiguration
      • NetworkException
      • NetworkPorts
      • Pinger
      • ReachableHost
      • ReachableHostMode
      • StreamDocument
    • Neon.Postgres
      • ConnectionExtensions
      • DatabaseStatus
      • PreparedCommand
      • ReaderAsyncEnumerator
      • ReaderEnumerator
      • ReaderExtensions
      • SchemaManager
      • SchemaManagerException
      • SchemaStatus
    • Neon.Retry
      • ExponentialRetryPolicy
      • IRetryPolicy
      • LinearRetryPolicy
      • NoRetryPolicy
      • RetryPolicy
      • RetryPolicyBase
      • RetryTransientArgs
      • TransientDetector
      • TransientException
    • Neon.Roslyn
      • DisplayFormat
      • DocumentationComment
      • DocumentationItem
      • MetadataLoadContext
      • RoslynAssembly
      • RoslynConstructorInfo
      • RoslynCustomAttributeData
      • RoslynExtensions
      • RoslynFieldInfo
      • RoslynMethodInfo
      • RoslynParameterInfo
      • RoslynPropertyInfo
      • RoslynType
      • SharedUtilities
    • Neon.Roslyn.Xunit
      • AdditionalSourceText
      • CompilationOptions
      • CompilationOptionsProvider
      • TestCompilation
      • TestCompilationAssertions
      • TestCompilationBuilder
      • TestCompilationBuilderExtensions
      • TestCompilationExtensions
    • Neon.SSH
      • CommandBundle
      • CommandFile
      • CommandResponse
      • HostFolders
      • IBashCommandFormatter
      • ILinuxSshProxy
      • LinuxDiskInfo
      • LinuxDiskPartition
      • LinuxSshProxy
      • LinuxSshProxy<TMetadata>
      • NamespaceDoc
      • RemoteCommandException
      • RunOptions
      • SshCredentials
      • SshExtensions
      • SshProxyException
    • Neon.Service
      • LogMetricsProcessor
      • MetricsMode
      • MetricsOptions
      • NeonService
      • NeonServiceOptions
      • NeonServiceStatus
      • OtelConfigExtensions
      • OtlpCollectorChecker
      • ProcessTerminator
      • ServiceApiContact
      • ServiceApiInfo
      • ServiceApiLicense
      • ServiceDependencies
      • ServiceDescription
      • ServiceEndpoint
      • ServiceEndpointProtocol
      • ServiceEndpoints
      • ServiceMap
    • Neon.SignalR
      • DependencyInjectionExtensions
      • DnsCache
      • GroupAction
      • GroupCommand
      • IDnsCache
      • Invocation
      • NatsHubLifetimeManager<THub>
      • ProxyConfig
      • ServiceCollectionExtensions
      • ServiceDiscovey
      • SignalrProxyMiddleware
      • SignalrProxyMiddlewareExtensions
      • TracerProviderBuilderExtensions
    • Neon.Tailwind
      • ClickOffEventHandler
      • ComponentEventArgs<TSender>
      • ComponentEventArgs<TSender, TEventArgs>
      • DisclosureState
      • EventHandlerComponentBase<TComponent>
      • HeadlessButton
      • HeadlessDialog
      • HeadlessDialogPanel
      • HeadlessDisclosure
      • HeadlessDisclosureButton
      • HeadlessDisclosurePanel
      • HeadlessListboxButton<TValue>
      • HeadlessListboxLabel<TValue>
      • HeadlessListboxOption<TValue>
      • HeadlessListboxOptions<TValue>
      • HeadlessListbox<TValue>
      • HeadlessMenu
      • HeadlessMenuButton
      • HeadlessMenuItem
      • HeadlessMenuItems
      • HeadlessSwitch
      • HeadlessSwitchGroup
      • HeadlessSwitchLabel
      • IPortalBinder
      • KeyDownEventHandler
      • KeyboardKey
      • ListboxFocus
      • ListboxState
      • MenuFocus
      • MenuState
      • Portal
      • PortalBinder
      • PortalContent
      • SearchAssistant
      • TailwindExtensions
      • Transition
      • TransitionGroup
      • TransitionState
    • Neon.Tasks
      • Async
      • AsyncAutoResetEvent
      • AsyncManualResetEvent
      • AsyncMutex
      • AsyncPeriodicTask
      • AsyncReaderWriterLock
      • AsyncReentrantMutex
      • AsyncTimer
      • IAsyncFuture
      • IAsyncFuture<T>
      • NonDisposableTask
      • NonDisposableTask<T>
      • SyncContext
      • SyncContextMode
    • Neon.Temporal
      • ActivityHelper
      • ActivityLogEnricher
      • TemporalEnricherTagNames
      • WorkflowLogEnricher
    • Neon.Time
      • GatedTimer
      • GoDuration
      • PolledTimer
      • RecurringTimer
      • RecurringTimerType
      • SysTime
      • TimeOfDay
    • Neon.WSL
      • Wsl2Proxy
    • Neon.Web
      • AesProtector
      • DataProtectionExtensions
      • NeonController
      • NeonControllerBase
      • RoundTripJsonInputFormatter
      • RoundTripJsonOutputFormatter
      • TracerProviderBuilderExtensions
      • WebHelper
    • Neon.WinTTY
      • ConsoleTTY
    • Neon.Windows
      • MEMORYSTATUSEX
      • PowerShellException
      • Win32
    • Neon.XenServer
      • IXenClient
      • XenClient
      • XenClient.MachineOperations
      • XenClient.StorageOperations
      • XenClient.TemplateOperations
      • XenException
      • XenHostInfo
      • XenObject
      • XenResponse
      • XenStorageRepository
      • XenTempIso
      • XenTemplate
      • XenVirtualDisk
      • XenVirtualMachine
      • XenVmPowerState
    • Neon.Xunit
      • AnsiblePlayResults
      • AnsiblePlayer
      • AnsibleTaskResult
      • AspNetFixture
      • BasicFixture
      • CodeFixture
      • CollectionComparer<T>
      • ComposedFixture
      • ContainerFixture
      • ContainerLimits
      • DockerComposeFixture
      • DockerFixture
      • DockerFixture.ConfigInfo
      • DockerFixture.ContainerInfo
      • DockerFixture.NetworkInfo
      • DockerFixture.SecretInfo
      • DockerFixture.ServiceInfo
      • DockerFixture.StackDefinition
      • DockerFixture.StackInfo
      • DockerFixture.StackService
      • EnvironmentFixture
      • HostsFixture
      • ITestFixture
      • IncompatibleServiceException
      • MaintainerFactAttribute
      • MaintainerTheoryAttribute
      • MockHttpServer
      • MockHttpServerExtensions
      • NatsFixture
      • NatsStreamingFixture
      • NeonServiceFixture<TService>
      • PlatformFactAttribute
      • RepeatAttribute
      • TargetPlatforms
      • TestArea
      • TestCollection
      • TestContext
      • TestFixture
      • TestFixtureStatus
      • TestHelper
      • TestHttpClient
      • TestOutputWriter
      • TestTrait
      • XunitExtensions
    • Neon.Xunit.YugaByte
      • YugaByteFixture
    • Neon.YugaByte
      • YugaByteHelper

    Class AesCipher

    Implements a convienent wrapper over AesManaged that handles the encryption and decryption of data using the AES algorthim using many security best practices.

    Inheritance
    object
    AesCipher
    Namespace: Neon.Cryptography
    Assembly: Neon.Cryptography.dll
    Syntax
    public sealed class AesCipher
    Remarks

    This class uses the BinaryWriter to generate the encrypted output and BinaryReader to read it.

    The data is formatted with an unencrypted header that specifies the initialization vector (IV), as well as the HMAC512 that will be used to validate the encrypted data. The encrypted data includes variable length psuedo random padding followed by the encrypted user data.

     Header (plaintext)
    +------------------+
    |    0x3BBAA035    |    32-bit magic number (for verification)
    +------------------+
    |     IV Size      |    16-bits
    +------------------+
    |                  |
    |     IV Bytes     |    IV Size bytes
    |                  |
    +------------------+
    |    HMAC Size     |    16-bits
    +------------------+
    |                  |
    |    HMAC Bytes    |    HMAC Size bytes
    |                  |
    +-------------------
    

    AES256 Encrypted: +------------------+ | Padding Size | 16-bits +------------------+ | | | Padding Bytes | Padding Size bytes | | +------------------+ | | | | | | | User Data | | | | | | | +------------------+

    note

    Note that this encodes multi-byte integers using little endian byte ordering via BinaryWriter and BinaryReader.

    This class automatically generates a new initialization vector for every encyption operation. This ensures that every encryption operation will generate different ciphertext even when the key and data haven't changed to enhance security.

    The class is designed to be easier to use than the .NET Core AesManaged base implementation.

    To encrypt data:

    1. Generate an encryption key via GenerateKey(int) and create an instance via AesCipher(string, int) passing the key, or just call AesCipher(int, int) to create with a generated key of the specified size.
    2. You can always obtain the key via the Key property.
    3. Call one of EncryptToBase64(byte[]), EncryptToBase64(byte[]), EncryptToBytes(string), or EncryptToBytes(byte[]) to perform the encryption with varying input and output formats.

    To decrypt data:

    1. Use AesCipher(string, int) to construct and instance using the key originally used to encrypt the data.
    2. Call one of DecryptBytesFrom(byte[]), DecryptBytesFrom(string), DecryptStringFrom(byte[]), or DecryptStringFrom(byte[]). to decrypt data.

    Constructors

    AesCipher(int, int)

    Constructs an AES cypher using a randomly generated encyption key.

    Declaration
    public AesCipher(int keySize = 256, int maxPaddingBytes = 64)
    Parameters
    Type Name Description
    int keySize

    Optionally specifies the key size (defaults to 256 bits).

    int maxPaddingBytes

    The maximum number of padding bytes. This must be less than or equal to 32767. This defaults to 64.

    Remarks

    Note that only these key sizes are currently supported: 128, 192, and 256 bits. Only 256 bits is currently considered to be secure.

    AesCipher(string, int)

    Constructs an AES cypher using a specific encryption key.

    Declaration
    public AesCipher(string key, int maxPaddingBytes = 64)
    Parameters
    Type Name Description
    string key

    The base-64 encoded key.

    int maxPaddingBytes

    The maximum number of padding bytes. This must be less than or equal to 32767. This defaults to 64.

    Fields

    Magic

    The 32-bit magic number that will be written in plaintext to the beginning of the encrypted output to be used to verify that encrypted buffers will generated by this class.

    Declaration
    public const int Magic = 1002086453
    Field Value
    Type Description
    int

    Properties

    IV

    Returns the encyption initialization vector encoded as base-64.

    Declaration
    public string IV { get; }
    Property Value
    Type Description
    string

    Key

    Returns the encyption key encoded as base-64.

    Declaration
    public string Key { get; }
    Property Value
    Type Description
    string

    Methods

    DecryptBytesFrom(byte[])

    Decrypts the encrypted base-64 text passed returning the result as a byte array.

    Declaration
    public byte[] DecryptBytesFrom(byte[] encryptedBytes)
    Parameters
    Type Name Description
    byte[] encryptedBytes

    The encrypted bytes.

    Returns
    Type Description
    byte[]

    The encrypted result as a string.

    DecryptBytesFrom(string)

    Decrypts the encrypted base-64 text passed returning the result as a byte array.

    Declaration
    public byte[] DecryptBytesFrom(string encryptedBase64)
    Parameters
    Type Name Description
    string encryptedBase64

    The encrypted base-64 text.

    Returns
    Type Description
    byte[]

    The encrypted result as a string.

    DecryptStream(Stream, Stream)

    Decrypts one stream to another.

    Declaration
    public void DecryptStream(Stream encrypted, Stream decrypted)
    Parameters
    Type Name Description
    Stream encrypted

    The encrypted input stream.

    Stream decrypted

    The decrypted output stream.

    DecryptStringFrom(byte[])

    Decrypts the encrypted bytes passed returning the result as a string.

    Declaration
    public string DecryptStringFrom(byte[] encryptedBytes)
    Parameters
    Type Name Description
    byte[] encryptedBytes

    The encrypted base-64 text.

    Returns
    Type Description
    string

    The encrypted result as a base-64 string.

    DecryptStringFrom(string)

    Decrypts the encrypted base-64 text passed returning the result as a string.

    Declaration
    public string DecryptStringFrom(string encryptedBase64)
    Parameters
    Type Name Description
    string encryptedBase64

    The encrypted base-64 text.

    Returns
    Type Description
    string

    The encrypted result as a base-64 string.

    Dispose()

    Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.

    Declaration
    public void Dispose()

    EncryptStream(Stream, Stream)

    Encrypts one stream to another.

    Declaration
    public void EncryptStream(Stream decrypted, Stream encrypted)
    Parameters
    Type Name Description
    Stream decrypted

    The decrypted input stream.

    Stream encrypted

    The encrypted output stream.

    EncryptToBase64(byte[])

    Encrypts the bytes passed returning the result encoded as base-64.

    Declaration
    public string EncryptToBase64(byte[] decryptedBytes)
    Parameters
    Type Name Description
    byte[] decryptedBytes

    The unencrypted text.

    Returns
    Type Description
    string

    The encrypted result as base-64.

    EncryptToBase64(string)

    Encrypts the text passed returning the result encoded as base-64.

    Declaration
    public string EncryptToBase64(string decryptedText)
    Parameters
    Type Name Description
    string decryptedText

    The unencrypted text.

    Returns
    Type Description
    string

    The encrypted result as base-64.

    EncryptToBytes(byte[])

    Encrypts the text passed returning the result encoded as a byte array.

    Declaration
    public byte[] EncryptToBytes(byte[] decryptedBytes)
    Parameters
    Type Name Description
    byte[] decryptedBytes

    The unencrypted bytes.

    Returns
    Type Description
    byte[]

    The encrypted result as bytes.

    EncryptToBytes(string)

    Encrypts the text passed returning the result encoded as a byte array.

    Declaration
    public byte[] EncryptToBytes(string decryptedText)
    Parameters
    Type Name Description
    string decryptedText

    The unencrypted text.

    Returns
    Type Description
    byte[]

    The encrypted result as bytes.

    GenerateKey(int)

    Generates a random encryption key with the specified size in bits.

    Declaration
    public static string GenerateKey(int keySize = 256)
    Parameters
    Type Name Description
    int keySize

    The key size in bits (default 256).

    Returns
    Type Description
    string

    The key encoded as base-64.

    Remarks

    Note that only these key sizes are currently supported: 128, 192, and 256 bits. Only 256 bits is currently considered to be secure.

    In this article
    Back to top © Copyright 2005-2023 by NEONFORGE LLC