public void MicrosoftCertificateAuthority_Sign_CngEcdh256_CertificateAuthorityRequestResponse_Issued()
        {
            string templateName = "ServerAuthentication-CngEcdh";

            int                keysize    = 256;
            string             commonName = "domain.com";
            WindowsApi         api        = WindowsApi.Cng;
            CipherAlgorithm    cipher     = CipherAlgorithm.ECDH;
            KeyUsage           keyUsage   = KeyUsage.ServerAuthentication;
            CertificateSubject subject    = new CertificateSubject(commonName);

            Win32CertificateProvider provider = new Win32CertificateProvider();

            CertificateRequest csr = provider.CreateCsrKeyPair(subject, cipher, keysize, api, SigningRequestProtocol.Pkcs10);

            MicrosoftCertificateAuthority ca = new MicrosoftCertificateAuthority(new MicrosoftCertificateAuthorityOptions()
            {
                AuthenticationRealm = domain,
                AuthenticationType  = MicrosoftCertificateAuthorityAuthenticationType.UsernamePassword,
                HashAlgorithm       = HashAlgorithm.SHA256,
                ServerName          = caServerName,
                CommonName          = caCommonName,
                Username            = username,
                Password            = password
            });

            CertificateAuthorityRequestResponse response = ca.Sign(csr, templateName, keyUsage);

            Assert.AreEqual(CertificateRequestStatus.Issued, response.CertificateRequestStatus);
        }
Beispiel #2
0
 public static Cipher CreateCipher(SSHProtocol protocol, CipherAlgorithm algorithm,
                                   byte[] key, byte[] iv)
 {
   if (protocol == SSHProtocol.SSH1)
   {
     //ignoring iv
     return CreateCipher(protocol, algorithm, key);
   }
   else
   {
     switch (algorithm)
     {
       case CipherAlgorithm.TripleDES:
         return new SSH2.TripleDESCipher2(key, iv);
       case CipherAlgorithm.Blowfish:
         return new SSH2.BlowfishCipher2(key, iv);
       case CipherAlgorithm.AES128:
       case CipherAlgorithm.AES192:
       case CipherAlgorithm.AES256:
       case CipherAlgorithm.AES128CTR:
       case CipherAlgorithm.AES192CTR:
       case CipherAlgorithm.AES256CTR:
         //return new RijindaelManagedCipher(key, iv, algorithm);
         return new SSH2.RijindaelCipher2(key, iv, algorithm);
       default:
         throw new SSHException("unknown algorithm " + algorithm);
     }
   }
 }
Beispiel #3
0
        private static SymmetricAlgorithm CreateCipher(CipherAlgorithm ca, string encryptionKey)
        {
            SymmetricAlgorithm sa = null;

            Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(encryptionKey, new byte[]
                                                            { 21, 221, 125, 99, 18, 200, 181, 116, 158, 30, 180, 73, 108 });

            switch (ca)
            {
            case CipherAlgorithm.AES128:
                sa = Aes.Create();
                break;

            case CipherAlgorithm.AES256:
                sa = Aes.Create();
                break;

            case CipherAlgorithm.TwoFish128:
                sa = new Twofish();
                break;

            case CipherAlgorithm.BlowFish256:
                sa = new BlowFish();
                break;

            case CipherAlgorithm.Serpent128:
                sa = new SerpentEngine();
                break;
            }

            sa.Key = pdb.GetBytes(sa.KeySize / 8);
            sa.IV  = pdb.GetBytes(sa.BlockSize / 8);

            return(sa);
        }
Beispiel #4
0
        //If encrypt is true, encrypts the given file into a new file in the same folder with name ".enc" appended.
        //If encrypt is false, decrypts the given file into a new file in the same folder with name ".dec" appended.
        //limit: file size limit
        internal static void EncryptOrDecrypt(CipherAlgorithm ca, string inputFile, string outputFile, string encryptionKey, bool encrypt)
        {
            run = true;
            using (SymmetricAlgorithm encryptor = CreateCipher(ca, encryptionKey))
            {
                byte[] buffer = new byte[1024];

                using (FileStream inputFs = new FileStream(inputFile, FileMode.Open, FileAccess.Read))
                    using (FileStream outputFs = new FileStream(outputFile, FileMode.CreateNew))
                        using (CryptoStream cs = new CryptoStream(outputFs, encrypt ? encryptor.CreateEncryptor() : encryptor.CreateDecryptor(), CryptoStreamMode.Write))
                        {
                            int bytesRead;
                            while (run && (bytesRead = inputFs.Read(buffer, 0, 1024)) > 0)
                            {
                                cs.Write(buffer, 0, bytesRead);
                                Processed(bytesRead);
                            }
                        }
            }

            if (!run)
            {
                File.Delete(outputFile);
            }

            run = false;
        }
        /// <summary>
        /// Constructor
        /// </summary>
        public AvailableNetworkGroupPack(
            InterfaceInfo interfaceInfo,
            NetworkIdentifier ssid,
            BssType bssType,
            int signalQuality,
            bool isSecurityEnabled,
            string profileName,
            AuthenticationAlgorithm authenticationAlgorithm,
            CipherAlgorithm cipherAlgorithm,
            IEnumerable <BssNetworkPack> bssNetworks) : base(
                interfaceInfo: interfaceInfo,
                ssid: ssid,
                bssType: bssType,
                signalQuality: signalQuality,
                isSecurityEnabled: isSecurityEnabled,
                profileName: profileName,
                authenticationAlgorithm: authenticationAlgorithm,
                cipherAlgorithm: cipherAlgorithm)
        {
            this.BssNetworks = Array.AsReadOnly(bssNetworks?.OrderByDescending(x => x.LinkQuality).ToArray() ?? new BssNetworkPack[0]);
            if (!this.BssNetworks.Any())
            {
                return;
            }

            var highestLinkQualityNetwork = this.BssNetworks.First();

            LinkQuality = highestLinkQualityNetwork.LinkQuality;
            Frequency   = highestLinkQualityNetwork.Frequency;
            Band        = highestLinkQualityNetwork.Band;
            Channel     = highestLinkQualityNetwork.Channel;
        }
        public AdcsTemplate DiscoverTemplate(CipherAlgorithm cipher, WindowsApi api, KeyUsage keyUsage)
        {
            Expression <Func <AdcsTemplate, bool> > query = template => template.Cipher == cipher && template.WindowsApi == api && template.KeyUsage.ToString() == keyUsage.ToString();
            AdcsTemplate results = configurationRepository.Get <AdcsTemplate>(query).First();

            return(results);
        }
        private CX509PrivateKey CreatePrivateKey(CipherAlgorithm cipher, int keysize, WindowsApi api = WindowsApi.CryptoApi)
        {
            CX509PrivateKey privateKey = new CX509PrivateKey
            {
                ProviderName = GetWindowsApiProviderName(api)
            };

            switch (api)
            {
            case WindowsApi.Cng:
                privateKey.KeySpec   = X509KeySpec.XCN_AT_NONE;
                privateKey.LegacyCsp = false;
                break;

            case WindowsApi.CryptoApi:
                privateKey.KeySpec = X509KeySpec.XCN_AT_KEYEXCHANGE;
                break;

            default:
                throw new AlgorithmNotSupportedByProviderException("Cryptographic provider is not valid");
            }

            privateKey.Algorithm          = GetPrivateKeyAlgorithm(cipher, keysize);
            privateKey.Length             = keysize;
            privateKey.ExportPolicy       = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_EXPORT_FLAG;
            privateKey.KeyUsage           = X509PrivateKeyUsageFlags.XCN_NCRYPT_ALLOW_ALL_USAGES;
            privateKey.MachineContext     = true;
            privateKey.CspInformations    = GetCspInformation(api);
            privateKey.SecurityDescriptor = GetDefaultPrivateKeySecurityDescriptor();
            privateKey.Create();

            return(privateKey);
        }
