/// <summary> /// Get the hashcode from the value. /// </summary> /// <param name="value">The value to generate the hash code for.</param> /// <param name="hashcodeType">The hash name.</param> /// <param name="keySizePBKDF2">The PBKDF2 key size to generate.</param> /// <returns>The generated hash code.</returns> public static byte[] GetHashcodeRaw(string value, Nequeo.Cryptography.HashcodeType hashcodeType, int keySizePBKDF2 = 100) { // Generate the hash code HashAlgorithm alg = null; // Select the hash code type. switch (hashcodeType) { case HashcodeType.SHA3: // SHA3 hashcode. alg = new Sha3.SHA3Managed(); break; case HashcodeType.PBKDF2: // PBKDF2 hashcode. byte[] hashValueEx = RandomDerivedKey.GenerateEx(value, keySizePBKDF2, 5000); return(hashValueEx); default: alg = HashAlgorithm.Create(hashcodeType.ToString()); break; } byte[] byteValue = Encoding.ASCII.GetBytes(value); byte[] hashValue = alg.ComputeHash(byteValue); return(hashValue); }
/// <summary> /// Get the hash algorithm. /// </summary> /// <param name="hashAlgorithm">The hash algorithm.</param> /// <returns>The pgp hash algorithm.</returns> internal static Key.Bcpg.HashAlgorithmTag GetHashAlgorithm(Nequeo.Cryptography.HashcodeType hashAlgorithm = HashcodeType.SHA512) { Key.Bcpg.HashAlgorithmTag tag = Key.Bcpg.HashAlgorithmTag.Sha512; // Select the algorithm. switch (hashAlgorithm) { case HashcodeType.MD5: tag = Key.Bcpg.HashAlgorithmTag.MD5; break; case HashcodeType.SHA1: tag = Key.Bcpg.HashAlgorithmTag.Sha1; break; case HashcodeType.SHA256: tag = Key.Bcpg.HashAlgorithmTag.Sha256; break; case HashcodeType.SHA384: tag = Key.Bcpg.HashAlgorithmTag.Sha384; break; case HashcodeType.SHA512: tag = Key.Bcpg.HashAlgorithmTag.Sha512; break; } // Return the algorithm; return(tag); }
/// <summary> /// Constructor with host attributes /// </summary> /// <param name="type">The type attribute.</param> /// <param name="passwordFormat">The password format attribute.</param> /// <param name="authorisationCode">The authorisation code attribute.</param> /// <param name="hashcodeType">The hashcode type attribute.</param> public EncoderElement(String type, Nequeo.Cryptography.PasswordFormat passwordFormat, String authorisationCode, Nequeo.Cryptography.HashcodeType hashcodeType) { TypeValue = type; PasswordFormat = passwordFormat; AuthorisationCode = authorisationCode; HashcodeType = hashcodeType; }
/// <summary> /// Decode the password. /// </summary> /// <param name="password">The password to decode (must include at the start of the password the encoded salt).</param> /// <param name="passwordFormat">The password format type to decode with.</param> /// <param name="originalPassword">The original password (used when format is Hashed); can be null.</param> /// <param name="hashcodeType">The hash code type (used when format is Hashed).</param> /// <returns>The decoded password.</returns> public string Decode(SecureString password, Nequeo.Cryptography.PasswordFormat passwordFormat, SecureString originalPassword, Nequeo.Cryptography.HashcodeType hashcodeType = Cryptography.HashcodeType.SHA512) { return(Decode( new Nequeo.Security.SecureText().GetText(password), passwordFormat, (originalPassword != null ? new Nequeo.Security.SecureText().GetText(originalPassword) : ""), hashcodeType)); }
/// <summary> /// Get the hashcode from the value. /// </summary> /// <param name="value">The value to generate the hash code for.</param> /// <param name="hashcodeType">The hash name.</param> /// <returns>The generated hash code.</returns> public static byte[] GetHashcodeRaw(string value, Nequeo.Cryptography.HashcodeType hashcodeType) { // Generate the hash code HashAlgorithm alg = HashAlgorithm.Create(hashcodeType.ToString()); byte[] byteValue = Encoding.ASCII.GetBytes(value); byte[] hashValue = alg.ComputeHash(byteValue); return(hashValue); }
/// <summary> /// Decode the password. /// </summary> /// <param name="password">The password to decode.</param> /// <param name="passwordFormat">The password format type to decode with.</param> /// <param name="originalPassword">The original password (used when format is Hashed).</param> /// <param name="hashcodeType">The the hash code type (used when format is Hashed).</param> /// <returns>The decoded password (if format is Hashed and the hash has been verified to be /// the same then the original password is returned; else the password is returned).</returns> public string Decode(string password, Cryptography.PasswordFormat passwordFormat, string originalPassword = "", Nequeo.Cryptography.HashcodeType hashcodeType = Cryptography.HashcodeType.SHA512) { // If authorised. if (IsAuthorised()) { // Select the format. switch (passwordFormat) { case Cryptography.PasswordFormat.Encrypted: // Convert the HEX string to bytes. byte[] bytes = Nequeo.Conversion.Context.HexStringToByteArray(password); // Decrypt the data byte[] decryptedData = new Nequeo.Cryptography.AdvancedAES().DecryptFromMemory(bytes, KeyContainer._passwordKey); return(Encoding.Default.GetString(decryptedData).Replace("\0", "")); case Cryptography.PasswordFormat.Hashed: // Get the salt. string saltBase = password.Substring(0, KeyContainer._saltLength * 2); byte[] saltBaseBytes = Nequeo.Conversion.Context.HexStringToByteArray(saltBase); string salt = Encoding.Default.GetString(saltBaseBytes); // Return the salt for the hash. string hash = Nequeo.Cryptography.Hashcode.GetHashcode(originalPassword + _authorisationKey + salt, hashcodeType); // Get the hex salt. byte[] saltBase64 = Encoding.Default.GetBytes(salt); string hashed = Nequeo.Conversion.Context.ByteArrayToHexString(saltBase64) + hash; // If the hash is the password. if (hashed.Equals(password)) { return(originalPassword); } else { return(password); } case Cryptography.PasswordFormat.Clear: default: return(password); } } else { if (passwordFormat == Cryptography.PasswordFormat.Clear) { return(password); } else { throw new Exception("Authorisation Failed."); } } }
/// <summary> /// Computes the hash value of the specified input stream using the specified /// hash algorithm, and signs the resulting hash value. /// </summary> /// <param name="data">The data to sign.</param> /// <param name="cert">x509 certificate.</param> /// <param name="hashAlgorithm">The hash algorithm to use to create the hash value.</param> /// <returns>The signature for the specified data.</returns> public byte[] SignData(Stream data, X509Certificate2 cert, Nequeo.Cryptography.HashcodeType hashAlgorithm = HashcodeType.SHA512) { // Create an ECDSA. using (ECDsa privateKey = cert.GetECDsaPrivateKey()) { // Sign the data. byte[] signature = privateKey.SignData(data, GetAlgorithmName(hashAlgorithm)); return(signature); } }
/// <summary> /// Computes the hash value of the specified input stream using the specified /// hash algorithm, and signs the resulting hash value. /// </summary> /// <param name="data">The data to sign.</param> /// <param name="key">Cryptography Next Generation (CNG) objects key.</param> /// <param name="hashAlgorithm">The hash algorithm to use to create the hash value.</param> /// <returns>The signature for the specified data.</returns> public byte[] SignData(Stream data, CngKey key, Nequeo.Cryptography.HashcodeType hashAlgorithm = HashcodeType.SHA512) { // Create an ECDSA. using (ECDsaCng dsa = new ECDsaCng(key)) { // Sign the data. dsa.HashAlgorithm = GetAlgorithm(hashAlgorithm); byte[] signature = dsa.SignData(data); return(signature); } }
/// <summary> /// Encrypt the file. /// </summary> /// <param name="encrypted">The encrypted data stream.</param> /// <param name="filename">The path and file name to encrypt.</param> /// <param name="password">The password used for encryption.</param> /// <param name="protectedKeys">Should the data be protected.</param> /// <param name="integrityCheck">Should the cipher stream have an integrity packet associated with it.</param> /// <param name="hashAlgorithm">The preferred hash algorithm to use to create the hash value.</param> /// <param name="symmetricKeyAlgorithm">The symmetric key algorithm used for cryptography.</param> public void Encrypt(System.IO.Stream encrypted, string filename, string password, bool protectedKeys = false, bool integrityCheck = false, Nequeo.Cryptography.HashcodeType hashAlgorithm = HashcodeType.SHA512, Nequeo.Cryptography.SymmetricKeyAlgorithmType symmetricKeyAlgorithm = Nequeo.Cryptography.SymmetricKeyAlgorithmType.Aes256) { // If file is protected. if (protectedKeys) { encrypted = new Key.Bcpg.ArmoredOutputStream(encrypted); } System.IO.Stream encOutput = null; try { // Create the encypted data generator. Key.Bcpg.OpenPgp.PgpEncryptedDataGenerator encryptedDataGenerator = new Key.Bcpg.OpenPgp.PgpEncryptedDataGenerator( GetSymmetricKeyAlgorithm(symmetricKeyAlgorithm), integrityCheck, new Key.Security.SecureRandom()); encryptedDataGenerator.AddMethod(password.ToArray(), GetHashAlgorithm(hashAlgorithm)); // The input data buffer. Key.Bcpg.OpenPgp.PgpCompressedDataGenerator compressedData = new Key.Bcpg.OpenPgp.PgpCompressedDataGenerator(Key.Bcpg.CompressionAlgorithmTag.Uncompressed); // Write the encrypted data. encOutput = encryptedDataGenerator.Open(encrypted, new byte[1 << 16]); Key.Bcpg.OpenPgp.PgpUtilities.WriteFileToLiteralData( compressedData.Open(encOutput), Key.Bcpg.OpenPgp.PgpLiteralData.Binary, new FileInfo(filename), new byte[1 << 16]); // Close the streams. compressedData.Close(); encOutput.Close(); // If file is protected. if (protectedKeys) { encrypted.Close(); } } catch (Exception) { throw; } finally { if (encOutput != null) { encOutput.Close(); } } }
/// <summary> /// Verifies that a digital signature is valid by determining the hash value /// in the signature using the provided public key and comparing it to the hash /// value of the provided data. /// </summary> /// <param name="data">The data that was signed.</param> /// <param name="signature">The signature data to be verified.</param> /// <param name="publicKey">ECDsa public key.</param> /// <param name="hashAlgorithm">The hash algorithm to use to create the hash value.</param> /// <returns>True if the signature is valid; otherwise, false.</returns> public bool VerifyData(Stream data, byte[] signature, ECDsa publicKey, Nequeo.Cryptography.HashcodeType hashAlgorithm = HashcodeType.SHA512) { // Verify the data. if (publicKey.VerifyData(data, signature, GetAlgorithmName(hashAlgorithm))) { return(true); } else { return(false); } }
/// <summary> /// Verifies that a digital signature is valid by determining the hash value /// in the signature using the provided public key and comparing it to the hash /// value of the provided data. /// </summary> /// <param name="data">The data that was signed.</param> /// <param name="signature">The signature data to be verified.</param> /// <param name="cert">x509 certificate.</param> /// <param name="hashAlgorithm">The hash algorithm to use to create the hash value.</param> /// <returns>True if the signature is valid; otherwise, false.</returns> public bool VerifyData(Stream data, byte[] signature, X509Certificate2 cert, Nequeo.Cryptography.HashcodeType hashAlgorithm = HashcodeType.SHA512) { // Create an ECDSA. using (ECDsa publicKey = cert.GetECDsaPublicKey()) { // Verify the data. if (publicKey.VerifyData(data, signature, GetAlgorithmName(hashAlgorithm))) { return(true); } else { return(false); } } }
/// <summary> /// Encode the password. /// </summary> /// <param name="password">The password to encode.</param> /// <param name="passwordFormat">The password format type to encode with.</param> /// <param name="hashcodeType">The hash code type (used when format is Hashed).</param> /// <returns>The encode password (includes at the start of the password the encoded salt).</returns> public string Encode(string password, Cryptography.PasswordFormat passwordFormat, Nequeo.Cryptography.HashcodeType hashcodeType = Cryptography.HashcodeType.SHA512) { // If authorised. if (IsAuthorised()) { // Select the format. switch (passwordFormat) { case Cryptography.PasswordFormat.Encrypted: // Encrypt the data. byte[] data = Encoding.Default.GetBytes(password); byte[] encryptedData = new Nequeo.Cryptography.AdvancedAES().EncryptToMemory(data, KeyContainer._passwordKey); return(Nequeo.Conversion.Context.ByteArrayToHexString(encryptedData)); case Cryptography.PasswordFormat.Hashed: // Encode the password to a hash. string salt = Nequeo.Cryptography.Hashcode.GenerateSalt(KeyContainer._saltLength, KeyContainer._saltLength); byte[] saltBase = Encoding.Default.GetBytes(salt); // Password - based Key Derivation Functions. Rfc2898DeriveBytes rfcDerive = new Rfc2898DeriveBytes(password, saltBase, KeyContainer._numberOfIterations); string derivedPassword = Encoding.Default.GetString(rfcDerive.GetBytes(KeyContainer._saltLength * 2)); // Get the hex salt. string hash = Nequeo.Cryptography.Hashcode.GetHashcode(derivedPassword + _authorisationKey + salt, hashcodeType); _encodedSalt = Nequeo.Conversion.Context.ByteArrayToHexString(saltBase); return(_encodedSalt + hash); case Cryptography.PasswordFormat.Clear: default: return(password); } } else { if (passwordFormat == Cryptography.PasswordFormat.Clear) { return(password); } else { throw new Exception("Authorisation Failed."); } } }
/// <summary> /// Encrypt the stream. /// </summary> /// <param name="encrypted">The encrypted data stream.</param> /// <param name="input">The data to encrypt.</param> /// <param name="password">The password used for encryption.</param> /// <param name="protectedKeys">Should the data be protected.</param> /// <param name="integrityCheck">Should the cipher stream have an integrity packet associated with it.</param> /// <param name="hashAlgorithm">The preferred hash algorithm to use to create the hash value.</param> /// <param name="symmetricKeyAlgorithm">The symmetric key algorithm used for cryptography.</param> public void Encrypt(System.IO.Stream encrypted, System.IO.Stream input, string password, bool protectedKeys = false, bool integrityCheck = false, Nequeo.Cryptography.HashcodeType hashAlgorithm = HashcodeType.SHA512, Nequeo.Cryptography.SymmetricKeyAlgorithmType symmetricKeyAlgorithm = Nequeo.Cryptography.SymmetricKeyAlgorithmType.Aes256) { // If file is protected. if (protectedKeys) { encrypted = new Key.Bcpg.ArmoredOutputStream(encrypted); } System.IO.Stream encOutput = null; try { // Create the encypted data generator. Key.Bcpg.OpenPgp.PgpEncryptedDataGenerator encryptedDataGenerator = new Key.Bcpg.OpenPgp.PgpEncryptedDataGenerator( GetSymmetricKeyAlgorithm(symmetricKeyAlgorithm), integrityCheck, new Key.Security.SecureRandom()); encryptedDataGenerator.AddMethod(password.ToArray(), GetHashAlgorithm(hashAlgorithm)); // The input data buffer. byte[] buffer = Compress(input, Key.Bcpg.CompressionAlgorithmTag.Uncompressed); // Write the encrypted data. encOutput = encryptedDataGenerator.Open(encrypted, (long)buffer.Length); encOutput.Write(buffer, 0, buffer.Length); encOutput.Close(); // If file is protected. if (protectedKeys) { encrypted.Close(); } } catch (Exception) { throw; } finally { if (encOutput != null) { encOutput.Close(); } } }
/// <summary> /// Get the CNG Algorithm. /// </summary> /// <param name="hashAlgorithm">The hash algorithm to use to create the hash value.</param> /// <returns>CNG Algorithm.</returns> private HashAlgorithmName GetAlgorithmName(Nequeo.Cryptography.HashcodeType hashAlgorithm = HashcodeType.SHA512) { switch (hashAlgorithm) { case HashcodeType.MD5: return(HashAlgorithmName.MD5); case HashcodeType.SHA1: return(HashAlgorithmName.SHA1); case HashcodeType.SHA256: return(HashAlgorithmName.SHA256); case HashcodeType.SHA384: return(HashAlgorithmName.SHA384); default: case HashcodeType.SHA512: return(HashAlgorithmName.SHA512); } }
/// <summary> /// Get the CNG Algorithm. /// </summary> /// <param name="hashAlgorithm">The hash algorithm to use to create the hash value.</param> /// <returns>CNG Algorithm.</returns> private CngAlgorithm GetAlgorithm(Nequeo.Cryptography.HashcodeType hashAlgorithm = HashcodeType.SHA512) { switch (hashAlgorithm) { case HashcodeType.MD5: return(CngAlgorithm.MD5); case HashcodeType.SHA1: return(CngAlgorithm.Sha1); case HashcodeType.SHA256: return(CngAlgorithm.Sha256); case HashcodeType.SHA384: return(CngAlgorithm.Sha384); default: case HashcodeType.SHA512: return(CngAlgorithm.Sha512); } }
/// <summary> /// Get the hashcode from the value. /// </summary> /// <param name="value">The value to generate the hash code for.</param> /// <param name="hashcodeType">The hash name.</param> /// <returns>The generated hash code.</returns> public static string GetHashcode(string value, Nequeo.Cryptography.HashcodeType hashcodeType) { int i = 0; // Generate the hash code HashAlgorithm alg = HashAlgorithm.Create(hashcodeType.ToString()); byte[] byteValue = Encoding.ASCII.GetBytes(value); byte[] hashValue = alg.ComputeHash(byteValue); // Get the string value of hashcode. string[] octetArrayByte = new string[hashValue.Count()]; foreach (Byte item in hashValue) { octetArrayByte[i++] = item.ToString("X2"); } // Create the octet string of bytes. string octetValue = String.Join("", octetArrayByte); return(octetValue); }
/// <summary> /// Get the hashcode from the file. /// </summary> /// <param name="filename">The path and file name to generate the hash code for.</param> /// <param name="hashcodeType">The hash name.</param> /// <returns>The generated hash code.</returns> public static byte[] GetHashcodeFileRaw(string filename, Nequeo.Cryptography.HashcodeType hashcodeType) { FileStream file = null; byte[] hashValue = null; try { // Open the file to generate the hash code for. using (file = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { // Select the hash code type. switch (hashcodeType) { case HashcodeType.MD5: // MD5 hashcode. MD5 md5 = new MD5CryptoServiceProvider(); hashValue = md5.ComputeHash(file); break; case HashcodeType.SHA1: // SHA1 hashcode. SHA1 sha1 = new SHA1CryptoServiceProvider(); hashValue = sha1.ComputeHash(file); break; case HashcodeType.SHA256: // SHA256 hashcode. SHA256 sha256 = new SHA256CryptoServiceProvider(); hashValue = sha256.ComputeHash(file); break; case HashcodeType.SHA384: // SHA384 hashcode. SHA384 sha384 = new SHA384CryptoServiceProvider(); hashValue = sha384.ComputeHash(file); break; case HashcodeType.SHA512: // SHA512 hashcode. SHA512 sha512 = new SHA512CryptoServiceProvider(); hashValue = sha512.ComputeHash(file); break; } // Close the file. file.Close(); // Return the hash code. return(hashValue); } } catch (Exception) { throw; } finally { // Clean-up if (file != null) { file.Close(); } } }
/// <summary> /// Computes the hash value of the specified input stream using the specified /// hash algorithm, and signs the resulting hash value. /// </summary> /// <param name="data">The data to sign.</param> /// <param name="privateKey">ECDsa private key.</param> /// <param name="hashAlgorithm">The hash algorithm to use to create the hash value.</param> /// <returns>The signature for the specified data.</returns> public byte[] SignData(Stream data, ECDsa privateKey, Nequeo.Cryptography.HashcodeType hashAlgorithm = HashcodeType.SHA512) { return(privateKey.SignData(data, GetAlgorithmName(hashAlgorithm))); }
/// <summary> /// Computes the hash value of the specified input stream using the specified /// hash algorithm, and signs the resulting hash value. /// </summary> /// <param name="inputStream">The input data for which to compute the hash.</param> /// <param name="rsaProvider">the RSA crypto service provider.</param> /// <param name="hashAlgorithm">The hash algorithm to use to create the hash value.</param> /// <returns>The System.Security.Cryptography.RSA signature for the specified data.</returns> public static byte[] SignData(Stream inputStream, RSACryptoServiceProvider rsaProvider, Nequeo.Cryptography.HashcodeType hashAlgorithm = HashcodeType.SHA512) { byte[] signValue = null; // Select the hash code type. switch (hashAlgorithm) { case HashcodeType.MD5: // MD5 hashcode. MD5 md5 = new MD5CryptoServiceProvider(); signValue = rsaProvider.SignData(inputStream, md5); break; case HashcodeType.SHA1: // SHA1 hashcode. SHA1 sha1 = new SHA1CryptoServiceProvider(); signValue = rsaProvider.SignData(inputStream, sha1); break; case HashcodeType.SHA256: // SHA256 hashcode. SHA256 sha256 = new SHA256CryptoServiceProvider(); signValue = rsaProvider.SignData(inputStream, sha256); break; case HashcodeType.SHA384: // SHA384 hashcode. SHA384 sha384 = new SHA384CryptoServiceProvider(); signValue = rsaProvider.SignData(inputStream, sha384); break; case HashcodeType.SHA512: // SHA512 hashcode. SHA512 sha512 = new SHA512CryptoServiceProvider(); signValue = rsaProvider.SignData(inputStream, sha512); break; } // Return the signed value. return(signValue); }
/// <summary> /// Verifies that a digital signature is valid by determining the hash value /// in the signature using the provided public key and comparing it to the hash /// value of the provided data. /// </summary> /// <param name="buffer">The data that was signed.</param> /// <param name="signature">The signature data to be verified.</param> /// <param name="rsaProvider">the RSA crypto service provider.</param> /// <param name="hashAlgorithm">The hash algorithm to use to create the hash value.</param> /// <returns>True if the signature is valid; otherwise, false.</returns> public static bool VerifyData(byte[] buffer, byte[] signature, RSACryptoServiceProvider rsaProvider, Nequeo.Cryptography.HashcodeType hashAlgorithm = HashcodeType.SHA512) { bool dataVerified = false; // Select the hash code type. switch (hashAlgorithm) { case HashcodeType.MD5: // MD5 hashcode. MD5 md5 = new MD5CryptoServiceProvider(); dataVerified = rsaProvider.VerifyData(buffer, md5, signature); break; case HashcodeType.SHA1: // SHA1 hashcode. SHA1 sha1 = new SHA1CryptoServiceProvider(); dataVerified = rsaProvider.VerifyData(buffer, sha1, signature); break; case HashcodeType.SHA256: // SHA256 hashcode. SHA256 sha256 = new SHA256CryptoServiceProvider(); dataVerified = rsaProvider.VerifyData(buffer, sha256, signature); break; case HashcodeType.SHA384: // SHA384 hashcode. SHA384 sha384 = new SHA384CryptoServiceProvider(); dataVerified = rsaProvider.VerifyData(buffer, sha384, signature); break; case HashcodeType.SHA512: // SHA512 hashcode. SHA512 sha512 = new SHA512CryptoServiceProvider(); dataVerified = rsaProvider.VerifyData(buffer, sha512, signature); break; } // Return the result. return(dataVerified); }
/// <summary> /// Get the hashcode from the file. /// </summary> /// <param name="filename">The path and file name to generate the hash code for.</param> /// <param name="hashcodeType">The hash name.</param> /// <returns>The generated hash code.</returns> public static string GetHashcodeFile(string filename, Nequeo.Cryptography.HashcodeType hashcodeType) { FileStream file = null; byte[] hashValue = null; StringBuilder sb = null; try { // Open the file to generate the hash code for. using (file = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { // Select the hash code type. switch (hashcodeType) { case HashcodeType.MD5: // MD5 hashcode. MD5 md5 = new MD5CryptoServiceProvider(); hashValue = md5.ComputeHash(file); break; case HashcodeType.SHA1: // SHA1 hashcode. SHA1 sha1 = new SHA1CryptoServiceProvider(); hashValue = sha1.ComputeHash(file); break; case HashcodeType.SHA256: // SHA256 hashcode. SHA256 sha256 = new SHA256CryptoServiceProvider(); hashValue = sha256.ComputeHash(file); break; case HashcodeType.SHA384: // SHA384 hashcode. SHA384 sha384 = new SHA384CryptoServiceProvider(); hashValue = sha384.ComputeHash(file); break; case HashcodeType.SHA512: // SHA512 hashcode. SHA512 sha512 = new SHA512CryptoServiceProvider(); hashValue = sha512.ComputeHash(file); break; case HashcodeType.SHA3: // SHA3 hashcode. Sha3.SHA3Managed sha3 = new Sha3.SHA3Managed(); hashValue = sha3.ComputeHash(file); break; case HashcodeType.PBKDF2: throw new Exception("PBKDF2 Hashing is not supported."); } // Close the file. file.Close(); // Get the hashcode bytes as hex-string. sb = new StringBuilder(); for (int i = 0; i < hashValue.Length; i++) { sb.Append(hashValue[i].ToString("X2")); } // Return the hash code. return(sb.ToString()); } } catch (Exception) { throw; } finally { // Clean-up if (file != null) { file.Close(); } } }
/// <summary> /// Generate a public secret key pair RSA crypto service provider. /// </summary> /// <param name="publicKey">The stream where public key data is written to.</param> /// <param name="secretKey">The stream where secret key data is written to.</param> /// <param name="identity">The unique identity of the public secret key pair (Name (comments) <[email protected]>).</param> /// <param name="password">The password used to protect the secret key.</param> /// <param name="keyID">The unique key id of the public secret key pair.</param> /// <param name="isCritical">True, if should be treated as critical, false otherwise.</param> /// <param name="secondsKeyValid">The number of seconds the key is valid, or zero if no expiry.</param> /// <param name="secondsSignatureValid">The number of seconds the signature is valid, or zero if no expiry.</param> /// <param name="protectedKeys">Should the public and secret key data be protected.</param> /// <param name="publicExponent">The public exponent (e; the public key is now represented as {e, n}).</param> /// <param name="strength">The strength of the cipher.</param> /// <param name="hashAlgorithm">The preferred hash algorithm to use to create the hash value.</param> /// <param name="symmetricKeyAlgorithm">The symmetric key algorithm used for cryptography.</param> /// <returns>The RSA cryto service provider.</returns> public RSACryptoServiceProvider Generate(System.IO.Stream publicKey, System.IO.Stream secretKey, string identity, string password, out long keyID, bool isCritical = false, long secondsKeyValid = 0, long secondsSignatureValid = 0, bool protectedKeys = true, long publicExponent = 3, int strength = 4096, Nequeo.Cryptography.HashcodeType hashAlgorithm = HashcodeType.SHA512, Nequeo.Cryptography.SymmetricKeyAlgorithmType symmetricKeyAlgorithm = Nequeo.Cryptography.SymmetricKeyAlgorithmType.Aes256) { // Create the rsa key paramaters from the strength and public exponent. Key.Crypto.Generators.RsaKeyPairGenerator keyPair = new Key.Crypto.Generators.RsaKeyPairGenerator(); Key.Crypto.Parameters.RsaKeyGenerationParameters keyPairParam = new Key.Crypto.Parameters.RsaKeyGenerationParameters( Key.Math.BigInteger.ValueOf(publicExponent), new Key.Security.SecureRandom(), strength, 25); // Initialise the parameters and generate the public private key pair. keyPair.Init(keyPairParam); Key.Crypto.AsymmetricCipherKeyPair rsaKeyPair = keyPair.GenerateKeyPair(); // Seperate the keys. Key.Crypto.Parameters.RsaKeyParameters rsaPrivatePublic = (Key.Crypto.Parameters.RsaKeyParameters)rsaKeyPair.Public; Key.Crypto.Parameters.RsaPrivateCrtKeyParameters rsaCrtPrivateParam = (Key.Crypto.Parameters.RsaPrivateCrtKeyParameters)rsaKeyPair.Private; // If file is not protected. if (!protectedKeys) { secretKey = new Key.Bcpg.ArmoredOutputStream(secretKey); } // Create the signature subpackets. Key.Bcpg.OpenPgp.PgpSignatureSubpacketGenerator signatureSubpacketGenerator = new Key.Bcpg.OpenPgp.PgpSignatureSubpacketGenerator(); signatureSubpacketGenerator.SetKeyExpirationTime(isCritical, secondsKeyValid); signatureSubpacketGenerator.SetPreferredHashAlgorithms(isCritical, new int[] { (int)GetHashAlgorithm(hashAlgorithm) }); signatureSubpacketGenerator.SetSignatureExpirationTime(isCritical, secondsSignatureValid); // Create the signature subpackets. Key.Bcpg.OpenPgp.PgpSignatureSubpacketGenerator signatureSubpacketUnHashedGenerator = new Key.Bcpg.OpenPgp.PgpSignatureSubpacketGenerator(); signatureSubpacketUnHashedGenerator.SetKeyExpirationTime(isCritical, secondsKeyValid); signatureSubpacketUnHashedGenerator.SetPreferredHashAlgorithms(isCritical, new int[] { (int)GetHashAlgorithm(hashAlgorithm) }); signatureSubpacketUnHashedGenerator.SetSignatureExpirationTime(isCritical, secondsSignatureValid); // Generate the packets Key.Bcpg.OpenPgp.PgpSignatureSubpacketVector hashedPackets = signatureSubpacketGenerator.Generate(); Key.Bcpg.OpenPgp.PgpSignatureSubpacketVector unhashedPackets = signatureSubpacketUnHashedGenerator.Generate(); // Create the secret key. Key.Bcpg.OpenPgp.PgpSecretKey pgpSecretKey = new Key.Bcpg.OpenPgp.PgpSecretKey ( Key.Bcpg.OpenPgp.PgpSignature.DefaultCertification, Key.Bcpg.PublicKeyAlgorithmTag.RsaGeneral, rsaPrivatePublic, rsaCrtPrivateParam, DateTime.UtcNow, identity, GetSymmetricKeyAlgorithm(symmetricKeyAlgorithm), password.ToArray(), true, hashedPackets, unhashedPackets, new Key.Security.SecureRandom(), GetHashAlgorithm(hashAlgorithm) ); // Encode the secret key. pgpSecretKey.Encode(secretKey); // If file is not protected. if (!protectedKeys) { secretKey.Close(); publicKey = new Key.Bcpg.ArmoredOutputStream(publicKey); } // Get the public key from the secret key. Key.Bcpg.OpenPgp.PgpPublicKey pgpPublicKey = pgpSecretKey.PublicKey; pgpPublicKey.Encode(publicKey); // If file is not protected. if (!protectedKeys) { publicKey.Close(); } // Assign the rsa parameters. RSAParameters rsaParam = new RSAParameters(); rsaParam.D = rsaCrtPrivateParam.Exponent.ToByteArrayUnsigned(); rsaParam.DP = rsaCrtPrivateParam.DP.ToByteArrayUnsigned(); rsaParam.DQ = rsaCrtPrivateParam.DQ.ToByteArrayUnsigned(); rsaParam.InverseQ = rsaCrtPrivateParam.QInv.ToByteArrayUnsigned(); rsaParam.P = rsaCrtPrivateParam.P.ToByteArrayUnsigned(); rsaParam.Q = rsaCrtPrivateParam.Q.ToByteArrayUnsigned(); rsaParam.Modulus = rsaCrtPrivateParam.Modulus.ToByteArrayUnsigned(); rsaParam.Exponent = rsaCrtPrivateParam.PublicExponent.ToByteArrayUnsigned(); // Create the encyption provider. RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider(); rsaProvider.ImportParameters(rsaParam); // Return the rsa provider. keyID = pgpSecretKey.KeyId; return(rsaProvider); }
/// <summary> /// Verifies that a digital signature is valid by determining the hash value /// in the signature using the provided public key and comparing it to the hash /// value of the provided data. /// </summary> /// <param name="inputStream">The data that was signed.</param> /// <param name="signature">The signature data to be verified.</param> /// <param name="rsaProvider">The RSA crypto service provider.</param> /// <param name="hashAlgorithm">The hash algorithm to use to create the hash value.</param> /// <returns>True if the signature is valid; otherwise, false.</returns> public bool VerifyData(Stream inputStream, byte[] signature, RSACryptoServiceProvider rsaProvider, Nequeo.Cryptography.HashcodeType hashAlgorithm = HashcodeType.SHA512) { Stream signatureInput = null; try { // Export the signer public key parameters. RSAParameters rsaPublicKeySignerParam = rsaProvider.ExportParameters(false); Key.Crypto.Parameters.RsaKeyParameters rsaPublicKeySigner = new Key.Crypto.Parameters.RsaKeyParameters( false, new Key.Math.BigInteger(1, rsaPublicKeySignerParam.Modulus), new Key.Math.BigInteger(1, rsaPublicKeySignerParam.Exponent) ); signatureInput = new MemoryStream(signature); signatureInput = Key.Bcpg.OpenPgp.PgpUtilities.GetDecoderStream(signatureInput); // Get the public key. Key.Bcpg.OpenPgp.PgpPublicKey publicKey = new Key.Bcpg.OpenPgp.PgpPublicKey(Key.Bcpg.PublicKeyAlgorithmTag.RsaGeneral, rsaPublicKeySigner, DateTime.UtcNow); Key.Bcpg.OpenPgp.PgpObjectFactory pgpFact = new Key.Bcpg.OpenPgp.PgpObjectFactory(signatureInput); Key.Bcpg.OpenPgp.PgpSignatureList signatureList = null; Key.Bcpg.OpenPgp.PgpObject pgpObject = pgpFact.NextPgpObject(); // If the message is compressed. if (pgpObject is Key.Bcpg.OpenPgp.PgpCompressedData) { // Get the compression object. Key.Bcpg.OpenPgp.PgpCompressedData compressedData = (Key.Bcpg.OpenPgp.PgpCompressedData)pgpObject; pgpFact = new Key.Bcpg.OpenPgp.PgpObjectFactory(compressedData.GetDataStream()); signatureList = (Key.Bcpg.OpenPgp.PgpSignatureList)pgpFact.NextPgpObject(); } else { // Get the message list. signatureList = (Key.Bcpg.OpenPgp.PgpSignatureList)pgpObject; } // Load the public key into the pgp signer. Key.Bcpg.OpenPgp.PgpSignature pgpSignature = signatureList[0]; pgpSignature.InitVerify(publicKey); int ch; while ((ch = inputStream.ReadByte()) >= 0) { // Update the generator. pgpSignature.Update((byte)ch); } // Verify the signature. if (pgpSignature.Verify()) { // signature verified. return(true); } else { // signature verification failed. return(false); } } catch (Exception) { throw; } finally { if (signatureInput != null) { signatureInput.Close(); } } }
/// <summary> /// Computes the hash value of the specified input stream using the specified /// hash algorithm, and signs the resulting hash value. /// </summary> /// <param name="inputStream">The input data for which to compute the hash.</param> /// <param name="rsaProvider">The RSA crypto service provider.</param> /// <param name="keyID">The unique key id of the public secret key pair.</param> /// <param name="hashAlgorithm">The hash algorithm to use to create the hash value.</param> /// <returns>The signature for the specified data.</returns> public byte[] SignData(Stream inputStream, RSACryptoServiceProvider rsaProvider, long keyID, Nequeo.Cryptography.HashcodeType hashAlgorithm = HashcodeType.SHA512) { MemoryStream output = null; Key.Bcpg.BcpgOutputStream pgpOutput = null; try { int ch; output = new MemoryStream(); // Export the signer private key parameters. RSAParameters rsaPrivateKeySignerParam = rsaProvider.ExportParameters(true); Key.Crypto.Parameters.RsaPrivateCrtKeyParameters rsaPrivateKeySigner = new Key.Crypto.Parameters.RsaPrivateCrtKeyParameters( new Key.Math.BigInteger(1, rsaPrivateKeySignerParam.Modulus), new Key.Math.BigInteger(1, rsaPrivateKeySignerParam.Exponent), new Key.Math.BigInteger(1, rsaPrivateKeySignerParam.D), new Key.Math.BigInteger(1, rsaPrivateKeySignerParam.P), new Key.Math.BigInteger(1, rsaPrivateKeySignerParam.Q), new Key.Math.BigInteger(1, rsaPrivateKeySignerParam.DP), new Key.Math.BigInteger(1, rsaPrivateKeySignerParam.DQ), new Key.Math.BigInteger(1, rsaPrivateKeySignerParam.InverseQ) ); // Get the private key. Key.Bcpg.OpenPgp.PgpPrivateKey privateKey = new Key.Bcpg.OpenPgp.PgpPrivateKey(rsaPrivateKeySigner, keyID); // Create a signature generator. Key.Bcpg.OpenPgp.PgpSignatureGenerator signatureGenerator = new Key.Bcpg.OpenPgp.PgpSignatureGenerator(Key.Bcpg.PublicKeyAlgorithmTag.RsaGeneral, GetHashAlgorithm(hashAlgorithm)); signatureGenerator.InitSign(Key.Bcpg.OpenPgp.PgpSignature.BinaryDocument, privateKey); // Create the output stream. pgpOutput = new Key.Bcpg.BcpgOutputStream(output); // Read the input stream. while ((ch = inputStream.ReadByte()) >= 0) { // Update the generator. signatureGenerator.Update((byte)ch); } // Write the hash to the output stream. Key.Bcpg.OpenPgp.PgpSignature signature = signatureGenerator.Generate(); signature.Encode(pgpOutput); // Return the signed value. return(output.ToArray()); } catch (Exception) { throw; } finally { if (output != null) { output.Close(); } if (pgpOutput != null) { pgpOutput.Close(); } } }
/// <summary> /// Encode the password. /// </summary> /// <param name="password">The password to encode.</param> /// <param name="passwordFormat">The password format type to encode with.</param> /// <param name="hashcodeType">The hash code type (used when format is Hashed).</param> /// <returns>The encode password (includes at the start of the password the encoded salt).</returns> public string Encode(SecureString password, Nequeo.Cryptography.PasswordFormat passwordFormat, Nequeo.Cryptography.HashcodeType hashcodeType = Cryptography.HashcodeType.SHA512) { return(Encode(new Nequeo.Security.SecureText().GetText(password), passwordFormat, hashcodeType)); }
/// <summary> /// Generate a public secret key pair. /// </summary> /// <param name="publicKey">The stream where public key data is written to.</param> /// <param name="secretKey">The stream where secret key data is written to.</param> /// <param name="identity">The unique identity of the public secret key pair (Name (comments) <[email protected]>).</param> /// <param name="password">The password used to protect the secret key.</param> /// <param name="isCritical">True, if should be treated as critical, false otherwise.</param> /// <param name="secondsKeyValid">The number of seconds the key is valid, or zero if no expiry.</param> /// <param name="secondsSignatureValid">The number of seconds the signature is valid, or zero if no expiry.</param> /// <param name="protectedKeys">Should the public and secret key data be protected.</param> /// <param name="publicExponent">The public exponent (e; the public key is now represented as {e, n}).</param> /// <param name="strength">The strength of the cipher.</param> /// <param name="hashAlgorithm">The preferred hash algorithm to use to create the hash value.</param> /// <param name="publicKeyAlgorithm">The public key algorithm type.</param> /// <param name="certificateLevel">The certification level.</param> /// <param name="symmetricKeyAlgorithm">The symmetric key algorithm used for cryptography.</param> /// <returns>The unique key id of the public secret key pair.</returns> public long Generate(System.IO.Stream publicKey, System.IO.Stream secretKey, Openpgp.Identity identity, string password, bool isCritical = false, long secondsKeyValid = 0, long secondsSignatureValid = 0, bool protectedKeys = true, long publicExponent = 3, int strength = 4096, Nequeo.Cryptography.HashcodeType hashAlgorithm = HashcodeType.SHA512, Openpgp.PublicKeyAlgorithmType publicKeyAlgorithm = Openpgp.PublicKeyAlgorithmType.RsaGeneral, Openpgp.CertificateLevelType certificateLevel = Openpgp.CertificateLevelType.DefaultCertification, Nequeo.Cryptography.SymmetricKeyAlgorithmType symmetricKeyAlgorithm = Nequeo.Cryptography.SymmetricKeyAlgorithmType.Aes256) { // Create the rsa key paramaters from the strength and public exponent. Key.Crypto.Generators.RsaKeyPairGenerator keyPair = new Key.Crypto.Generators.RsaKeyPairGenerator(); Key.Crypto.Parameters.RsaKeyGenerationParameters keyPairParam = new Key.Crypto.Parameters.RsaKeyGenerationParameters( Key.Math.BigInteger.ValueOf(publicExponent), new Key.Security.SecureRandom(), strength, 25); // Initialise the parameters and generate the public private key pair. keyPair.Init(keyPairParam); Key.Crypto.AsymmetricCipherKeyPair rsaKeyPair = keyPair.GenerateKeyPair(); // Seperate the keys. Key.Crypto.Parameters.RsaKeyParameters rsaPrivatePublic = (Key.Crypto.Parameters.RsaKeyParameters)rsaKeyPair.Public; Key.Crypto.Parameters.RsaPrivateCrtKeyParameters rsaCrtPrivateParam = (Key.Crypto.Parameters.RsaPrivateCrtKeyParameters)rsaKeyPair.Private; // If file is not protected. if (!protectedKeys) { secretKey = new Key.Bcpg.ArmoredOutputStream(secretKey); } // Create the signature subpackets. Key.Bcpg.OpenPgp.PgpSignatureSubpacketGenerator signatureSubpacketGenerator = new Key.Bcpg.OpenPgp.PgpSignatureSubpacketGenerator(); signatureSubpacketGenerator.SetKeyExpirationTime(isCritical, secondsKeyValid); signatureSubpacketGenerator.SetPreferredHashAlgorithms(isCritical, new int[] { (int)Openpgp.PublicSecretKey.GetHashAlgorithm(hashAlgorithm) }); signatureSubpacketGenerator.SetSignatureExpirationTime(isCritical, secondsSignatureValid); // Create the signature subpackets. Key.Bcpg.OpenPgp.PgpSignatureSubpacketGenerator signatureSubpacketUnHashedGenerator = new Key.Bcpg.OpenPgp.PgpSignatureSubpacketGenerator(); signatureSubpacketUnHashedGenerator.SetKeyExpirationTime(isCritical, secondsKeyValid); signatureSubpacketUnHashedGenerator.SetPreferredHashAlgorithms(isCritical, new int[] { (int)Openpgp.PublicSecretKey.GetHashAlgorithm(hashAlgorithm) }); signatureSubpacketUnHashedGenerator.SetSignatureExpirationTime(isCritical, secondsSignatureValid); // Generate the packets Key.Bcpg.OpenPgp.PgpSignatureSubpacketVector hashedPackets = signatureSubpacketGenerator.Generate(); Key.Bcpg.OpenPgp.PgpSignatureSubpacketVector unhashedPackets = signatureSubpacketUnHashedGenerator.Generate(); // Create the secret key. Key.Bcpg.OpenPgp.PgpSecretKey pgpSecretKey = new Key.Bcpg.OpenPgp.PgpSecretKey ( GetCertificateLevelType(certificateLevel), GetPublicKeyAlgorithm(publicKeyAlgorithm), rsaPrivatePublic, rsaCrtPrivateParam, DateTime.UtcNow, identity.ToString(), Openpgp.PublicSecretKey.GetSymmetricKeyAlgorithm(symmetricKeyAlgorithm), password.ToArray(), true, hashedPackets, unhashedPackets, new Key.Security.SecureRandom(), Openpgp.PublicSecretKey.GetHashAlgorithm(hashAlgorithm) ); // Encode the secret key. pgpSecretKey.Encode(secretKey); // If file is not protected. if (!protectedKeys) { secretKey.Close(); publicKey = new Key.Bcpg.ArmoredOutputStream(publicKey); } // Get the public key from the secret key. Key.Bcpg.OpenPgp.PgpPublicKey pgpPublicKey = pgpSecretKey.PublicKey; pgpPublicKey.Encode(publicKey); // If file is not protected. if (!protectedKeys) { publicKey.Close(); } // Return the key id. return(pgpSecretKey.KeyId); }