/// <summary> /// Encrypts the string encoded plain text /// </summary> /// <param name="asymmetricEncryptionAlgorithm"></param> /// <param name="hashAlgorithm"></param> /// <param name="asymmetricEncryptionPadding"></param> /// <param name="asymmetricKeyParameter"></param> /// <param name="plainText"></param> /// <returns>Base64 encrypted encryptedInput text</returns> private string doEncrypt(AsymmetricEncryptionAlgorithm asymmetricEncryptionAlgorithm, HashAlgorithm hashAlgorithm, AsymmetricEncryptionPadding asymmetricEncryptionPadding, AsymmetricKeyParameter asymmetricKeyParameter, string plainText) { IAsymmetricBlockCipher asymEngine = getEngine(asymmetricEncryptionAlgorithm); IDigest hash = getDigest(hashAlgorithm); IAsymmetricBlockCipher cipher = getPadding(asymEngine, hash, asymmetricEncryptionPadding); BufferedAsymmetricBlockCipher bufferedCipher = new BufferedAsymmetricBlockCipher(cipher); if (this.error.existsError()) { return(""); } bufferedCipher.Init(true, asymmetricKeyParameter); EncodingUtil eu = new EncodingUtil(); byte[] inputBytes = eu.getBytes(plainText); if (eu.GetError().existsError()) { this.error = eu.GetError(); return(""); } bufferedCipher.ProcessBytes(inputBytes, 0, inputBytes.Length); byte[] outputBytes = bufferedCipher.DoFinal(); if (outputBytes == null || outputBytes.Length == 0) { this.error.setError("AE041", "Asymmetric encryption error"); return(""); } this.error.cleanError(); return(Base64.ToBase64String(outputBytes)); }
/// <summary> /// Decrypts the base64 encoded encrypted text /// </summary> /// <param name="asymmetricEncryptionAlgorithm">string AsymmetricEncryptionAlgorithm enum, algorithm name</param> /// <param name="hashAlgorithm">string HashAlgorithm enum, algorithm name</param> /// <param name="asymmetricEncryptionPadding">string AsymmetricEncryptionPadding enum, padding name</param> /// <param name="asymmetricKeyParameter">AsymmetricKeyParameter with loaded key for specified algorithm</param> /// <param name="encryptedInput">string Base64 to decrypt</param> /// <returns>string decypted encryptedInput text</returns> private string doDecrypt(AsymmetricEncryptionAlgorithm asymmetricEncryptionAlgorithm, HashAlgorithm hashAlgorithm, AsymmetricEncryptionPadding asymmetricEncryptionPadding, AsymmetricKeyParameter asymmetricKeyParameter, string encryptedInput) { IAsymmetricBlockCipher asymEngine = getEngine(asymmetricEncryptionAlgorithm); IDigest hash = getDigest(hashAlgorithm); IAsymmetricBlockCipher cipher = getPadding(asymEngine, hash, asymmetricEncryptionPadding); BufferedAsymmetricBlockCipher bufferedCipher = new BufferedAsymmetricBlockCipher(cipher); if (this.error.existsError()) { return(""); } bufferedCipher.Init(false, asymmetricKeyParameter); byte[] inputBytes = Base64.Decode(encryptedInput); bufferedCipher.ProcessBytes(inputBytes, 0, inputBytes.Length); byte[] outputBytes = bufferedCipher.DoFinal(); if (outputBytes == null || outputBytes.Length == 0) { this.error.setError("AE040", "Asymmetric decryption error"); return(""); } EncodingUtil eu = new EncodingUtil(); this.error = eu.GetError(); return(eu.getString(outputBytes)); }
public static byte[] Sign(byte[] hash, string hashAlgo, AsymmetricEncryptionAlgorithm cryptoAlgo, string privateKey) { switch (cryptoAlgo) { case AsymmetricEncryptionAlgorithm.RSA: using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider()) { RSA.FromXmlString(privateKey); return(RSA.SignHash(hash, CryptoConfig.MapNameToOID(hashAlgo))); } case AsymmetricEncryptionAlgorithm.DSA: using (DSACryptoServiceProvider DSA = new DSACryptoServiceProvider()) { DSA.FromXmlString(privateKey); DSASignatureFormatter DSAFormatter = new DSASignatureFormatter(DSA); DSAFormatter.SetHashAlgorithm(hashAlgo); return(DSAFormatter.CreateSignature(hash)); } default: throw new NotImplementedException("Feature not implemented for specified algorithm."); } }
public Signature(Stream s) { BinaryReader bR = new BinaryReader(s); if (Encoding.ASCII.GetString(bR.ReadBytes(2)) != "SN") //format { throw new CryptoException("Invalid signature format."); } switch (bR.ReadByte()) //version { case 1: _signedHash = bR.ReadBytes(bR.ReadUInt16()); _hashAlgo = Encoding.ASCII.GetString(bR.ReadBytes(bR.ReadByte())); _signAlgo = (AsymmetricEncryptionAlgorithm)bR.ReadByte(); if (s.ReadByte() == 1) { _signingCert = new Certificate(s); } break; default: throw new CryptoException("Signature format version not supported."); } }
public async Task <byte[]> UnwrapKeyAsync(byte[] encryptedKey, string algorithm = RsaOaep.AlgorithmName, CancellationToken token = default(CancellationToken)) { if (_csp == null) { throw new ObjectDisposedException(string.Format("RsaKey {0} is disposed", Kid)); } if (string.IsNullOrWhiteSpace(algorithm)) { algorithm = DefaultKeyWrapAlgorithm; } if (encryptedKey == null || encryptedKey.Length == 0) { throw new ArgumentNullException("wrappedKey"); } if (_csp.PublicOnly) { throw new NotSupportedException("UnwrapKey is not supported because no private key is available"); } AsymmetricEncryptionAlgorithm algo = AlgorithmResolver.Default[algorithm] as AsymmetricEncryptionAlgorithm; if (algo == null) { throw new NotSupportedException("algorithm is not supported"); } using (var encryptor = algo.CreateDecryptor(_csp)) { return(encryptor.TransformFinalBlock(encryptedKey, 0, encryptedKey.Length)); } }
public Signature(Stream data, string hashAlgo, Certificate signingCert, AsymmetricCryptoKey privateKey) { _signedHash = privateKey.Sign(data, hashAlgo); _hashAlgo = hashAlgo; _signAlgo = privateKey.Algorithm; _signingCert = signingCert; }
public static byte[] Sign(Stream data, string hashAlgo, AsymmetricEncryptionAlgorithm cryptoAlgo, string privateKey) { using (HashAlgorithm hash = HashAlgorithm.Create(hashAlgo)) { return(Sign(hash.ComputeHash(data), hashAlgo, cryptoAlgo, privateKey)); } }
public async Task <Tuple <byte[], string> > WrapKeyAsync(byte[] key, string algorithm = RsaOaep.AlgorithmName, CancellationToken token = default(CancellationToken)) { if (_csp == null) { throw new ObjectDisposedException(string.Format("RsaKey {0} is disposed", Kid)); } if (string.IsNullOrWhiteSpace(algorithm)) { algorithm = DefaultKeyWrapAlgorithm; } if (key == null || key.Length == 0) { throw new ArgumentNullException("key"); } AsymmetricEncryptionAlgorithm algo = AlgorithmResolver.Default[algorithm] as AsymmetricEncryptionAlgorithm; if (algo == null) { throw new NotSupportedException("algorithm is not supported"); } using (var encryptor = algo.CreateEncryptor(_csp)) { return(new Tuple <byte[], string>(encryptor.TransformFinalBlock(key, 0, key.Length), algorithm)); } }
public static bool Verify(Stream data, byte[] signedHash, string hashAlgo, AsymmetricEncryptionAlgorithm cryptoAlgo, string publicKey) { using (HashAlgorithm hash = HashAlgorithm.Create(hashAlgo)) { return(Verify(hash.ComputeHash(data), signedHash, hashAlgo, cryptoAlgo, publicKey)); } }
/// <summary> /// Mapping between AsymmetricEncryptionAlgorithm enum representation and string name /// </summary> /// <param name="asymmetricEncryptionAlgorithm">AsymmetricEncryptionAlgorithm enum, algorithm name</param> /// <param name="error">Error type for error management</param> /// <returns>string asymmetricEncryptionAlgorithm name</returns> public static string valueOf(AsymmetricEncryptionAlgorithm asymmetricEncryptionAlgorithm, Error error) { switch (asymmetricEncryptionAlgorithm) { case AsymmetricEncryptionAlgorithm.RSA: return("RSA"); default: error.setError("AE002", "Unrecognized AsymmetricEncryptionAlgorithm"); return(""); } }
/// <summary> /// Build asymmetric block cipher engine /// </summary> /// <param name="asymmetricEncryptionAlgorithm">AsymmetricEncryptionAlgorithm enum, algorithm name</param> /// <returns>IAsymmetricBlockCipher Engine for the specified algorithm</returns> private IAsymmetricBlockCipher getEngine(AsymmetricEncryptionAlgorithm asymmetricEncryptionAlgorithm) { switch (asymmetricEncryptionAlgorithm) { case AsymmetricEncryptionAlgorithm.RSA: return(new RsaEngine()); default: this.error.setError("AE042", "Unrecognized algorithm"); return(null); } }
public Task <byte[]> DecryptAsync(byte[] ciphertext, byte[] iv, byte[] authenticationData = null, byte[] authenticationTag = null, string algorithm = RsaOaep.AlgorithmName, CancellationToken token = default(CancellationToken)) { if (_csp == null) { throw new ObjectDisposedException(string.Format("RsaKey {0} is disposed", Kid)); } if (string.IsNullOrWhiteSpace(algorithm)) { algorithm = DefaultEncryptionAlgorithm; } if (ciphertext == null || ciphertext.Length == 0) { throw new ArgumentNullException("ciphertext"); } if (iv != null) { throw new ArgumentException("Initialization vector must be null", "iv"); } if (authenticationData != null) { throw new ArgumentException("Authentication data must be null", "authenticationData"); } // TODO: Not available via the RSA class //if ( _csp.PublicOnly ) // throw new NotSupportedException( "Decrypt is not supported because no private key is available" ); AsymmetricEncryptionAlgorithm algo = AlgorithmResolver.Default[algorithm] as AsymmetricEncryptionAlgorithm; if (algo == null) { throw new NotSupportedException("algorithm is not supported"); } using (var encryptor = algo.CreateDecryptor(_csp)) { try { var result = encryptor.TransformFinalBlock(ciphertext, 0, ciphertext.Length); return(Task.FromResult(result)); } catch (Exception ex) { return(TaskException.FromException <byte[]>(ex)); } } }
public static byte[] Decrypt(byte[] data, AsymmetricEncryptionAlgorithm cryptoAlgo, string privateKey) { switch (cryptoAlgo) { case AsymmetricEncryptionAlgorithm.RSA: RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); rsa.PersistKeyInCsp = false; rsa.FromXmlString(privateKey); return(rsa.Decrypt(data, false)); default: throw new NotImplementedException("Feature not implemented for specified algorithm."); } }
public Task <Tuple <byte[], byte[], string> > EncryptAsync(byte[] plaintext, byte[] iv = null, byte[] authenticationData = null, string algorithm = RsaOaep.AlgorithmName, CancellationToken token = default(CancellationToken)) { if (_csp == null) { throw new ObjectDisposedException(string.Format("RsaKey {0} is disposed", Kid)); } if (string.IsNullOrWhiteSpace(algorithm)) { algorithm = DefaultEncryptionAlgorithm; } if (plaintext == null || plaintext.Length == 0) { throw new ArgumentNullException("plaintext"); } if (iv != null) { throw new ArgumentException("Initialization vector must be null", "iv"); } if (authenticationData != null) { throw new ArgumentException("Authentication data must be null", "authenticationData"); } AsymmetricEncryptionAlgorithm algo = AlgorithmResolver.Default[algorithm] as AsymmetricEncryptionAlgorithm; if (algo == null) { throw new NotSupportedException("algorithm is not supported"); } using (var encryptor = algo.CreateEncryptor(_csp)) { try { var result = new Tuple <byte[], byte[], string>(encryptor.TransformFinalBlock(plaintext, 0, plaintext.Length), null, algorithm); return(Task.FromResult(result)); } catch (Exception ex) { return(TaskException.FromException <Tuple <byte[], byte[], string> >(ex)); } } }
// Warning 1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread. #pragma warning disable 1998 public async Task <byte[]> DecryptAsync(byte[] ciphertext, byte[] iv, byte[] authenticationData = null, byte[] authenticationTag = null, string algorithm = RsaOaep.AlgorithmName, CancellationToken token = default(CancellationToken)) { if (_certificate == null) { throw new ObjectDisposedException(string.Format("Certificate {0} is disposed", Kid)); } if (!_certificate.HasPrivateKey) { throw new NotSupportedException("Certificate does not have a private key"); } if (ciphertext == null || ciphertext.Length == 0) { throw new ArgumentNullException("ciphertext"); } if (iv != null) { throw new ArgumentException("Initialization vector must be null", "iv"); } if (authenticationData != null) { throw new ArgumentException("Authentication data must be null", "authenticationData"); } if (string.IsNullOrWhiteSpace(algorithm)) { algorithm = DefaultEncryptionAlgorithm; } AsymmetricEncryptionAlgorithm algo = AlgorithmResolver.Default[algorithm] as AsymmetricEncryptionAlgorithm; if (algo == null) { throw new NotSupportedException("algorithm is not supported"); } using (var encryptor = algo.CreateDecryptor(_certificate.PrivateKey)) { return(encryptor.TransformFinalBlock(ciphertext, 0, ciphertext.Length)); } }
public Certificate(Stream s) { BinaryReader bR = new BinaryReader(s); if (Encoding.ASCII.GetString(bR.ReadBytes(2)) != "CE") { throw new InvalidCertificateException("Invalid certificate format."); } _version = bR.ReadByte(); switch (_version) { case 1: _type = (CertificateType)bR.ReadByte(); _serialNumber = Encoding.ASCII.GetString(bR.ReadBytes(bR.ReadByte())); _issuedTo = new CertificateProfile(s); _capability = (CertificateCapability)bR.ReadByte(); _issuedOnUTC = bR.ReadUInt64(); _expiresOnUTC = bR.ReadUInt64(); _publicKeyEncryptionAlgorithm = (AsymmetricEncryptionAlgorithm)bR.ReadByte(); _publicKeyXML = Encoding.ASCII.GetString(bR.ReadBytes(bR.ReadUInt16())); byte rUriLen = bR.ReadByte(); if (rUriLen > 0) { _revocationUri = new Uri(Encoding.UTF8.GetString(bR.ReadBytes(rUriLen))); } if (s.ReadByte() == 1) { _issuerSignature = new Signature(s); } break; default: throw new InvalidCertificateException("Certificate format version not supported."); } }
public AsymmetricCryptoKey(Stream s) { BinaryReader bR = new BinaryReader(s); if (Encoding.ASCII.GetString(bR.ReadBytes(2)) != "AK") { throw new CryptoException("Invalid AsymmetricCryptoKey format."); } switch (bR.ReadByte()) //version { case 1: AsymmetricEncryptionAlgorithm cryptoAlgo = (AsymmetricEncryptionAlgorithm)bR.ReadByte(); string privateKey = Encoding.ASCII.GetString(bR.ReadBytes(bR.ReadUInt16())); switch (cryptoAlgo) { case AsymmetricEncryptionAlgorithm.RSA: RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); rsa.PersistKeyInCsp = false; rsa.FromXmlString(privateKey); _asymAlgo = rsa; break; case AsymmetricEncryptionAlgorithm.DSA: DSACryptoServiceProvider dsa = new DSACryptoServiceProvider(); dsa.PersistKeyInCsp = false; dsa.FromXmlString(privateKey); _asymAlgo = dsa; break; default: throw new NotImplementedException("Feature not implemented for specified algorithm."); } _cryptoAlgo = cryptoAlgo; break; default: throw new CryptoException("AsymmetricCryptoKey format version not supported."); } }
public Certificate(CertificateType type, string serialNumber, CertificateProfile issuedTo, CertificateCapability capability, DateTime issuedOnUTC, DateTime expiresOnUTC, AsymmetricEncryptionAlgorithm publicKeyEncryptionAlgorithm, string publicKeyXML) { if (issuedOnUTC > expiresOnUTC) { throw new CryptoException("Invalid issue or expiry date. Issue date is greater than expiry date."); } _version = 1; _type = type; _serialNumber = serialNumber; _issuedTo = issuedTo; _capability = capability; _issuedOnUTC = Convert.ToUInt64((issuedOnUTC - _epoch).TotalSeconds); _expiresOnUTC = Convert.ToUInt64((expiresOnUTC - _epoch).TotalSeconds); _publicKeyEncryptionAlgorithm = publicKeyEncryptionAlgorithm; _publicKeyXML = publicKeyXML; }
public AsymmetricCryptoKey(AsymmetricEncryptionAlgorithm cryptoAlgo, int keySize) { switch (cryptoAlgo) { case AsymmetricEncryptionAlgorithm.RSA: RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(keySize); rsa.PersistKeyInCsp = false; _asymAlgo = rsa; break; case AsymmetricEncryptionAlgorithm.DSA: DSACryptoServiceProvider dsa = new DSACryptoServiceProvider(keySize); dsa.PersistKeyInCsp = false; _asymAlgo = dsa; break; default: throw new NotImplementedException("Feature not implemented for specified algorithm."); } _cryptoAlgo = cryptoAlgo; }
/********EXTERNAL OBJECT PUBLIC METHODS - END ********/ /// <summary> /// Encrypts the string encoded plain text /// </summary> /// <param name="asymmetricEncryptionAlgorithm">string AsymmetricEncryptionAlgorithm enum, algorithm name</param> /// <param name="hashAlgorithm">string HashAlgorithm enum, algorithm name</param> /// <param name="asymmetricEncryptionPadding">string AsymmetricEncryptionPadding enum, padding name</param> /// <param name="keyPath">string path to key/certificate</param> /// <param name="isPrivate">boolean true if key is private, false if it is public</param> /// <param name="alias">string keystore/certificate pkcs12 format alias</param> /// <param name="password">Srting keysore/certificate pkcs12 format alias</param> /// <param name="plainText">string to encrypt</param> /// <returns>string Base64 encrypted plainText text</returns> private string DoEncryptInternal(string hashAlgorithm, string asymmetricEncryptionPadding, Key key, bool isPrivate, string plainText) { this.error.cleanError(); HashAlgorithm hash = HashAlgorithmUtils.getHashAlgorithm(hashAlgorithm, this.error); AsymmetricEncryptionPadding padding = AsymmetricEncryptionPaddingUtils.getAsymmetricEncryptionPadding(asymmetricEncryptionPadding, this.error); if (this.error.existsError()) { return(""); } string asymmetricEncryptionAlgorithm = ""; AsymmetricKeyParameter asymKey = null; if (isPrivate) { PrivateKeyManager keyMan = (PrivateKeyManager)key; if (!keyMan.HasPrivateKey || keyMan.HasError()) { this.error = keyMan.GetError(); return(""); } asymmetricEncryptionAlgorithm = keyMan.getPrivateKeyAlgorithm(); asymKey = keyMan.getPrivateKeyParameterForEncryption(); if (keyMan.HasError()) { this.error = keyMan.GetError(); return(""); } } else { CertificateX509 cert = (CertificateX509)key; if (!cert.Inicialized || cert.HasError()) { this.error = cert.GetError(); return(""); } asymmetricEncryptionAlgorithm = cert.getPublicKeyAlgorithm(); asymKey = cert.getPublicKeyParameterForEncryption(); if (cert.HasError()) { this.error = cert.GetError(); return(""); } } AsymmetricEncryptionAlgorithm algorithm = AsymmetricEncryptionAlgorithmUtils .getAsymmetricEncryptionAlgorithm(asymmetricEncryptionAlgorithm, this.error); try { return(doEncrypt(algorithm, hash, padding, asymKey, plainText)); } catch (InvalidCipherTextException) { this.error.setError("AE036", "Algoritmo inválido" + algorithm); return(""); } }