Beispiel #8
0
 public AgileEncryptionVerifier(CipherAlgorithm cipherAlgorithm, HashAlgorithm hashAlgorithm, int keyBits, int blockSize, ChainingMode chainingMode)
 {
     CipherAlgorithm = (cipherAlgorithm);
     HashAlgorithm   = (hashAlgorithm);
     ChainingMode    = (chainingMode);
     SpinCount       = (100000); // TODO: use parameter
 }
        public static string AlgorithmToSSH2Name(CipherAlgorithm algorithm)
        {
            switch (algorithm)
            {
            case CipherAlgorithm.TripleDES:
                return("3des-cbc");

            case CipherAlgorithm.Blowfish:
                return("blowfish-cbc");

            case CipherAlgorithm.AES128:
                return("aes128-cbc");

            case CipherAlgorithm.AES192:
                return("aes192-cbc");

            case CipherAlgorithm.AES256:
                return("aes256-cbc");

            case CipherAlgorithm.AES128CTR:
                return("aes128-ctr");

            case CipherAlgorithm.AES192CTR:
                return("aes192-ctr");

            case CipherAlgorithm.AES256CTR:
                return("aes256-ctr");

            default:
                throw new SSHException("unknown algorithm " + algorithm);
            }
        }
Beispiel #10
0
        public static String ToName(CipherAlgorithm algorithm)
        {
            switch (algorithm)
            {
            //case CipherAlgorithm.IDEA: return "IDEA";     // See comment in Enums.cs
            case CipherAlgorithm.None: return(String.Empty);

            case CipherAlgorithm.ThreeDes: return("3DES");

            case CipherAlgorithm.Cast5: return("CAST5");

            case CipherAlgorithm.BlowFish: return("BLOWFISH");

            case CipherAlgorithm.Aes: return("AES");

            case CipherAlgorithm.Aes192: return("AES192");

            case CipherAlgorithm.Aes256: return("AES256");

            case CipherAlgorithm.TwoFish: return("TWOFISH");

            case CipherAlgorithm.Camellia128: return("CAMELLIA128");

            case CipherAlgorithm.Camellia192: return("CAMELLIA192");

            case CipherAlgorithm.Camellia256: return("CAMELLIA256");

            default: return(String.Empty);
            }
        }
        public static Cipher CreateCipher(SSHProtocol protocol, CipherAlgorithm algorithm, byte[] key)
        {
            if (protocol == SSHProtocol.SSH1)
            {
                switch (algorithm)
                {
                case CipherAlgorithm.TripleDES:
                    return(new SSH1.TripleDESCipher1(key));

                case CipherAlgorithm.Blowfish:
                    return(new SSH1.BlowfishCipher1(key));

                default:
                    throw new SSHException("unknown algorithm " + algorithm);
                }
            }
            else
            {
                switch (algorithm)
                {
                case CipherAlgorithm.TripleDES:
                    return(new SSH2.TripleDESCipher2(key));

                case CipherAlgorithm.Blowfish:
                    return(new SSH2.BlowfishCipher2(key));

                default:
                    throw new SSHException("unknown algorithm " + algorithm);
                }
            }
        }
        public static Cipher CreateCipher(SSHProtocol protocol, CipherAlgorithm algorithm, byte[] key, byte[] iv)
        {
            if (protocol == SSHProtocol.SSH1)            //ignoring iv
            {
                return(CreateCipher(protocol, algorithm, key));
            }
            else
            {
                switch (algorithm)
                {
                case CipherAlgorithm.TripleDES:
                    return(new SSH2.TripleDESCipher2(key, iv));

                case CipherAlgorithm.Blowfish:
                    return(new SSH2.BlowfishCipher2(key, iv));

                case CipherAlgorithm.AES128:
                case CipherAlgorithm.AES192:
                case CipherAlgorithm.AES256:
                case CipherAlgorithm.AES128CTR:
                case CipherAlgorithm.AES192CTR:
                case CipherAlgorithm.AES256CTR:
                    return(new SSH2.RijindaelCipher2(key, iv, algorithm));

                default:
                    throw new SSHException("unknown algorithm " + algorithm);
                }
            }
        }
Beispiel #13
0
 public override string ToString()
 {
     return(SslProtocol.ToString() + ", " +
            CipherAlgorithm.ToString() + " (" + cipherStrength.ToString() + " bit), " +
            KeyExchangeAlgorithm.ToString() + " (" + keyExchangeStrength.ToString() + " bit), " +
            HashAlgorithm.ToString() + " (" + hashStrength.ToString() + " bit)");
 }
Beispiel #14
0
        /// <summary>
        /// returns necessary key size from Algorithm in bytes
        /// </summary>
        public static int GetKeySize(CipherAlgorithm algorithm)
        {
            switch (algorithm)
            {
            case CipherAlgorithm.TripleDES:
                return(24);

            case CipherAlgorithm.Blowfish:
            case CipherAlgorithm.AES128:
            case CipherAlgorithm.AES128CTR:
                return(16);

            case CipherAlgorithm.AES192:
            case CipherAlgorithm.AES192CTR:
                return(24);

            case CipherAlgorithm.AES256:
            case CipherAlgorithm.AES256CTR:
                return(32);

            default:
                //throw new Exception("unknown algorithm " + algorithm);
                throw new Exception("unknown algorithm " + algorithm);
            }
        }
Beispiel #15
0
        private static IBlockCipher CreateBlockCipher(CipherAlgorithm cipherAlgorithm)
        {
            switch (cipherAlgorithm)
            {
            case CipherAlgorithm.AES: return(new AesEngine());

            case CipherAlgorithm.BLOWFISH: return(new BlowfishEngine());

            case CipherAlgorithm.CAMELLIA: return(new CamelliaEngine());

            case CipherAlgorithm.CAST5: return(new Cast5Engine());

            case CipherAlgorithm.CAST6: return(new Cast6Engine());

            case CipherAlgorithm.DES: return(new DesEngine());

            case CipherAlgorithm.DESEDE: return(new DesEdeEngine());

            case CipherAlgorithm.GOST28147: return(new Gost28147Engine());

            case CipherAlgorithm.IDEA: return(new IdeaEngine());

            case CipherAlgorithm.NOEKEON: return(new NoekeonEngine());

            case CipherAlgorithm.RC2: return(new RC2Engine());

            case CipherAlgorithm.RC5: return(new RC532Engine());

            case CipherAlgorithm.RC5_64: return(new RC564Engine());

            case CipherAlgorithm.RC6: return(new RC6Engine());

            case CipherAlgorithm.RIJNDAEL: return(new RijndaelEngine());

            case CipherAlgorithm.SEED: return(new SeedEngine());

            case CipherAlgorithm.SERPENT: return(new SerpentEngine());

            case CipherAlgorithm.SKIPJACK: return(new SkipjackEngine());

            case CipherAlgorithm.SM4: return(new SM4Engine());

            case CipherAlgorithm.TEA: return(new TeaEngine());

            case CipherAlgorithm.THREEFISH_256: return(new ThreefishEngine(ThreefishEngine.BLOCKSIZE_256));

            case CipherAlgorithm.THREEFISH_512: return(new ThreefishEngine(ThreefishEngine.BLOCKSIZE_512));

            case CipherAlgorithm.THREEFISH_1024: return(new ThreefishEngine(ThreefishEngine.BLOCKSIZE_1024));

            case CipherAlgorithm.TNEPRES: return(new TnepresEngine());

            case CipherAlgorithm.TWOFISH: return(new TwofishEngine());

            case CipherAlgorithm.XTEA: return(new XteaEngine());

            default:
                throw new SecurityUtilityException("Cipher " + cipherAlgorithm + " not recognised or not a block cipher");
            }
        }
Beispiel #16
0
        public void fromMenu()
        {
            string direction;
            string identifier;

            do
            {
                identifier = displayAlgorithmMenu();
                direction  = displayDirectionMenu(identifier);
            } while (direction == id_back);

            Console.Clear();
            Console.WriteLine("Wpisz tekst (potwierdź enterem)\n");
            string input = Console.ReadLine();

            Console.Clear();

            CipherAlgorithm algorithm = getAlgorithm(identifier);

            if (direction == id_from)
            {
                Console.WriteLine(algorithm.from(input));
            }
            else
            {
                Console.WriteLine(algorithm.to(input));
            }

            Console.ReadKey(true);
        }
Beispiel #17
0
        public string encryptString(string toEncrypt, string target, string sign = null, CipherAlgorithm algorithm = CipherAlgorithm.Aes256, bool armour = true, bool hideuserid = false)
        {
            List<KeyId> recipients = new List<KeyId>();
            recipients.Add(new KeyId(target));

            KeyId signkey = new KeyId(defaultsign);

            GpgInterface.ExePath = ExePath;

            string path = Directory.GetCurrentDirectory() + "\\" + GetUniqueKey() + ".txt";
            string pathout = path + ".out";

            System.IO.File.WriteAllText(path, toEncrypt);

            GpgEncrypt encrypt = new GpgEncrypt(path, pathout, armour, hideuserid, signkey, recipients, algorithm);

            encrypt.AskPassphrase = GetPassword;

            GpgInterfaceResult result = encrypt.Execute();

            System.IO.File.Delete(path);

            if (result.Status == GpgInterfaceStatus.Success)
            {
                string toReturn = System.IO.File.ReadAllText(pathout);
                System.IO.File.Delete(pathout);
                return toReturn;
            }
            else
            {
                throw new Exception("Encryption Failed");
            }
        }
Beispiel #18
0
        private ZipEntrySource fileToSource(FileInfo tmpFile, CipherAlgorithm cipherAlgorithm, byte[] keyBytes, byte[] ivBytes)
        {
            SecretKeySpec skeySpec = new SecretKeySpec(keyBytes, cipherAlgorithm.jceId);
            Cipher        ciDec    = CryptoFunctions.GetCipher(skeySpec, cipherAlgorithm, ChainingMode.cbc, ivBytes, Cipher.DECRYPT_MODE, "PKCS5PAdding");
            ZipFile       zf       = new ZipFile(tmpFile.FullName);

            return(new AesZipFileZipEntrySource(zf, ciDec));
        }
Beispiel #19
0
 internal SecurityAttributes(WLAN_SECURITY_ATTRIBUTES attributes)
 {
     _attributes     = attributes;
     SecurityEnabled = attributes.bSecurityEnabled;
     OneXEnabled     = attributes.bOneXEnabled;
     AuthAlgorithm   = (AuthAlgorithm)attributes.dot11AuthAlgorithm;
     CipherAlgorithm = (CipherAlgorithm)attributes.dot11CipherAlgorithm;
 }
Beispiel #20
0
 protected internal StandardEncryptionVerifier(CipherAlgorithm cipherAlgorithm, HashAlgorithm hashAlgorithm, int keyBits, int blockSize, ChainingMode chainingMode)
 {
     CipherAlgorithm  = (cipherAlgorithm);
     HashAlgorithm    = (hashAlgorithm);
     ChainingMode     = (chainingMode);
     SpinCount        = (SPIN_COUNT);
     verifierHashSize = hashAlgorithm.hashSize;
 }
Beispiel #21
0
 public AgileEncryptionHeader(CipherAlgorithm algorithm, HashAlgorithm hashAlgorithm, int keyBits, int blockSize, ChainingMode chainingMode)
 {
     CipherAlgorithm = (algorithm);
     HashAlgorithm   = (hashAlgorithm);
     KeySize         = (keyBits);
     BlockSize       = (blockSize);
     ChainingMode    = (chainingMode);
 }
Beispiel #22
0
 public static CipherAlgorithm[] ParseCipherAlgorithm(string[] t) {
     CipherAlgorithm[] ret = new CipherAlgorithm[t.Length];
     int i = 0;
     foreach (string a in t) {
         ret[i++] = ParseCipherAlgorithm(a);
     }
     return ret;
 }
Beispiel #23
0
        /**
         * instead of a password, it's also possible to decrypt via certificate.
         * Warning: this code is experimental and hasn't been validated
         *
         * @see <a href="http://social.msdn.microsoft.com/Forums/en-US/cc9092bb-0c82-4b5b-ae21-abf643bdb37c/agile-encryption-with-certificates">Agile encryption with certificates</a>
         *
         * @param keyPair
         * @param x509
         * @return true, when the data can be successfully decrypted with the given private key
         * @throws GeneralSecurityException
         */
        public bool VerifyPassword(KeyPair keyPair, X509Certificate x509)
        {
            AgileEncryptionVerifier ver        = (AgileEncryptionVerifier)builder.GetVerifier();
            AgileEncryptionHeader   header     = (AgileEncryptionHeader)builder.GetHeader();
            HashAlgorithm           hashAlgo   = header.HashAlgorithm;
            CipherAlgorithm         cipherAlgo = header.CipherAlgorithm;
            int blockSize = header.BlockSize;

            AgileCertificateEntry ace = null;

            foreach (AgileCertificateEntry aceEntry in ver.GetCertificates())
            {
                if (x509.Equals(aceEntry.x509))
                {
                    ace = aceEntry;
                    break;
                }
            }
            if (ace == null)
            {
                return(false);
            }

            Cipher cipher = Cipher.GetInstance("RSA");

            cipher.Init(Cipher.DECRYPT_MODE, keyPair.getPrivate());
            byte[]        keyspec   = cipher.DoFinal(ace.encryptedKey);
            SecretKeySpec secretKey = new SecretKeySpec(keyspec, ver.CipherAlgorithm.jceId);

            Mac x509Hmac = CryptoFunctions.GetMac(hashAlgo);

            x509Hmac.Init(secretKey);
            byte[] certVerifier = x509Hmac.DoFinal(ace.x509.GetEncoded());

            byte[] vec = CryptoFunctions.GenerateIv(hashAlgo, header.KeySalt, kIntegrityKeyBlock, blockSize);
            cipher = GetCipher(secretKey, cipherAlgo, ver.ChainingMode, vec, Cipher.DECRYPT_MODE);
            byte[] hmacKey = cipher.DoFinal(header.GetEncryptedHmacKey());
            hmacKey = GetBlock0(hmacKey, hashAlgo.hashSize);

            vec    = CryptoFunctions.GenerateIv(hashAlgo, header.KeySalt, kIntegrityValueBlock, blockSize);
            cipher = GetCipher(secretKey, cipherAlgo, ver.ChainingMode, vec, Cipher.DECRYPT_MODE);
            byte[] hmacValue = cipher.DoFinal(header.GetEncryptedHmacValue());
            hmacValue = GetBlock0(hmacValue, hashAlgo.hashSize);


            if (Arrays.Equals(ace.certVerifier, certVerifier))
            {
                SetSecretKey(secretKey);
                SetIntegrityHmacKey(hmacKey);
                SetIntegrityHmacValue(hmacValue);
                return(true);
            }
            else
            {
                return(false);
            }
        }
    public void NewTagEncryptedFromStream(byte[] bytes, CipherAlgorithm algorithm, byte[] data)
    {
        using var ms = new MemoryStream(bytes);
        var tag = ms.Decode <TagEncrypted>();

        Assert.AreEqual(ILTagId.Encrypted, tag.TagId);
        Assert.AreEqual(algorithm, tag.Algorithm);
        Assert.AreEqual(data.Length, tag.CipherData?.Length ?? 0);
    }
Beispiel #25
0
        /// <summary>
        /// constructs from file
        /// </summary>
        /// <param name="path">file name</param>
        /// <param name="passphrase">passphrase or empty string if passphrase is not required</param>
        public SSH1UserAuthKey(string path, string passphrase)
        {
            var fileTask = StorageFile.GetFileFromPathAsync(path);

            fileTask.AsTask().Wait();
            var fileObject = fileTask.AsTask().Result;
            var openTask   = fileObject.OpenReadAsync();

            openTask.AsTask().Wait();

            Stream s = openTask.AsTask().Result.AsStream();

            byte[] header = new byte[32];
            s.Read(header, 0, header.Length);
            if (Encoding.UTF8.GetString(header, 0, header.Length) != "SSH PRIVATE KEY FILE FORMAT 1.1\n")
            {
                //throw new Exception(String.Format(Strings.GetString("BrokenKeyFile"), path));
                throw new Exception(String.Format(Strings.GetString("BrokenKeyFile"), path));
            }

            SSH1DataReader reader = new SSH1DataReader(ReadAll(s));

            s.Dispose();

            byte[] cipher = reader.Read(2);             //first 2 bytes indicates algorithm and next 8 bytes is space
            reader.Read(8);

            _modulus        = reader.ReadMPInt();
            _publicExponent = reader.ReadMPInt();
            byte[] comment = reader.ReadString();
            byte[] prvt    = reader.ReadAll();
            //必要なら復号
            CipherAlgorithm algo = (CipherAlgorithm)cipher[1];

            if (algo != 0)
            {
                Cipher c   = CipherFactory.CreateCipher(SSHProtocol.SSH1, algo, ConvertToKey(passphrase));
                byte[] buf = new byte[prvt.Length];
                c.Decrypt(prvt, 0, prvt.Length, buf, 0);
                prvt = buf;
            }

            SSH1DataReader prvtreader = new SSH1DataReader(prvt);

            byte[] mark = prvtreader.Read(4);
            if (mark[0] != mark[2] || mark[1] != mark[3])
            {
                //throw new Exception(Strings.GetString("WrongPassphrase"));
                throw new Exception(Strings.GetString("WrongPassphrase"));
            }

            _privateExponent = prvtreader.ReadMPInt();
            _crtCoefficient  = prvtreader.ReadMPInt();
            _primeP          = prvtreader.ReadMPInt();
            _primeQ          = prvtreader.ReadMPInt();
        }
Beispiel #26
0
 /// <summary>
 /// Initializes a new instance of the <see cref="GpgApi.GpgEncrypt"/> class.
 /// </summary>
 /// <param name="fileName"></param>
 /// <param name="encryptedFileName"></param>
 /// <param name="armored"></param>
 /// <param name="hideUserIds"></param>
 /// <param name="signatureKeyId"></param>
 /// <param name="recipients"></param>
 /// <param name="cipherAlgorithm"></param>
 public GpgEncrypt(String fileName, String encryptedFileName, Boolean armored, Boolean hideUserIds, KeyId signatureKeyId, IEnumerable<KeyId> recipients, CipherAlgorithm cipherAlgorithm)
 {
     FileName = fileName;
     EncryptedFileName = encryptedFileName;
     Armored = armored;
     HideUserIds = hideUserIds;
     SignatureKeyId = signatureKeyId;
     Recipients = recipients;
     CipherAlgorithm = cipherAlgorithm;
 }
 public void Initialize(EncryptionInfo info,
                        CipherAlgorithm cipherAlgorithm, HashAlgorithm hashAlgorithm,
                        int keyBits, int blockSize, ChainingMode chainingMode)
 {
     this.info = info;
     header    = new BinaryRC4EncryptionHeader();
     verifier  = new BinaryRC4EncryptionVerifier();
     decryptor = new BinaryRC4Decryptor(this);
     encryptor = new BinaryRC4Encryptor(this);
 }
Beispiel #28
0
 /// <summary>
 /// Initializes a new instance of the <see cref="GpgApi.GpgEncrypt"/> class.
 /// </summary>
 /// <param name="fileName"></param>
 /// <param name="encryptedFileName"></param>
 /// <param name="armored"></param>
 /// <param name="hideUserIds"></param>
 /// <param name="signatureKeyId"></param>
 /// <param name="recipients"></param>
 /// <param name="cipherAlgorithm"></param>
 public GpgEncrypt(String fileName, String encryptedFileName, Boolean armored, Boolean hideUserIds, KeyId signatureKeyId, IEnumerable <KeyId> recipients, CipherAlgorithm cipherAlgorithm)
 {
     FileName          = fileName;
     EncryptedFileName = encryptedFileName;
     Armored           = armored;
     HideUserIds       = hideUserIds;
     SignatureKeyId    = signatureKeyId;
     Recipients        = recipients;
     CipherAlgorithm   = cipherAlgorithm;
 }
Beispiel #29
0
        /// <summary>
        /// constructs from file
        /// </summary>
        /// <param name="path">file name</param>
        /// <param name="passphrase">passphrase or empty string if passphrase is not required</param>
        public SSH1UserAuthKey(string path, string passphrase)
        {
#if PODEROSA_KEYFORMAT
            PrivateKeyLoader loader = new PrivateKeyLoader(path);
            loader.LoadSSH1PrivateKey(
                passphrase,
                out _modulus,
                out _publicExponent,
                out _privateExponent,
                out _primeP,
                out _primeQ,
                out _crtCoefficient,
                out _comment);
#else
            Stream s      = File.Open(path, FileMode.Open);
            byte[] header = new byte[32];
            s.Read(header, 0, header.Length);
            if (Encoding.ASCII.GetString(header) != "SSH PRIVATE KEY FILE FORMAT 1.1\n")
            {
                throw new SSHException(String.Format(Strings.GetString("BrokenKeyFile"), path));
            }

            SSH1DataReader reader = new SSH1DataReader(ReadAll(s));
            s.Close();

            byte[] cipher = reader.Read(2); //first 2 bytes indicates algorithm and next 8 bytes is space
            reader.Read(8);

            _modulus        = reader.ReadMPInt();
            _publicExponent = reader.ReadMPInt();
            _comment        = reader.ReadString();
            byte[] prvt = reader.GetRemainingDataView().GetBytes();
            //必要なら復号
            CipherAlgorithm algo = (CipherAlgorithm)cipher[1];
            if (algo != 0)
            {
                Cipher c   = CipherFactory.CreateCipher(SSHProtocol.SSH1, algo, ConvertToKey(passphrase));
                byte[] buf = new byte[prvt.Length];
                c.Decrypt(prvt, 0, prvt.Length, buf, 0);
                prvt = buf;
            }

            SSH1DataReader prvtreader = new SSH1DataReader(prvt);
            byte[]         mark       = prvtreader.Read(4);
            if (mark[0] != mark[2] || mark[1] != mark[3])
            {
                throw new SSHException(Strings.GetString("WrongPassphrase"));
            }

            _privateExponent = prvtreader.ReadMPInt();
            _crtCoefficient  = prvtreader.ReadMPInt();
            _primeP          = prvtreader.ReadMPInt();
            _primeQ          = prvtreader.ReadMPInt();
#endif
        }
Beispiel #30
0
        public void AdcsTemplateLogic_GetActiveDirectoryPublishedTemplate_ValidNameAndCipherEdsa_ReturnsObjectWithExpectedCipherAlgorithm()
        {
            string          name           = "ServerAuthentication-CngEcdsa";
            CipherAlgorithm expectedCipher = CipherAlgorithm.ECDSA;

            AdcsTemplateLogic templateLogic = new AdcsTemplateLogic(null, activeDirectory);

            AdcsCertificateTemplate template = templateLogic.GetActiveDirectoryPublishedTemplate(name, metadata);

            Assert.AreEqual(expectedCipher, template.Cipher);
        }
        /// <summary>
        /// Read SSH1 private key parameters.
        /// </summary>
        /// <param name="passphrase">passphrase for decrypt the key file</param>
        /// <param name="modulus">private key parameter</param>
        /// <param name="publicExponent">private key parameter</param>
        /// <param name="privateExponent">private key parameter</param>
        /// <param name="primeP">private key parameter</param>
        /// <param name="primeQ">private key parameter</param>
        /// <param name="crtCoefficient">private key parameter</param>
        /// <exception cref="SSHException">failed to parse</exception>
        public void Load(
            string passphrase,
            out BigInteger modulus,
            out BigInteger publicExponent,
            out BigInteger privateExponent,
            out BigInteger primeP,
            out BigInteger primeQ,
            out BigInteger crtCoefficient)
        {
            if (keyFile == null)
            {
                throw new SSHException("A key file is not loaded yet");
            }
            byte[] hdr = Encoding.ASCII.GetBytes(PrivateKeyFileHeader.SSH1_HEADER);
            if (!ByteArrayUtil.ByteArrayStartsWith(keyFile, hdr))
            {
                throw new SSHException(Strings.GetString("NotValidPrivateKeyFile"));
            }

            SSH1DataReader reader = new SSH1DataReader(keyFile);

            reader.Read(hdr.Length);

            byte[] cipher = reader.Read(2); //first 2 bytes indicates algorithm and next 8 bytes is space
            reader.Read(8);

            modulus        = reader.ReadMPInt();
            publicExponent = reader.ReadMPInt();
            byte[] comment = reader.ReadString();
            byte[] prvt    = reader.ReadAll();
            //必要なら復号
            CipherAlgorithm algo = (CipherAlgorithm)cipher[1];

            if (algo != 0)
            {
                Cipher c   = CipherFactory.CreateCipher(SSHProtocol.SSH1, algo, SSH1PassphraseToKey(passphrase));
                byte[] buf = new byte[prvt.Length];
                c.Decrypt(prvt, 0, prvt.Length, buf, 0);
                prvt = buf;
            }

            SSH1DataReader prvtreader = new SSH1DataReader(prvt);

            byte[] mark = prvtreader.Read(4);
            if (mark[0] != mark[2] || mark[1] != mark[3])
            {
                throw new SSHException(Strings.GetString("WrongPassphrase"));
            }

            privateExponent = prvtreader.ReadMPInt();
            crtCoefficient  = prvtreader.ReadMPInt();
            primeP          = prvtreader.ReadMPInt();
            primeQ          = prvtreader.ReadMPInt();
        }
Beispiel #32
0
        public static CipherAlgorithm[] ParseCipherAlgorithm(string[] t)
        {
            CipherAlgorithm[] ret = new CipherAlgorithm[t.Length];
            int i = 0;

            foreach (string a in t)
            {
                ret[i++] = ParseCipherAlgorithm(a);
            }
            return(ret);
        }
		/// <summary>
		/// returns necessary key size from Algorithm in bytes
		/// </summary>
		public static int GetKeySize(CipherAlgorithm algorithm) {
			switch(algorithm) {
				case CipherAlgorithm.TripleDES:
					return 24;
				case CipherAlgorithm.Blowfish:
				case CipherAlgorithm.AES128:
					return 16;
				default:
					throw new SSHException("unknown algorithm " + algorithm);
			}
		}
    public byte[] SerializeEncryptedText(CipherAlgorithm algorithm, string clearText)
    {
        var encodedBytes = new EncryptedText(algorithm,
                                             clearText,
                                             TestFakeSigner.FixedKeysInstance,
                                             TestFakeSigner.FixedKeysInstance,
                                             Array.Empty <TagReader>()).AsPayload.EncodedBytes;

        TestContext.WriteLine(encodedBytes.AsLiteral());
        return(encodedBytes.PartOf(124));
    }
Beispiel #35
0
        /**
         * Initialize the builder from scratch
         */
        public void Initialize(EncryptionInfo info, CipherAlgorithm cipherAlgorithm, HashAlgorithm hashAlgorithm, int keyBits, int blockSize, ChainingMode chainingMode)
        {
            this.info = info;

            if (cipherAlgorithm == null)
            {
                cipherAlgorithm = CipherAlgorithm.aes128;
            }
            if (cipherAlgorithm != CipherAlgorithm.aes128 &&
                cipherAlgorithm != CipherAlgorithm.aes192 &&
                cipherAlgorithm != CipherAlgorithm.aes256)
            {
                throw new EncryptedDocumentException("Standard encryption only supports AES128/192/256.");
            }

            if (hashAlgorithm == null)
            {
                hashAlgorithm = HashAlgorithm.sha1;
            }
            if (hashAlgorithm != HashAlgorithm.sha1)
            {
                throw new EncryptedDocumentException("Standard encryption only supports SHA-1.");
            }
            if (chainingMode == null)
            {
                chainingMode = ChainingMode.ecb;
            }
            if (chainingMode != ChainingMode.ecb)
            {
                throw new EncryptedDocumentException("Standard encryption only supports ECB chaining.");
            }
            if (keyBits == -1)
            {
                keyBits = cipherAlgorithm.defaultKeySize;
            }
            if (blockSize == -1)
            {
                blockSize = cipherAlgorithm.blockSize;
            }
            bool found = false;

            foreach (int ks in cipherAlgorithm.allowedKeySize)
            {
                found |= (ks == keyBits);
            }
            if (!found)
            {
                throw new EncryptedDocumentException("KeySize " + keyBits + " not allowed for Cipher " + cipherAlgorithm.ToString());
            }
            header    = new StandardEncryptionHeader(cipherAlgorithm, hashAlgorithm, keyBits, blockSize, chainingMode);
            verifier  = new StandardEncryptionVerifier(cipherAlgorithm, hashAlgorithm, keyBits, blockSize, chainingMode);
            decryptor = new StandardDecryptor(this);
            encryptor = new StandardEncryptor(this);
        }
 public static string AlgorithmToSSH2Name(CipherAlgorithm algorithm)
 {
     switch(algorithm) {
         case CipherAlgorithm.TripleDES:
             return "3des-cbc";
         case CipherAlgorithm.Blowfish:
             return "blowfish-cbc";
         case CipherAlgorithm.AES128:
             return "aes128-cbc";
         default:
             throw new SSHException("unknown algorithm " + algorithm);
     }
 }
Beispiel #37
0
        /// <summary>
        /// Append missing algorithm to the list of <see cref="CipherAlgorithm"/>.
        /// </summary>
        /// <param name="algorithms">list of <see cref="CipherAlgorithm"/></param>
        /// <returns>new array of of <see cref="CipherAlgorithm"/></returns>
        public static CipherAlgorithm[] AppendMissingCipherAlgorithm(CipherAlgorithm[] algorithms)
        {
            var enumSet = new HashSet<CipherAlgorithm>((CipherAlgorithm[])Enum.GetValues(typeof(CipherAlgorithm)));
            foreach (var a in algorithms) {
                enumSet.Remove(a);
            }
            var listToAppend = new List<CipherAlgorithm>(enumSet);
            listToAppend.Sort((a1, a2) => a2.GetDefaultPriority().CompareTo(a1.GetDefaultPriority()));    // descending order

            var list = new List<CipherAlgorithm>(algorithms.Length + enumSet.Count);
            list.AddRange(algorithms);
            list.AddRange(listToAppend);
            return list.ToArray();
        }
Beispiel #38
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="hostName">Host name</param>
 /// <param name="portNumber">port number</param>
 /// <param name="protocol">SSH protocol version</param>
 /// <param name="authType">authentication type</param>
 /// <param name="userName">user name for login</param>
 /// <param name="password">password for login. pass empty string for the keyboard interactive mode.</param>
 public SSHConnectionParameter(string hostName, int portNumber, SSHProtocol protocol, AuthenticationType authType, string userName, string password)
 {
     HostName = hostName;
     PortNumber = portNumber;
     Protocol = protocol;
     PreferableCipherAlgorithms = new CipherAlgorithm[] { CipherAlgorithm.AES256CTR, CipherAlgorithm.AES256, CipherAlgorithm.AES192CTR, CipherAlgorithm.AES192, CipherAlgorithm.AES128CTR, CipherAlgorithm.AES128, CipherAlgorithm.Blowfish, CipherAlgorithm.TripleDES };
     PreferableHostKeyAlgorithms = new PublicKeyAlgorithm[] { PublicKeyAlgorithm.DSA, PublicKeyAlgorithm.RSA };
     AuthenticationType = authType;
     UserName = userName;
     Password = password;
     TerminalName = "vt100";
     WindowSize = 0x1000;
     MaxPacketSize = 0x10000;
     CheckMACError = true;
 }
Beispiel #39
0
 public static Cipher CreateCipher(SSHProtocol protocol, CipherAlgorithm algorithm, byte[] key) {
     if (protocol == SSHProtocol.SSH1) {
         throw new SSHException("SSH1 is not supported");
     }
     else {
         switch (algorithm) {
             case CipherAlgorithm.TripleDES:
                 return new SSH2.TripleDESCipher2(key);
             case CipherAlgorithm.Blowfish:
                 return new SSH2.BlowfishCipher2(key);
             default:
                 throw new SSHException("unknown algorithm " + algorithm);
         }
     }
 }
 /// <summary>
 /// returns necessary key size from Algorithm in bytes
 /// </summary>
 public static int GetKeySize(CipherAlgorithm algorithm)
 {
     switch(algorithm) {
         case CipherAlgorithm.TripleDES:
             return 24;
         case CipherAlgorithm.Blowfish:
         case CipherAlgorithm.AES128:
         case CipherAlgorithm.AES128CTR:
             return 16;
         case CipherAlgorithm.AES192:
         case CipherAlgorithm.AES192CTR:
             return 24;
         case CipherAlgorithm.AES256:
         case CipherAlgorithm.AES256CTR:
             return 32;
         default:
             //throw new Exception("unknown algorithm " + algorithm);
             throw new Exception("unknown algorithm " + algorithm);
     }
 }
 public CipherAlgorithmListItem(CipherAlgorithm value)
 {
     this.Value = value;
     this.AlgorithmName = value.GetAlgorithmName();
 }
 public static string AlgorithmToSSH2Name(CipherAlgorithm algorithm)
 {
     switch(algorithm) {
         case CipherAlgorithm.TripleDES:
             return "3des-cbc";
         case CipherAlgorithm.Blowfish:
             return "blowfish-cbc";
         case CipherAlgorithm.AES128:
             return "aes128-cbc";
         case CipherAlgorithm.AES192:
             return "aes192-cbc";
         case CipherAlgorithm.AES256:
             return "aes256-cbc";
         case CipherAlgorithm.AES128CTR:
             return "aes128-ctr";
         case CipherAlgorithm.AES192CTR:
             return "aes192-ctr";
         case CipherAlgorithm.AES256CTR:
             return "aes256-ctr";
         default:
             //throw new Exception("unknown algorithm " + algorithm);
             throw new Exception("unknown algorithm " + algorithm);
     }
 }
 public static Cipher CreateCipher(SSHProtocol protocol, CipherAlgorithm algorithm, byte[] key)
 {
     if(protocol==SSHProtocol.SSH1) {
         switch(algorithm) {
             case CipherAlgorithm.TripleDES:
                 return new TripleDESCipher1(key);
             case CipherAlgorithm.Blowfish:
                 return new BlowfishCipher1(key);
             default:
                 //throw new Exception("unknown algorithm " + algorithm);
                 throw new Exception("unknown algorithm " + algorithm);
         }
     }
     else {
         switch(algorithm) {
             case CipherAlgorithm.TripleDES:
                 return new TripleDESCipher2(key);
             case CipherAlgorithm.Blowfish:
                 return new BlowfishCipher2(key);
             default:
                 //throw new Exception("unknown algorithm " + algorithm);
                 throw new Exception("unknown algorithm " + algorithm);
         }
     }
 }
Beispiel #44
0
 /// <summary>
 /// returns the block size from Algorithm in bytes
 /// </summary>
 public static int GetBlockSize(CipherAlgorithm algorithm) {
     switch (algorithm) {
         case CipherAlgorithm.TripleDES:
         case CipherAlgorithm.Blowfish:
             return 8;
         case CipherAlgorithm.AES128:
         case CipherAlgorithm.AES192:
         case CipherAlgorithm.AES256:
         case CipherAlgorithm.AES128CTR:
         case CipherAlgorithm.AES192CTR:
         case CipherAlgorithm.AES256CTR:
             return 16;
         default:
             throw new SSHException("unknown algorithm " + algorithm);
     }
 }
 private static IBlockCipher CreateBlockCipher(CipherAlgorithm cipherAlgorithm)
 {
     switch (cipherAlgorithm)
     {
         case CipherAlgorithm.AES: return new AesFastEngine();
         case CipherAlgorithm.BLOWFISH: return new BlowfishEngine();
         case CipherAlgorithm.CAMELLIA: return new CamelliaEngine();
         case CipherAlgorithm.CAST5: return new Cast5Engine();
         case CipherAlgorithm.CAST6: return new Cast6Engine();
         case CipherAlgorithm.DES: return new DesEngine();
         case CipherAlgorithm.DESEDE: return new DesEdeEngine();
         case CipherAlgorithm.GOST28147: return new Gost28147Engine();
         case CipherAlgorithm.IDEA: return new IdeaEngine();
         case CipherAlgorithm.NOEKEON: return new NoekeonEngine();
         case CipherAlgorithm.RC2: return new RC2Engine();
         case CipherAlgorithm.RC5: return new RC532Engine();
         case CipherAlgorithm.RC5_64: return new RC564Engine();
         case CipherAlgorithm.RC6: return new RC6Engine();
         case CipherAlgorithm.RIJNDAEL: return new RijndaelEngine();
         case CipherAlgorithm.SEED: return new SeedEngine();
         case CipherAlgorithm.SERPENT: return new SerpentEngine();
         case CipherAlgorithm.SKIPJACK: return new SkipjackEngine();
         case CipherAlgorithm.TEA: return new TeaEngine();
         case CipherAlgorithm.TWOFISH: return new TwofishEngine();
         case CipherAlgorithm.XTEA: return new XteaEngine();
         default:
             throw new SecurityUtilityException("Cipher " + cipherAlgorithm + " not recognised or not a block cipher");
     }
 }
Beispiel #46
0
 //�A���S���Y����
 private static string CipherAlgorithmName(CipherAlgorithm a)
 {
     switch(a) {
         case CipherAlgorithm.AES128:
             return "AES(Rijndael) ";
         case CipherAlgorithm.Blowfish:
             return "Blowfish";
         case CipherAlgorithm.TripleDES:
             return "TripleDES";
         default:
             throw new Exception("Unexpected Algorithm "+a);
     }
 }
Beispiel #47
0
 public RijindaelCipher2(byte[] key, byte[] iv, CipherAlgorithm algorithm) {
     _rijindael = new Rijndael();
     _rijindael.SetIV(iv);
     _rijindael.InitializeKey(key);
     if (algorithm == CipherAlgorithm.AES256CTR ||
         algorithm == CipherAlgorithm.AES192CTR ||
         algorithm == CipherAlgorithm.AES128CTR)
         isCTR = true;
     else
         isCTR = false;
 }
Beispiel #48
0
 public static String ToName(CipherAlgorithm algorithm)
 {
     switch (algorithm)
     {
         //case CipherAlgorithm.IDEA: return "IDEA";     // See comment in Enums.cs
         case CipherAlgorithm.None: return String.Empty;
         case CipherAlgorithm.ThreeDes: return "3DES";
         case CipherAlgorithm.Cast5: return "CAST5";
         case CipherAlgorithm.BlowFish: return "BLOWFISH";
         case CipherAlgorithm.Aes: return "AES";
         case CipherAlgorithm.Aes192: return "AES192";
         case CipherAlgorithm.Aes256: return "AES256";
         case CipherAlgorithm.TwoFish: return "TWOFISH";
         case CipherAlgorithm.Camellia128: return "CAMELLIA128";
         case CipherAlgorithm.Camellia192: return "CAMELLIA192";
         case CipherAlgorithm.Camellia256: return "CAMELLIA256";
         default: return String.Empty;
     }
 }
Beispiel #49
0
 public static Cipher CreateCipher(SSHProtocol protocol, CipherAlgorithm algorithm, byte[] key, byte[] iv)
 {
     if(protocol==SSHProtocol.SSH1) {
         return CreateCipher(protocol, algorithm, key);
     }
     else {
         switch(algorithm) {
             case CipherAlgorithm.TripleDES:
                 return new TripleDESCipher2(key, iv);
             case CipherAlgorithm.Blowfish:
                 return new BlowfishCipher2(key, iv);
             case CipherAlgorithm.AES128:
                 return new RijindaelCipher2(key, iv);
             default:
                 throw new SSHException("unknown algorithm " + algorithm);
         }
     }
 }