示例#1
1
文件: EncDecUtil.cs 项目: radtek/crm
 /// <summary>
 /// RSA加密
 /// </summary>
 /// <param name="pCertFilePath">pfx证书文件路径</param>
 /// <param name="pCertFilePassword">pfx证书文件的密码</param>
 /// <param name="pEncryptContent">需要加密的内容</param>
 /// <returns>密文</returns>
 public static byte[] RSAEncrypt(string pCertFilePath, string pCertFilePassword, string pEncryptContent)
 {
     using (FileStream fs = new FileStream(pCertFilePath, FileMode.Open))
     {
         byte[] bytes = new byte[fs.Length];
         fs.Read(bytes, 0, bytes.Length);
         fs.Close();
         X509Certificate2 mycert = new X509Certificate2(bytes, pCertFilePassword,
                                                        X509KeyStorageFlags.MachineKeySet
                                                        | X509KeyStorageFlags.PersistKeySet
                                                        | X509KeyStorageFlags.Exportable);
         AsymmetricKeyParameter bouncyCastlePrivateKey = EncDecUtil.TransformRSAPrivateKey(mycert.PrivateKey);
         IBufferedCipher        c = CipherUtilities.GetCipher("RSA/ECB/PKCS1Padding");// 参数与JAVA中解密的参数一致
         c.Init(true, bouncyCastlePrivateKey);
         byte[] outBytes = c.DoFinal(Encoding.UTF8.GetBytes(pEncryptContent));
         return(outBytes);
     }
 }
        internal WinzipAesCryptoStream(Stream stream, WinzipAesEncryptionData winzipAesEncryptionData, long length)
        {
            this.stream = stream;
            totalBytesLeftToRead = length;

            rijndael = CreateRijndael(winzipAesEncryptionData);
        }
示例#3
0
 /// <summary>
 /// Initializes a new instance of the <see cref="AsymmetricStream"/> class.
 /// </summary>
 /// <param name="cipher">The cipher.</param>
 /// <param name="output">The output.</param>
 /// <param name="initFunc">The init func.</param>
 /// <param name="encrypt">if set to <c>true</c> [encrypt].</param>
 public AsymmetricStream(IAsymmetricBlockCipher cipher, Stream output, Action<IBufferedCipher, bool> initFunc,
                         bool encrypt)
 {
     _cipher = new BufferedAsymmetricBlockCipher(cipher);
     _output = output;
     _initFunc = initFunc;
     _encrypt = encrypt;
 }
        private void InitializeRSA()
        {
            string[] keyComponents = publicKey.Split('|');
            var modulus = new Org.BouncyCastle.Math.BigInteger(keyComponents[1].ToLower(), 16);
            var exponent = new Org.BouncyCastle.Math.BigInteger(keyComponents[0].ToLower(), 16);
            RsaKeyParameters keyParams = new RsaKeyParameters(false, modulus, exponent);

            rsaCipher = CipherUtilities.GetCipher("RSA/None/PKCS1Padding");
            rsaCipher.Init(true, keyParams);
        }
        private Task<byte[]> Process(byte[] data, IBufferedCipher cipher)
        {

            return Task.Run<byte[]>(() =>
            {
                var byteCompositeKey = data;
            
                byteCompositeKey = cipher.ProcessBytes(byteCompositeKey);  

                return byteCompositeKey;

            });
        
        }
示例#6
0
        public static byte[] DecryptCipherDataUsingAesGcmAlgorithm(byte[] keyMaterial, byte[] cipherData)
        {
            if (keyMaterial.Length != 32)
            {
                throw new InvalidOperationException("KeyMaterial size was invalid.");
            }

            IBufferedCipher Cipher = CipherUtilities.GetCipher("AES/GCM/NoPadding");

            Cipher.Init(
                false,
                new ParametersWithIV(
                    ParameterUtilities.CreateKeyParameter("AES", keyMaterial),
                    s_ApplePayInitializationVector));
            return(Cipher.DoFinal(cipherData));
        }
示例#7
0
        private static Stream CreateStream(Stream s, bool bEncrypt, byte[] pbKey, byte[] pbIV)
        {
            StandardAesEngine.ValidateArguments(s, bEncrypt, pbKey, pbIV);

            byte[] pbLocalIV = new byte[16];
            Array.Copy(pbIV, pbLocalIV, 16);

            byte[] pbLocalKey = new byte[32];
            Array.Copy(pbKey, pbLocalKey, 32);

#if !KeePassRT
            RijndaelManaged r = new RijndaelManaged();
            if (r.BlockSize != 128)            // AES block size
            {
                Debug.Assert(false);
                r.BlockSize = 128;
            }

            r.IV      = pbLocalIV;
            r.KeySize = 256;
            r.Key     = pbLocalKey;
            r.Mode    = m_rCipherMode;
            r.Padding = m_rCipherPadding;

            ICryptoTransform iTransform = (bEncrypt ? r.CreateEncryptor() : r.CreateDecryptor());
            Debug.Assert(iTransform != null);
            if (iTransform == null)
            {
                throw new SecurityException("Unable to create Rijndael transform!");
            }

            return(new CryptoStream(s, iTransform, bEncrypt ? CryptoStreamMode.Write :
                                    CryptoStreamMode.Read));
#else
            AesEngine                 aes = new AesEngine();
            CbcBlockCipher            cbc = new CbcBlockCipher(aes);
            PaddedBufferedBlockCipher bc  = new PaddedBufferedBlockCipher(cbc,
                                                                          new Pkcs7Padding());
            KeyParameter     kp    = new KeyParameter(pbLocalKey);
            ParametersWithIV prmIV = new ParametersWithIV(kp, pbLocalIV);
            bc.Init(bEncrypt, prmIV);

            IBufferedCipher cpRead  = (bEncrypt ? null : bc);
            IBufferedCipher cpWrite = (bEncrypt ? bc : null);
            return(new CipherStream(s, cpRead, cpWrite));
#endif
        }
        private bool VerifyDigest(byte[] digest, AsymmetricKeyParameter key, byte[] signature)
        {
            //IL_010a: Expected O, but got Unknown
            string encryptionAlgName = Helper.GetEncryptionAlgName(EncryptionAlgOid);

            try
            {
                if (encryptionAlgName.Equals("RSA"))
                {
                    IBufferedCipher bufferedCipher = CmsEnvelopedHelper.Instance.CreateAsymmetricCipher("RSA/ECB/PKCS1Padding");
                    bufferedCipher.Init(forEncryption: false, key);
                    byte[]     encoding   = bufferedCipher.DoFinal(signature);
                    DigestInfo digestInfo = DerDecode(encoding);
                    if (!digestInfo.AlgorithmID.Algorithm.Equals(digestAlgorithm.Algorithm))
                    {
                        return(false);
                    }
                    if (!IsNull(digestInfo.AlgorithmID.Parameters))
                    {
                        return(false);
                    }
                    byte[] digest2 = digestInfo.GetDigest();
                    return(Arrays.ConstantTimeAreEqual(digest, digest2));
                }
                if (encryptionAlgName.Equals("DSA"))
                {
                    ISigner signer = SignerUtilities.GetSigner("NONEwithDSA");
                    signer.Init(forSigning: false, key);
                    signer.BlockUpdate(digest, 0, digest.Length);
                    return(signer.VerifySignature(signature));
                }
                throw new CmsException("algorithm: " + encryptionAlgName + " not supported in base signatures.");
            }
            catch (SecurityUtilityException ex)
            {
                throw ex;
            }
            catch (GeneralSecurityException ex2)
            {
                throw new CmsException(string.Concat((object)"Exception processing signature: ", (object)ex2), ex2);
            }
            catch (IOException val)
            {
                IOException val2 = val;
                throw new CmsException(string.Concat((object)"Exception decoding signature: ", (object)val2), (global::System.Exception)(object) val2);
            }
        }
        internal static byte[] TripleDESKeyWrapDecrypt(byte[] rgbKey, byte[] rgbEncryptedWrappedKeyData)
        {
            if (rgbEncryptedWrappedKeyData.Length != 32 && rgbEncryptedWrappedKeyData.Length != 40 &&
                rgbEncryptedWrappedKeyData.Length != 48)
            {
                throw new System.Security.Cryptography.CryptographicException(SR.Cryptography_Xml_KW_BadKeySize);
            }

            IBufferedCipher dec1 = null;
            IBufferedCipher dec2 = null;

            try
            {
                dec1 = CipherUtilities.GetCipher("DESEDE/CBC/NOPADDING");
                dec2 = CipherUtilities.GetCipher("DESEDE/CBC/NOPADDING");

                dec1.Init(false, new ParametersWithIV(new DesEdeParameters(rgbKey), s_rgbTripleDES_KW_IV));

                byte[] temp2 = dec1.DoFinal(rgbEncryptedWrappedKeyData);
                Array.Reverse(temp2);
                byte[] rgbIV = new byte[8];
                Buffer.BlockCopy(temp2, 0, rgbIV, 0, 8);
                byte[] temp1 = new byte[temp2.Length - rgbIV.Length];
                Buffer.BlockCopy(temp2, 8, temp1, 0, temp1.Length);

                dec2.Init(false, new ParametersWithIV(new DesEdeParameters(rgbKey), rgbIV));
                byte[] rgbWKCKS = dec2.DoFinal(temp1);

                byte[] rgbWrappedKeyData = new byte[rgbWKCKS.Length - 8];
                Buffer.BlockCopy(rgbWKCKS, 0, rgbWrappedKeyData, 0, rgbWrappedKeyData.Length);
                var    sha    = DigestUtilities.GetDigest("SHA-1");
                byte[] rgbCKS = new byte[sha.GetDigestSize()];
                sha.BlockUpdate(rgbWrappedKeyData, 0, rgbWrappedKeyData.Length);
                sha.DoFinal(rgbCKS, 0);
                for (int index = rgbWrappedKeyData.Length, index1 = 0; index < rgbWKCKS.Length; index++, index1++)
                {
                    if (rgbWKCKS[index] != rgbCKS[index1])
                    {
                        throw new System.Security.Cryptography.CryptographicException(SR.Cryptography_Xml_BadWrappedKeySize);
                    }
                }
                return(rgbWrappedKeyData);
            }
            finally
            {
            }
        }
示例#10
0
        /// <summary>
        /// 用私钥给数据进行RSA加密
        /// </summary>
        /// <param name="xmlPrivateKey"></param>
        /// <param name="strEncryptString"></param>
        /// <returns></returns>
        public static string PrivateKeyEncrypt(string xmlPrivateKey, string strEncryptString)
        {
            RSAHelper rs  = new RSAHelper(RSAType.RSA, Encoding.UTF8, xmlPrivateKey);
            var       xml = rs._privateKeyRsaProvider.ToXmlString(true);

            MAX_ENCRYPT_BLOCK = rs._privateKeyRsaProvider.KeySize / 8 - 11;
            //加载私钥
            RSACryptoServiceProvider privateRsa = new RSACryptoServiceProvider();

            privateRsa.FromXmlString(xml);

            //转换密钥
            AsymmetricCipherKeyPair keyPair = DotNetUtilities.GetKeyPair(privateRsa);
            IBufferedCipher         c       = CipherUtilities.GetCipher("RSA/ECB/PKCS1Padding"); //使用RSA/ECB/PKCS1Padding格式

            c.Init(true, keyPair.Private);                                                       //第一个参数为true表示加密,为false表示解密;第二个参数表示密钥
            byte[] DataToEncrypt = Encoding.UTF8.GetBytes(strEncryptString);                     //获取字节

            byte[] cache;
            int    time     = 0;//次数
            int    inputLen = DataToEncrypt.Length;
            int    offSet   = 0;

            using (MemoryStream outStream = new MemoryStream())
            {
                while (inputLen - offSet > 0)
                {
                    if (inputLen - offSet > MAX_ENCRYPT_BLOCK)
                    {
                        cache = c.DoFinal(DataToEncrypt, offSet, MAX_ENCRYPT_BLOCK);
                    }
                    else
                    {
                        cache = c.DoFinal(DataToEncrypt, offSet, inputLen - offSet);
                    }
                    //写入
                    outStream.Write(cache, 0, cache.Length);

                    time++;
                    offSet = time * MAX_ENCRYPT_BLOCK;
                }
                byte[] resData = outStream.ToArray();

                string strBase64 = Convert.ToBase64String(resData);
                return(strBase64);
            }
        }
示例#11
0
        /// <summary>
        /// RSA解密
        /// </summary>
        /// <param name="content">密文</param>
        /// <param name="rsaKey">公钥</param>
        /// <returns>明文</returns>
        public static string RSADecryByType(string content, string rsaKey, RSAType type)
        {
            try
            {
                MemoryStream bufferStream = new MemoryStream();
                byte[]       bytData      = Convert.FromBase64String(content);
                int          inputLength  = bytData.Length;

                AsymmetricKeyParameter key;
                if (type == RSAType.公钥)
                {
                    key = PublicKeyFactory.CreateKey(Convert.FromBase64String(rsaKey));
                }
                else
                {
                    key = PrivateKeyFactory.CreateKey(Convert.FromBase64String(rsaKey));
                }

                IBufferedCipher cipher = CipherUtilities.GetCipher("RSA/ECB/PKCS1Padding");
                cipher.Init(false, key);
                int    offSet = 0;
                byte[] cache;
                int    i = 0;
                while (inputLength - offSet > 0)
                {
                    if (inputLength - offSet > 128)
                    {
                        cache = cipher.DoFinal(bytData, offSet, 128);
                    }
                    else
                    {
                        cache = cipher.DoFinal(bytData, offSet, inputLength - offSet);
                    }
                    bufferStream.Write(cache, 0, cache.Length);
                    i++;
                    offSet = i * 128;
                }
                byte[] decryptedData = bufferStream.ToArray();
                bufferStream.Close();
                return(Encoding.UTF8.GetString(bufferStream.ToArray()));
            }
            catch (Exception e)
            {
                return(e.Message);
            }
        }
 public CmsReadable GetReadable(KeyParameter sKey)
 {
     //IL_00c5: Expected O, but got Unknown
     //IL_00f4: Expected O, but got Unknown
     try
     {
         cipher = CipherUtilities.GetCipher(algorithm.Algorithm);
         Asn1Object        asn1Object       = algorithm.Parameters?.ToAsn1Object();
         ICipherParameters cipherParameters = sKey;
         if (asn1Object != null && !(asn1Object is Asn1Null))
         {
             cipherParameters = ParameterUtilities.GetCipherParameters(algorithm.Algorithm, cipherParameters, asn1Object);
         }
         else
         {
             string id = algorithm.Algorithm.Id;
             if (id.Equals(CmsEnvelopedGenerator.DesEde3Cbc) || id.Equals("1.3.6.1.4.1.188.7.1.1.2") || id.Equals("1.2.840.113533.7.66.10"))
             {
                 cipherParameters = new ParametersWithIV(cipherParameters, new byte[8]);
             }
         }
         cipher.Init(forEncryption: false, cipherParameters);
     }
     catch (SecurityUtilityException e)
     {
         throw new CmsException("couldn't create cipher.", e);
     }
     catch (InvalidKeyException e2)
     {
         throw new CmsException("key invalid in message.", e2);
     }
     catch (IOException val)
     {
         IOException e3 = val;
         throw new CmsException("error decoding algorithm parameters.", (global::System.Exception)(object) e3);
     }
     try
     {
         return(new CmsProcessableInputStream((Stream)(object)new CipherStream(readable.GetInputStream(), cipher, null)));
     }
     catch (IOException val2)
     {
         IOException e4 = val2;
         throw new CmsException("error reading content.", (global::System.Exception)(object) e4);
     }
 }
示例#13
0
        /// <summary>
        /// Method for decrypting to text
        /// </summary>
        /// <param name="selectedAlgorithim">the algorithim to use, will be cast to enum</param>
        /// <param name="keySize">the key size to use</param>
        /// <param name="secretKey">the secret key for the algorithim</param>
        /// <param name="encrypted">the encrypted bytes</param>
        /// <returns>decrypted text</returns>
        public string DecryptToText(int selectedAlgorithim, int keySize, byte[] secretKey, byte[] iv, byte[] encrypted)
        {
            var algorithim = ((SymmetricBouncyCastleCipher)selectedAlgorithim).ToString().Replace("_", "-");;

            bufferedCipher = CipherUtilities.GetCipher(algorithim);
            if (GetIvSize(selectedAlgorithim) > 0)
            {
                var kp  = new KeyParameter(secretKey);
                var ivp = new ParametersWithIV(kp, iv);
                bufferedCipher.Init(false, ivp);
            }
            else
            {
                bufferedCipher.Init(false, new KeyParameter(secretKey));
            }

            byte[] decrypted = null;
            try
            {
                decrypted = bufferedCipher.DoFinal(encrypted);
            }
            catch (CryptoException exception)
            {
                if (exception.Message == "pad block corrupted")
                {
                    string message = "Decryption failed!\n" +
                                     "The secret key is corrupted.\n" +
                                     "Verify that the same key is used for encrypting and decrypting.";
                    throw new CryptoException(message, exception);
                }
                else if (exception.Message == "last block incomplete in decryption")
                {
                    string message = "Decryption failed!\n" +
                                     "The encryption block length is not complete\n" +
                                     "Verify that the encryption bit length is a multiple of the expected blocksize\n" +
                                     $"Blocksize bit length: {bufferedCipher.GetBlockSize() * 8}\n" +
                                     $"Encryption bit length: {encrypted.Length * 8}";
                    throw new CryptoException(message, exception);
                }
                else
                {
                    throw new CryptoException("Contact developer for help.", exception);
                }
            }
            return(ByteConvert.BytesToUTF8String(decrypted));
        }
示例#14
0
        /// <summary>
        /// Method for encrypting plain bytes
        /// </summary>
        /// <param name="selectedAlgorithim">the algorithim to use, will be cast to enum</param>
        /// <param name="keySize">the key size to use</param>
        /// <param name="secretKey">the secret key for the algorithim</param>
        /// <param name="plain">the plain bytes to encrypt</param>
        /// <returns>the encrypted bytes</returns>
        public byte[] EncryptBytes(int selectedAlgorithim, int keySize, byte[] secretKey, byte[] iv, byte[] plain)
        {
            var algorithim = ((SymmetricBouncyCastleCipher)selectedAlgorithim).ToString().Replace("_", "-");;

            bufferedCipher = CipherUtilities.GetCipher(algorithim);
            if (GetIvSize(selectedAlgorithim) > 0)
            {
                var kp  = new KeyParameter(secretKey);
                var ivp = new ParametersWithIV(kp, iv);
                bufferedCipher.Init(true, ivp);
            }
            else
            {
                bufferedCipher.Init(true, new KeyParameter(secretKey));
            }
            return(bufferedCipher.DoFinal(plain));
        }
        private byte[] Process(byte[] data, double rounds, IProgress<double> percentComplete, IBufferedCipher cipher, bool track = false)
        {
            var byteCompositeKey = data;
            int x = (int)rounds / 100;
            for (var i = 0; i < rounds; ++i)
            {
                if (track && i % x == 0)
                {
                    percentComplete.Report(i / rounds * 100);

                }
                byteCompositeKey = cipher.ProcessBytes(byteCompositeKey);
            }
            percentComplete.Report(100);

            return byteCompositeKey;
        }
示例#16
0
            public CmsReadable GetReadable(KeyParameter sKey)
            {
                try
                {
                    this.cipher = CipherUtilities.GetCipher(this.algorithm.ObjectID);
                    Asn1Encodable     parameters       = this.algorithm.Parameters;
                    Asn1Object        asn1Object       = (parameters == null) ? null : parameters.ToAsn1Object();
                    ICipherParameters cipherParameters = sKey;
                    if (asn1Object != null && !(asn1Object is Asn1Null))
                    {
                        cipherParameters = ParameterUtilities.GetCipherParameters(this.algorithm.ObjectID, cipherParameters, asn1Object);
                    }
                    else
                    {
                        string id = this.algorithm.ObjectID.Id;
                        if (id.Equals(CmsEnvelopedGenerator.DesEde3Cbc) || id.Equals("1.3.6.1.4.1.188.7.1.1.2") || id.Equals("1.2.840.113533.7.66.10"))
                        {
                            cipherParameters = new ParametersWithIV(cipherParameters, new byte[8]);
                        }
                    }
                    this.cipher.Init(false, cipherParameters);
                }
                catch (SecurityUtilityException e)
                {
                    throw new CmsException("couldn't create cipher.", e);
                }
                catch (InvalidKeyException e2)
                {
                    throw new CmsException("key invalid in message.", e2);
                }
                catch (IOException e3)
                {
                    throw new CmsException("error decoding algorithm parameters.", e3);
                }
                CmsReadable result;

                try
                {
                    result = new CmsProcessableInputStream(new CipherStream(this.readable.GetInputStream(), this.cipher, null));
                }
                catch (IOException e4)
                {
                    throw new CmsException("error reading content.", e4);
                }
                return(result);
            }
示例#17
0
        public void decode(Stream outStream)
        {
            IBufferedCipher cipher = CipherUtilities.GetCipher("RSA/None/NoPadding");

            cipher.Init(false, e);
            byte[]         buffer          = new byte[8192];
            BufferedStream bufferedStream  = new BufferedStream(new CipherStream(b, cipher, null), 8192);
            BufferedStream bufferedStream2 = new BufferedStream(outStream, 8192);
            int            count;

            while ((count = bufferedStream.Read(buffer, 0, 8192)) > 0)
            {
                bufferedStream2.Write(buffer, 0, count);
            }
            bufferedStream2.Flush();
            bufferedStream.Close();
        }
示例#18
0
        public string Decrypt(string data)
        {
            byte[]          dataAsBytes = Hex.Decode(data);
            byte[]          keyAsBytes  = System.Text.Encoding.Default.GetBytes(DecryptKey);
            int             inputLength = dataAsBytes.Length;
            IBufferedCipher bf          = CipherUtilities.GetCipher("Blowfish/ECB/PKCS5Padding");
            KeyParameter    key         = new KeyParameter(keyAsBytes);

            bf.Init(false, key);
            byte[] output       = new byte[bf.GetOutputSize(inputLength)];
            int    outputLength = bf.ProcessBytes(dataAsBytes, output, 0);

            bf.DoFinal(output, outputLength);
            string final = System.Text.Encoding.ASCII.GetString(output);

            return(final);
        }
示例#19
0
        public void doTest(
            IAsymmetricCipherKeyPairGenerator g,
            IBufferedCipher c1,
            IBufferedCipher c2)
        {
            //
            // a side
            //
            AsymmetricCipherKeyPair aKeyPair = g.GenerateKeyPair();
            AsymmetricKeyParameter  aPub     = aKeyPair.Public;
            AsymmetricKeyParameter  aPriv    = aKeyPair.Private;

            //
            // b side
            //
            AsymmetricCipherKeyPair bKeyPair = g.GenerateKeyPair();
            AsymmetricKeyParameter  bPub     = bKeyPair.Public;
            AsymmetricKeyParameter  bPriv    = bKeyPair.Private;

            // TODO Put back in
//			//
//			// stream test
//			//
//			IEKeySpec c1Key = new IEKeySpec(aPriv, bPub);
//			IEKeySpec c2Key = new IEKeySpec(bPriv, aPub);
//
//			byte[] d = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
//			byte[] e = new byte[] { 8, 7, 6, 5, 4, 3, 2, 1 };
//
//			IESParameterSpec param = new IESParameterSpec(d, e, 128);
//
//			c1.Init(true, c1Key, param);
//
//			c2.Init(false, c2Key, param);
//
//			byte[] message = Hex.Decode("1234567890abcdef");
//
//			byte[] out1 = c1.DoFinal(message, 0, message.Length);
//
//			byte[] out2 = c2.DoFinal(out1, 0, out1.Length);
//
//			if (!AreEqual(out2, message))
//			{
//				Fail("stream cipher test failed");
//			}
        }
示例#20
0
        /// <summary>
        /// 私钥加密 .Net平台默认是使用公钥进行加密,私钥进行解密。私钥加密需要自己实现或者使用第三方dll
        /// </summary>
        /// <param name="data"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static byte[] encryptByPrivateKey(String data, String key)
        {
            String priKey        = key.Trim();
            String xmlPrivateKey = RSAPrivateKeyJava2DotNet(priKey);
            //加载私钥
            RSACryptoServiceProvider privateRsa = new RSACryptoServiceProvider();

            privateRsa.FromXmlString(xmlPrivateKey);
            //转换密钥
            AsymmetricCipherKeyPair keyPair = DotNetUtilities.GetKeyPair(privateRsa);
            IBufferedCipher         c       = CipherUtilities.GetCipher("RSA/ECB/PKCS1Padding"); // 参数与Java中加密解密的参数一致

            c.Init(true, keyPair.Private);                                                       //第一个参数为true表示加密,为false表示解密;第二个参数表示密钥
            byte[] DataToEncrypt = Encoding.UTF8.GetBytes(data);
            byte[] outBytes      = c.DoFinal(DataToEncrypt);                                     //加密
            return(outBytes);
        }
示例#21
0
        internal static byte[] TripleDESKeyWrapEncrypt(byte[] rgbKey, byte[] rgbWrappedKeyData)
        {
            byte[] rgbCKS;

            var sha = DigestUtilities.GetDigest("SHA-1");

            // checksum the key
            rgbCKS = new byte[sha.GetDigestSize()];
            sha.BlockUpdate(rgbWrappedKeyData, 0, rgbWrappedKeyData.Length);
            sha.DoFinal(rgbCKS, 0);

            // generate a random IV
            byte[]       rgbIV = new byte[8];
            SecureRandom rng   = new SecureRandom();

            rng.NextBytes(rgbIV);

            // rgbWKCS = rgbWrappedKeyData | (first 8 bytes of the hash)
            byte[]          rgbWKCKS = new byte[rgbWrappedKeyData.Length + 8];
            IBufferedCipher enc1     = null;
            IBufferedCipher enc2     = null;

            try
            {
                // Don't add padding, use CBC mode: for example, a 192 bits key will yield 40 bytes of encrypted data
                enc1 = CipherUtilities.GetCipher("DESEDE/CBC/NOPADDING");
                enc2 = CipherUtilities.GetCipher("DESEDE/CBC/NOPADDING");
                enc1.Init(true, new ParametersWithIV(new DesEdeParameters(rgbKey), rgbIV));
                enc2.Init(true, new ParametersWithIV(new DesEdeParameters(rgbKey), s_rgbTripleDES_KW_IV));

                Buffer.BlockCopy(rgbWrappedKeyData, 0, rgbWKCKS, 0, rgbWrappedKeyData.Length);
                Buffer.BlockCopy(rgbCKS, 0, rgbWKCKS, rgbWrappedKeyData.Length, 8);
                byte[] temp1 = enc1.DoFinal(rgbWKCKS);
                byte[] temp2 = new byte[rgbIV.Length + temp1.Length];
                Buffer.BlockCopy(rgbIV, 0, temp2, 0, rgbIV.Length);
                Buffer.BlockCopy(temp1, 0, temp2, rgbIV.Length, temp1.Length);
                // temp2 = REV (rgbIV | E_k(rgbWrappedKeyData | rgbCKS))
                Array.Reverse(temp2);

                return(enc2.DoFinal(temp2));
            }
            finally
            {
            }
        }
示例#22
0
        // Encrypts the given element with the certificate specified. The certificate is added as
        // an X509Data KeyInfo to an EncryptedKey (AES session key) generated randomly.
        public EncryptedData Encrypt(XmlElement inputElement, X509Certificate certificate)
        {
            if (inputElement == null)
            {
                throw new ArgumentNullException(nameof(inputElement));
            }
            if (certificate == null)
            {
                throw new ArgumentNullException(nameof(certificate));
            }

            AsymmetricKeyParameter rsaPublicKey = certificate.GetPublicKey();

            if (rsaPublicKey == null || !(rsaPublicKey is RsaKeyParameters))
            {
                throw new NotSupportedException(SR.NotSupported_KeyAlgorithm);
            }

            // Create the EncryptedData object, using an AES-256 session key by default.
            EncryptedData ed = new EncryptedData();

            ed.Type             = EncryptedXml.XmlEncElementUrl;
            ed.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncAES256Url);

            // Include the certificate in the EncryptedKey KeyInfo.
            EncryptedKey ek = new EncryptedKey();

            ek.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncRSA15Url);
            ek.KeyInfo.AddClause(new KeyInfoX509Data(certificate));

            // Create a random AES session key and encrypt it with the public key associated with the certificate.
            IBufferedCipher  rijn     = CipherUtilities.GetCipher("RIJNDAEL/CBC/PKCS7");
            KeyParameter     keyParam = new KeyParameter(Utils.GenerateRandomBlock(rijn.GetBlockSize()));
            ParametersWithIV rijnKey  = new ParametersWithIV(keyParam, Utils.GenerateRandomBlock(rijn.GetBlockSize()));

            ek.CipherData.CipherValue = EncryptedXml.EncryptKey(keyParam.GetKey(), (RsaKeyParameters)rsaPublicKey, false);

            // Encrypt the input element with the random session key that we've created above.
            KeyInfoEncryptedKey kek = new KeyInfoEncryptedKey(ek);

            ed.KeyInfo.AddClause(kek);
            ed.CipherData.CipherValue = EncryptData(inputElement, rijnKey, false);

            return(ed);
        }
        internal CmsTypedStream GetContentFromSessionKey(
            KeyParameter sKey)
        {
            try
            {
                IBufferedCipher cipher = CipherUtilities.GetCipher(_encAlg.ObjectID);

                Asn1Encodable asn1Enc    = _encAlg.Parameters;
                Asn1Object    asn1Params = asn1Enc == null ? null : asn1Enc.ToAsn1Object();

                ICipherParameters cipherParameters = sKey;

                if (asn1Params != null && !(asn1Params is Asn1Null))
                {
                    cipherParameters = ParameterUtilities.GetCipherParameters(
                        _encAlg.ObjectID, cipherParameters, asn1Params);
                }
                else
                {
                    string alg = _encAlg.ObjectID.Id;
                    if (alg.Equals(CmsEnvelopedDataGenerator.DesEde3Cbc) ||
                        alg.Equals(CmsEnvelopedDataGenerator.IdeaCbc) ||
                        alg.Equals(CmsEnvelopedDataGenerator.Cast5Cbc))
                    {
                        cipherParameters = new ParametersWithIV(cipherParameters, new byte[8]);
                    }
                }

                cipher.Init(false, cipherParameters);

                return(new CmsTypedStream(new CipherStream(_data, cipher, null)));
            }
            catch (SecurityUtilityException e)
            {
                throw new CmsException("couldn't create cipher.", e);
            }
            catch (InvalidKeyException e)
            {
                throw new CmsException("key invalid in message.", e);
            }
            catch (IOException e)
            {
                throw new CmsException("error decoding algorithm parameters.", e);
            }
        }
示例#24
0
        public static string Encrypt(string text, string key)
        {
            byte[] output = null;

            KeyParameter    keyparam = ParameterUtilities.CreateKeyParameter("DES", GetBytesFromString(key));
            IBufferedCipher cipher   = CipherUtilities.GetCipher("DES/ECB/ISO7816_4PADDING");

            cipher.Init(true, keyparam);
            try
            {
                output = cipher.DoFinal(GetBytesFromString(text));
                return(GetStringFromByteArray(output));
            }
            catch (System.Exception ex)
            {
                throw new CryptoException("Invalid Data");
            }
        }
示例#25
0
        public CipherStream(
            Stream stream,
            IBufferedCipher readCipher,
            IBufferedCipher writeCipher)
        {
            this.stream = stream;

            if (readCipher != null)
            {
                this.inCipher = readCipher;
                mInBuf        = null;
            }

            if (writeCipher != null)
            {
                this.outCipher = writeCipher;
            }
        }
示例#26
0
        private static byte[] CryptPbeData(
            bool				forEncryption,
            AlgorithmIdentifier	algId,
            char[]				password,
            bool				wrongPkcs12Zero,
            byte[]				data)
        {
            IBufferedCipher cipher = PbeUtilities.CreateEngine(algId.Algorithm) as IBufferedCipher;

            if (cipher == null)
                throw new Exception("Unknown encryption algorithm: " + algId.Algorithm);

            Pkcs12PbeParams pbeParameters = Pkcs12PbeParams.GetInstance(algId.Parameters);
            ICipherParameters cipherParams = PbeUtilities.GenerateCipherParameters(
                algId.Algorithm, password, wrongPkcs12Zero, pbeParameters);
            cipher.Init(forEncryption, cipherParams);
            return cipher.DoFinal(data);
        }
示例#27
0
        public byte[] EnDecrypt(bool forEncrypt, byte[] inBytes)
        {
            cipher = CipherUtilities.GetCipher(algorithm);
            cipher.Init(forEncrypt, key);
            int outBytesSize = cipher.GetOutputSize(inBytes.Length);
            byte[] outBytes = new byte[outBytesSize];
            int outLentgh;

            outLentgh = cipher.ProcessBytes(inBytes, 0, inBytes.Length, outBytes, 0);
            outLentgh += cipher.DoFinal(outBytes, outLentgh);

            if (outLentgh != outBytesSize)
            {
                return null;
            }

            return outBytes;
        }
示例#28
0
        /*加密核心
         * Src加密内容
         *
         * PFXorCER  证书
         *
         * Mode  加密或解密  true  OR  false
         */
        private static byte[] RSAEDCore(byte[] Src, AsymmetricKeyParameter PFXorCER, bool Mode)
        {
            IAsymmetricBlockCipher engine = new RsaEngine();
            IBufferedCipher        Cipher = CipherUtilities.GetCipher("RSA/ECB/PKCS1Padding"); //加密标准

            Cipher.Init(Mode, PFXorCER);                                                       //初始加密程序

            byte[] EDString = null;

            int blockSize = Cipher.GetBlockSize();

            for (int i = 0; i < Src.Length; i += blockSize)
            {
                byte[] outBytes = Cipher.DoFinal(Subarray(Src, i, i + blockSize));//数据加密
                EDString = AddAll(EDString, outBytes);
            }
            return(EDString);
        }
示例#29
0
        public static EncryptedPrivateKeyInfo CreateEncryptedPrivateKeyInfo(string algorithm, char[] passPhrase, byte[] salt, int iterationCount, PrivateKeyInfo keyInfo)
        {
            IBufferedCipher bufferedCipher = PbeUtilities.CreateEngine(algorithm) as IBufferedCipher;

            if (bufferedCipher == null)
            {
                throw new global::System.Exception("Unknown encryption algorithm: " + algorithm);
            }
            Asn1Encodable     asn1Encodable = PbeUtilities.GenerateAlgorithmParameters(algorithm, salt, iterationCount);
            ICipherParameters parameters    = PbeUtilities.GenerateCipherParameters(algorithm, passPhrase, asn1Encodable);

            bufferedCipher.Init(forEncryption: true, parameters);
            byte[] encoding = bufferedCipher.DoFinal(keyInfo.GetEncoded());
            DerObjectIdentifier objectIdentifier = PbeUtilities.GetObjectIdentifier(algorithm);
            AlgorithmIdentifier algId            = new AlgorithmIdentifier(objectIdentifier, asn1Encodable);

            return(new EncryptedPrivateKeyInfo(algId, encoding));
        }
示例#30
0
        public CipherStream(
            Stream stream,
            IBufferedCipher readCipher,
            IBufferedCipher writeCipher)
        {
            this.stream = stream;

            if (readCipher != null)
            {
                this.inCipher = readCipher;
                mInBuf = null;
            }

            if (writeCipher != null)
            {
                this.outCipher = writeCipher;
            }
        }
示例#31
0
        private void doOidTest()
        {
            string[] oids =
            {
                CryptoProObjectIdentifiers.GostR28147Cbc.Id,
            };

            string[] names =
            {
                "GOST28147/CBC/PKCS7Padding"
            };

            try
            {
                byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };
//				IvParameterSpec ivSpec = new IvParameterSpec(new byte[8]);
                byte[] iv = new byte[8];

                for (int i = 0; i != oids.Length; i++)
                {
                    IBufferedCipher c1 = CipherUtilities.GetCipher(oids[i]);
                    IBufferedCipher c2 = CipherUtilities.GetCipher(names[i]);

//					KeyGenerator kg = KeyGenerator.getInstance(oids[i]);
//					SecretKey k = kg.generateKey();
                    CipherKeyGenerator kg = GeneratorUtilities.GetKeyGenerator(oids[i]);
                    KeyParameter       k  = ParameterUtilities.CreateKeyParameter(oids[i], kg.GenerateKey());

                    c1.Init(true, new ParametersWithIV(k, iv));
                    c2.Init(false, new ParametersWithIV(k, iv));

                    byte[] result = c2.DoFinal(c1.DoFinal(data));

                    if (!AreEqual(data, result))
                    {
                        Fail("failed OID test");
                    }
                }
            }
            catch (Exception ex)
            {
                Fail("failed exception " + ex.ToString(), ex);
            }
        }
示例#32
0
        private static byte[] DoCryptStuff(byte[] data, IKey key, CipherDirection direction, CipherMode cipherMode, byte[] iv)
        {
            byte[] result;
            String transformation = key.GetAlgorithm();

            if (key.GetAlgorithm().StartsWith(ALG_DES))
            {
                transformation += "/" + ModetoString(cipherMode) + "/" + DES_NO_PADDING;
            }

            ICipherParameters keyparam = new KeyParameter(key.GetEncoded());
            IBufferedCipher   cipher   = CipherUtilities.GetCipher(transformation);

            if (cipherMode != CipherMode.ECB)
            {
                keyparam = new ParametersWithIV(keyparam, iv);
            }

            byte[] output = new byte[cipher.GetOutputSize(data.Length)];
            cipher.Init(direction == CipherDirection.ENCRYPT_MODE ? true : false, keyparam);
            result = cipher.DoFinal(data);

            if (cipherMode != CipherMode.ECB)
            {
                Array.Copy(result, result.Length - 8, iv, 0, iv.Length);
            }

            //AlgorithmParameterSpec aps = null;
            //try
            //{
            //    Cipher c1 = Cipher.getInstance(transformation, provider.getName());
            //    if (cipherMode != CipherMode.ECB)
            //        aps = new IvParameterSpec(iv);
            //    c1.init(direction, key, aps);
            //    result = c1.doFinal(data);
            //    if (cipherMode != CipherMode.ECB)
            //        System.arraycopy(result, result.length - 8, iv, 0, iv.length);
            //}
            //catch (Exception e)
            //{
            //    throw e;
            //}
            return(result);
        }
示例#33
0
        public static byte[] AsymmetricDecrypt(byte[] data, ref AsymmetricCipherKeyPair keypair)
        {
            //create the key agreement
            ECDHBasicAgreement ag = new ECDHBasicAgreement();

            ag.Init(keypair.Private);

            //calculate the shared secret key
            BigInteger a = ag.CalculateAgreement(keypair.Public);

            byte[] secret = a.ToByteArray();

            //derive the symmetric encryption key
            ECDHKekGenerator topkek = new ECDHKekGenerator(DigestUtilities.GetDigest("SHA256"));

            topkek.Init(new DHKdfParameters(NistObjectIdentifiers.Aes, secret.Length, secret));
            byte[] symKey = new byte[DigestUtilities.GetDigest("SHA256").GetDigestSize()];
            topkek.GenerateBytes(symKey, 0, symKey.Length);

            //decrypt the data
            KeyParameter    parm   = ParameterUtilities.CreateKeyParameter("DES", symKey);
            IBufferedCipher cipher = CipherUtilities.GetCipher("DES/ECB/ISO7816_4PADDING");

            cipher.Init(false, parm);
            byte[] ret = null;
            try
            {
                ret = cipher.DoFinal(data);
            }
            catch (Exception e)
            {
                if (e != null)
                {
                    return(null);
                }
            }

            //erase the keys
            Eraser.SecureErase(secret);
            Eraser.SecureErase(symKey);

            return(ret);
        }
示例#34
0
        /// <summary>
        /// 公钥解密
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dataToDecrypt">待解密数据</param>
        /// <param name="publicKey">公钥</param>
        /// <returns></returns>
        public static T DecryptWithPublicKeyAndDeserialize <T>(string dataToDecrypt, string publicKey)
        {
            byte[] bytesToDecrypt = Convert.FromBase64String(dataToDecrypt);

            AsymmetricKeyParameter keyParameter;

            using (StringReader stringReader = new StringReader(publicKey))
            {
                PemReader pemReader = new PemReader(stringReader);
                keyParameter = (AsymmetricKeyParameter)pemReader.ReadObject();
            }
            IBufferedCipher cipher = CipherUtilities.GetCipher("RSA/ECB/PKCS1Padding");

            cipher.Init(false, keyParameter);
            byte[] decipheredBytes = cipher.DoFinal(bytesToDecrypt);
            string decipheredText  = Encoding.UTF8.GetString(decipheredBytes);

            return(JsonConvert.DeserializeObject <T>(decipheredText));
        }
示例#35
0
        /// <summary>
        /// RSA加密
        /// </summary>
        /// <param name="publickey"></param>
        /// <param name="content"></param>
        /// <returns></returns>
        //public static string RSAEncrypt(string publickey, string content, string exponent = "RSA")
        //{
        //    //try
        //    //{
        //    //publickey = string.Format(@"<RSAKeyValue><Modulus>{0}</Modulus><Exponent>{1}</Exponent></RSAKeyValue>", publickey, exponent);
        //    RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
        //    //创建RSA参数对象并加入参数
        //    RSAParameters RSAKeyInfo = new RSAParameters();
        //    RSAKeyInfo.Modulus = Encoding.UTF8.GetBytes(publickey);
        //    RSAKeyInfo.Exponent = new byte[] { 01, 00, 01 };
        //    //RSAKeyInfo.Exponent = Encoding.UTF8.GetBytes(exponent);
        //    //RSAKeyInfo.Modulus = FromHex(publickey);
        //    //RSAKeyInfo.Exponent = Encoding.UTF8.GetBytes(exponent);
        //    //将参数转载如RSA对象中
        //    RSA.ImportParameters(RSAKeyInfo);
        //    //RSA.FromXmlString(publickey);
        //    byte[] cipherbytes = RSA.Encrypt(Encoding.UTF8.GetBytes(content), false);

        //    return Convert.ToBase64String(cipherbytes);
        //    //}
        //    //catch (Exception e)
        //    //{

        //    //    return e.Message;
        //    //}
        //}

        public static string RSAEncrypt(string publickey, string content, string exponent = "RSA")
        {
            try
            {
                RSACryptoServiceProvider rsa      = new RSACryptoServiceProvider();
                byte[] publicKeyBytes             = Convert.FromBase64String(publickey);
                AsymmetricKeyParameter privateKey = PublicKeyFactory.CreateKey(publicKeyBytes);
                IBufferedCipher        c          = CipherUtilities.GetCipher("RSA/None/PKCS1Padding");
                //加密
                c.Init(true, privateKey);
                byte[] byteData = Encoding.UTF8.GetBytes(content);
                byteData = c.DoFinal(byteData, 0, byteData.Length);
                return(Convert.ToBase64String(byteData));
            }
            catch (Exception e)
            {
                return(e.Message);
            }
        }
示例#36
0
        /// <summary>
        /// 用公钥解密
        /// </summary>
        /// <param name="data"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static byte[] decryptByPublicKey(String data, String key)
        {
            String pubKey       = key.Trim();
            String xmlPublicKey = RSAPublicKeyJava2DotNet(pubKey);

            RSACryptoServiceProvider publicRsa = new RSACryptoServiceProvider();

            publicRsa.FromXmlString(xmlPublicKey);

            AsymmetricKeyParameter keyPair = DotNetUtilities.GetRsaPublicKey(publicRsa);
            //转换密钥
            // AsymmetricCipherKeyPair keyPair = DotNetUtilities.GetRsaKeyPair(publicRsa);
            IBufferedCipher c = CipherUtilities.GetCipher("RSA/ECB/PKCS1Padding"); // 参数与Java中加密解密的参数一致

            c.Init(false, keyPair);                                                //第一个参数为true表示加密,为false表示解密;第二个参数表示密钥
            byte[] DataToEncrypt = Convert.FromBase64String(data);
            byte[] outBytes      = c.DoFinal(DataToEncrypt);                       //解密
            return(outBytes);
        }
示例#37
0
        public static string Decrypt(string ciphertext, string key, string note = "")
        {
            byte[] output = null;

            KeyParameter    keyparam = ParameterUtilities.CreateKeyParameter("DES", GetBytesFromString(key));
            IBufferedCipher cipher   = CipherUtilities.GetCipher("DES/ECB/ISO7816_4PADDING");

            cipher.Init(false, keyparam);
            try
            {
                output = cipher.DoFinal(GetBytesFromString(ciphertext));
                return(GetStringFromByteArray(output));
            }
            catch (System.Exception ex)
            {
                CConsole.Red("!!! Failed to Decrypt Message !!!");
                return(null);
            }
        }
示例#38
0
        /*
            * This method performs all the decryption and writes
            * the plain text to the buffered output stream created
            * previously.
            */
        static public string Decode(string encyStr, string key, string iv)
        {
            /* 
                    * Setup the DES cipher engine, with PKCS5PADDING
                    * in CBC mode.
                    */
            if (cipher == null)
            {
                cipher = CipherUtilities.GetCipher("DES/CBC/PKCS5PADDING");
            }

            string result = null;
            byte[] key_ = Encoding.UTF8.GetBytes(key.Substring(0, 8));
            byte[] iv_ = Encoding.UTF8.GetBytes(iv.Substring(0, 8));

            cipher.Init(false, new ParametersWithIV(new DesParameters(key_), iv_));

            try
            {
                int outL = 0;
                byte[] outblock = null;
                string decodeUrl = Uri.UnescapeDataString(encyStr);
                byte[] inblock = Convert.FromBase64String(decodeUrl);
                outblock = new byte[cipher.GetOutputSize(inblock.Length)];

                outL = cipher.ProcessBytes(inblock, 0, inblock.Length, outblock, 0);
               /*
                        * Before we write anything out, we need to make sure
                        * that we've got something to write out. 
                        */
                if (outL > 0)
                {
                    cipher.DoFinal(outblock, outL);
                }
                result = Encoding.UTF8.GetString(outblock, 0, outblock.Length);
            }
            catch (IOException) { }

            return result;
        }
示例#39
0
 /// <summary>
 /// Releases the unmanaged resources used by the <see cref="T:System.IO.Stream"/> and optionally releases the managed resources.
 /// </summary>
 /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
 protected override void Dispose(bool disposing)
 {
     if (disposing)
     {
     }
     _cipher.Reset();
     _cipher = null;
     _output.Flush();
     _output = null;
     base.Dispose(disposing);
 }
        public void doDefTest(
			IAsymmetricCipherKeyPairGenerator	g,
			IBufferedCipher						c1,
			IBufferedCipher						c2)
        {
            //
            // a side
            //
            IAsymmetricCipherKeyPair aKeyPair = g.GenerateKeyPair();
            IAsymmetricKeyParameter aPub = aKeyPair.Public;
            IAsymmetricKeyParameter aPriv = aKeyPair.Private;

            //
            // b side
            //
            IAsymmetricCipherKeyPair bKeyPair = g.GenerateKeyPair();
            IAsymmetricKeyParameter bPub = bKeyPair.Public;
            IAsymmetricKeyParameter bPriv = bKeyPair.Private;

            // TODO Put back in
            //			//
            //			// stream test
            //			//
            //			IEKeySpec c1Key = new IEKeySpec(aPriv, bPub);
            //			IEKeySpec c2Key = new IEKeySpec(bPriv, aPub);
            //
            //			c1.Init(true, c1Key);
            //
            //			AlgorithmParameters param = c1.getParameters();
            //
            //			c2.Init(false, c2Key, param);
            //
            //			byte[] message = Hex.Decode("1234567890abcdef");
            //
            //			byte[] out1 = c1.DoFinal(message, 0, message.Length);
            //
            //			byte[] out2 = c2.DoFinal(out1, 0, out1.Length);
            //
            //			if (!AreEqual(out2, message))
            //			{
            //				Fail("stream cipher test failed");
            //			}
            //
            //			//
            //			// int DoFinal
            //			//
            //			int len1 = c1.DoFinal(message, 0, message.Length, out1, 0);
            //
            //			if (len1 != out1.Length)
            //			{
            //				Fail("encryption length wrong");
            //			}
            //
            //			int len2 = c2.DoFinal(out1, 0, out1.Length, out2, 0);
            //
            //			if (len2 != out2.Length)
            //			{
            //				Fail("decryption length wrong");
            //			}
            //
            //			if (!AreEqual(out2, message))
            //			{
            //				Fail("stream cipher test failed");
            //			}
            //
            //			//
            //			// int DoFinal with update
            //			//
            //			len1 = c1.ProcessBytes(message, 0, 2, out1, 0);
            //
            //			len1 += c1.DoFinal(message, 2, message.Length - 2, out1, len1);
            //
            //			if (len1 != out1.Length)
            //			{
            //				Fail("update encryption length wrong");
            //			}
            //
            //			len2 = c2.ProcessBytes(out1, 0, 2, out2, 0);
            //
            //			len2 += c2.DoFinal(out1, 2, out1.Length - 2, out2, len2);
            //
            //			if (len2 != out2.Length)
            //			{
            //				Fail("update decryption length wrong");
            //			}
            //
            //			if (!AreEqual(out2, message))
            //			{
            //				Fail("update stream cipher test failed");
            //			}
        }
 private void ProcessSymmetricKeyDataForRsa(IBufferedCipher cipher, IList<IBigInteger> symmetricKeyData)
 {
     cipher.ProcessBytes(symmetricKeyData[0].ToByteArrayUnsigned());
 }
		/// <summary>
		/// <p>
		/// If buffer is non null stream assumed to be partial, otherwise the length will be used
		/// to output a fixed length packet.
		/// </p>
		/// <p>
		/// The stream created can be closed off by either calling Close()
		/// on the stream or Close() on the generator. Closing the returned
		/// stream does not close off the Stream parameter <c>outStr</c>.
		/// </p>
		/// </summary>
        private Stream Open(
            Stream	outStr,
            long	length,
            byte[]	buffer)
        {
			if (cOut != null)
				throw new InvalidOperationException("generator already in open state");
			if (methods.Count == 0)
				throw new InvalidOperationException("No encryption methods specified");
			if (outStr == null)
				throw new ArgumentNullException("outStr");

			pOut = new BcpgOutputStream(outStr);

			KeyParameter key;

			if (methods.Count == 1)
            {
                if (methods[0] is PbeMethod)
                {
                    PbeMethod m = (PbeMethod)methods[0];

					key = m.GetKey();
                }
                else
                {
                    key = PgpUtilities.MakeRandomKey(defAlgorithm, rand);

					byte[] sessionInfo = CreateSessionInfo(defAlgorithm, key);
                    PubMethod m = (PubMethod)methods[0];

                    try
                    {
                        m.AddSessionInfo(sessionInfo, rand);
                    }
                    catch (Exception e)
                    {
                        throw new PgpException("exception encrypting session key", e);
                    }
                }

				pOut.WritePacket((ContainedPacket)methods[0]);
            }
            else // multiple methods
            {
                key = PgpUtilities.MakeRandomKey(defAlgorithm, rand);
				byte[] sessionInfo = CreateSessionInfo(defAlgorithm, key);

				for (int i = 0; i != methods.Count; i++)
                {
                    EncMethod m = (EncMethod)methods[i];

                    try
                    {
                        m.AddSessionInfo(sessionInfo, rand);
                    }
                    catch (Exception e)
                    {
                        throw new PgpException("exception encrypting session key", e);
                    }

                    pOut.WritePacket(m);
                }
            }

            string cName = PgpUtilities.GetSymmetricCipherName(defAlgorithm);
			if (cName == null)
            {
                throw new PgpException("null cipher specified");
            }

			try
            {
                if (withIntegrityPacket)
                {
                    cName += "/CFB/NoPadding";
                }
                else
                {
                    cName += "/OpenPGPCFB/NoPadding";
                }

                c = CipherUtilities.GetCipher(cName);

				// TODO Confirm the IV should be all zero bytes (not inLineIv - see below)
				byte[] iv = new byte[c.GetBlockSize()];
                c.Init(true, new ParametersWithRandom(new ParametersWithIV(key, iv), rand));

                if (buffer == null)
                {
                    //
                    // we have to Add block size + 2 for the Generated IV and + 1 + 22 if integrity protected
                    //
                    if (withIntegrityPacket)
                    {
                        pOut = new BcpgOutputStream(outStr, PacketTag.SymmetricEncryptedIntegrityProtected, length + c.GetBlockSize() + 2 + 1 + 22);
                        pOut.WriteByte(1);        // version number
                    }
                    else
                    {
                        pOut = new BcpgOutputStream(outStr, PacketTag.SymmetricKeyEncrypted, length + c.GetBlockSize() + 2, oldFormat);
                    }
                }
                else
                {
                    if (withIntegrityPacket)
                    {
                        pOut = new BcpgOutputStream(outStr, PacketTag.SymmetricEncryptedIntegrityProtected, buffer);
                        pOut.WriteByte(1);        // version number
                    }
                    else
                    {
                        pOut = new BcpgOutputStream(outStr, PacketTag.SymmetricKeyEncrypted, buffer);
                    }
                }

				int blockSize = c.GetBlockSize();
				byte[] inLineIv = new byte[blockSize + 2];
                rand.NextBytes(inLineIv, 0, blockSize);
				Array.Copy(inLineIv, inLineIv.Length - 4, inLineIv, inLineIv.Length - 2, 2);

				Stream myOut = cOut = new CipherStream(pOut, null, c);

				if (withIntegrityPacket)
                {
					string digestName = PgpUtilities.GetDigestName(HashAlgorithmTag.Sha1);
					IDigest digest = DigestUtilities.GetDigest(digestName);
					myOut = digestOut = new DigestStream(myOut, null, digest);
                }

				myOut.Write(inLineIv, 0, inLineIv.Length);

				return new WrappedGeneratorStream(this, myOut);
            }
            catch (Exception e)
            {
                throw new PgpException("Exception creating cipher", e);
            }
        }
示例#43
0
        public void init(String srcFile, String dstFile, String opMode, int segmentSize,
            Int64 srcFileOffset = 0, Int64 dstFileOffset = 0)
        {
            //System.Console.WriteLine("cipherMode: {0}, segment: {1}, srcOffset: {2}, dstOffset: {3}",
            //    opMode, segmentSize, srcFileOffset, dstFileOffset);

            //@todo: walidacja opMode z segmentSize
            //@todo: try..catch wyrzucający System.ArgumentException
            // w OFB i CFB dł. podbloku musi być wielokrotnością 8 b, np. OFB8, OFB16

            mOpMode = opMode;
            mSegmentSize = segmentSize >> 3; // divide by 8, i.e. [b] => [B]
            mBufferSize = BUFFER_SIZE - (BUFFER_SIZE % mSegmentSize); // size of the single chunk of data read from disk
                                                                      // multiplicity of segment size

            //
            mSrcFileOffset = srcFileOffset;
            mDstFileOffset = dstFileOffset;

            // w trybie "in memory" nie potrzeba podawać plików
            if (srcFile != null && dstFile != null)
            {
                mSrcFile = File.OpenRead(srcFile);
                mDstFile = (Encryption
                    ? new FileStream(dstFile, FileMode.OpenOrCreate | FileMode.Append, FileAccess.Write)
                    : File.Create(dstFile));

                mSrcFile.Seek(mSrcFileOffset, SeekOrigin.Begin);
                mDstFile.Seek(mDstFileOffset, SeekOrigin.Begin);
            }

            // inicjalizacja algorytmu Serpent
            if (mOpMode == "OFB" || mOpMode == "CFB")
            {
                mOpMode += segmentSize.ToString();
            }

            if (mOpMode != "ECB")
            {
                var cipherId = "Serpent/" + mOpMode + "/NoPadding";
                //System.Console.WriteLine(cipherId);
                mSerpent = CipherUtilities.GetCipher(cipherId);
                mSerpent.Init(Encryption, combineKeyWithIV(mSessionKey, mIV));
            }
            else
            {
                mSerpent = new BufferedBlockCipher(new SerpentEngine());
                mSerpent.Init(Encryption, mSessionKey);
            }

            System.Console.WriteLine("serpent init");
        }
 private static void ProcessEncodedMpi(IBufferedCipher cipher, int size, byte[] mpiEnc)
 {
     if (mpiEnc.Length - 2 > size)  // leading Zero? Shouldn't happen but...
     {
         cipher.ProcessBytes(mpiEnc, 3, mpiEnc.Length - 3);
     }
     else
     {
         byte[] tmp = new byte[size];
         Array.Copy(mpiEnc, 2, tmp, tmp.Length - (mpiEnc.Length - 2), mpiEnc.Length - 2);
         cipher.ProcessBytes(tmp, 0, tmp.Length);
     }
 }
示例#45
0
 public static void Init()
 {
     publicKey = (RsaKeyParameters)PublicKeyFactory.CreateKey(Convert.FromBase64String("MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAM5U06JAbYWdRBrnMdE2bEuDmWgUav7xNKm7i8s1Uy/fvpvfxLeoWowLGIBKz0kDLIvhuLV8Lv4XV0+aXdl2j4kCAwEAAQ=="));
     cipher = CipherUtilities.GetCipher("RSA/ECB/PKCS1Padding");
     cipher.Init(true, publicKey);
 }
示例#46
0
		/// <summary>
		/// Encrypt or decrypt a stream and send the result to an output stream.
		/// </summary>
		/// <param name="instream">The input stream to be encrypted.</param>
		/// <param name="outstream">The encrypted stream.</param>
		/// <param name="cipher">A PaddedBufferedBlockCipher configured to encrypt or decrypt.</param>
		private void DoCipher(Stream instream, Stream outstream, IBufferedCipher cipher)
		{
			byte[] buffer = new byte[1024];
			int blocksize = buffer.Length;
			while((blocksize = instream.Read(buffer, 0, blocksize)) != 0)
			{
				byte[] enc = cipher.ProcessBytes(buffer, 0, blocksize);
				outstream.Write(enc, 0, enc.Length);
			}
			byte[] enc2 = cipher.DoFinal();
			outstream.Write(enc2, 0, enc2.Length);
			outstream.Flush();
		}
示例#47
0
 public BufferedCipherWrapper(
     IBufferedCipher cipher)
 {
     this.cipher = cipher;
 }
        public void doTest(
			IAsymmetricCipherKeyPairGenerator	g,
			IBufferedCipher						c1,
			IBufferedCipher						c2)
        {
            //
            // a side
            //
            IAsymmetricCipherKeyPair aKeyPair = g.GenerateKeyPair();
            IAsymmetricKeyParameter aPub = aKeyPair.Public;
            IAsymmetricKeyParameter  aPriv = aKeyPair.Private;

            //
            // b side
            //
            IAsymmetricCipherKeyPair bKeyPair = g.GenerateKeyPair();
            IAsymmetricKeyParameter bPub = bKeyPair.Public;
            IAsymmetricKeyParameter bPriv = bKeyPair.Private;

            // TODO Put back in
            //			//
            //			// stream test
            //			//
            //			IEKeySpec c1Key = new IEKeySpec(aPriv, bPub);
            //			IEKeySpec c2Key = new IEKeySpec(bPriv, aPub);
            //
            //			byte[] d = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
            //			byte[] e = new byte[] { 8, 7, 6, 5, 4, 3, 2, 1 };
            //
            //			IESParameterSpec param = new IESParameterSpec(d, e, 128);
            //
            //			c1.Init(true, c1Key, param);
            //
            //			c2.Init(false, c2Key, param);
            //
            //			byte[] message = Hex.Decode("1234567890abcdef");
            //
            //			byte[] out1 = c1.DoFinal(message, 0, message.Length);
            //
            //			byte[] out2 = c2.DoFinal(out1, 0, out1.Length);
            //
            //			if (!AreEqual(out2, message))
            //			{
            //				Fail("stream cipher test failed");
            //			}
        }
        private void ProcessSymmetricKeyDataForElGamal(IPgpPrivateKey privateKey, IBufferedCipher cipher, IList<IBigInteger> symmetricKeyData)
        {
            var k = (ElGamalPrivateKeyParameters)privateKey.Key;
            var size = (k.Parameters.P.BitLength + 7) / 8;

            var bi = symmetricKeyData[0].ToByteArray();

            var diff = bi.Length - size;
            if (diff >= 0)
            {
                cipher.ProcessBytes(bi, diff, size);
            }
            else
            {
                var zeros = new byte[-diff];
                cipher.ProcessBytes(zeros);
                cipher.ProcessBytes(bi);
            }

            bi = symmetricKeyData[1].ToByteArray();

            diff = bi.Length - size;
            if (diff >= 0)
            {
                cipher.ProcessBytes(bi, diff, size);
            }
            else
            {
                var zeros = new byte[-diff];
                cipher.ProcessBytes(zeros);
                cipher.ProcessBytes(bi);
            }
        }
			public CmsReadable GetReadable(KeyParameter sKey)
			{
				try
				{
					this.cipher =  CipherUtilities.GetCipher(this.algorithm.ObjectID);

					Asn1Encodable asn1Enc = this.algorithm.Parameters;
					Asn1Object asn1Params = asn1Enc == null ? null : asn1Enc.ToAsn1Object();

					ICipherParameters cipherParameters = sKey;

					if (asn1Params != null && !(asn1Params is Asn1Null))
					{
						cipherParameters = ParameterUtilities.GetCipherParameters(
							this.algorithm.ObjectID, cipherParameters, asn1Params);
					}
					else
					{
						string alg = this.algorithm.ObjectID.Id;
						if (alg.Equals(CmsEnvelopedDataGenerator.DesEde3Cbc)
							|| alg.Equals(CmsEnvelopedDataGenerator.IdeaCbc)
							|| alg.Equals(CmsEnvelopedDataGenerator.Cast5Cbc))
						{
							cipherParameters = new ParametersWithIV(cipherParameters, new byte[8]);
						}
					}

					cipher.Init(false, cipherParameters);
				}
				catch (SecurityUtilityException e)
				{
					throw new CmsException("couldn't create cipher.", e);
				}
				catch (InvalidKeyException e)
				{
					throw new CmsException("key invalid in message.", e);
				}
				catch (IOException e)
				{
					throw new CmsException("error decoding algorithm parameters.", e);
				}

				try
				{
					return new CmsProcessableInputStream(
						new CipherStream(readable.GetInputStream(), cipher, null));
				}
				catch (IOException e)
				{
					throw new CmsException("error reading content.", e);
				}
			}
示例#51
0
        private static void DecryptThread(IBufferedCipher cipher, byte[] input, BlockingCollection<string> producerConsumerCollection, bool allPaddings = false)
        {
            var taskOutputs = new StringBuilder();
            int lineCount = 0;

            IBlockCipherPadding[] paddings;

            if (allPaddings)
            {
                paddings = new IBlockCipherPadding[]
                               {
                                   new ZeroBytePadding(),
                                   new ISO10126d2Padding(),
                                   new ISO7816d4Padding(),
                                   new Pkcs7Padding(),
                                   new TbcPadding(),
                                   new X923Padding(),
                                   new X923Padding(),
                               };
            }
            else
            {
                paddings = new IBlockCipherPadding[] {new Pkcs7Padding()};
            }

            while (!producerConsumerCollection.IsCompleted)
            {
                string line;
                try
                {
                    line = producerConsumerCollection.Take();
                }
                catch (InvalidOperationException)
                {
                    if (producerConsumerCollection.IsCompleted)
                        break;
                    throw;
                }

                // Use that line as the key.
                byte[] key = Encoding.ASCII.GetBytes(line);

                // For each possible padding...
                foreach (IBlockCipherPadding padding in paddings)
                {
                    // Decrypt
                    byte[] output;
                    try
                    {
                        cipher.Init(false, new KeyParameter(key));
                        output = cipher.DoFinal(input);
                        cipher.Reset();
                    }
                    catch (InvalidCipherTextException)
                    {
                        // TODO: Possibly filder out those inputs before and/or tell the user not to generate them.
                        continue;
                    }

                    // Convert to hexadecimal.
                    foreach (byte b in output)
                    {
                        taskOutputs.Append(HexStringTable[b]);
                    }
                    taskOutputs.AppendFormat(" `{0}` [{1}]", line, padding.PaddingName);
                    taskOutputs.AppendLine();
                    ++lineCount;
                }

                // Output the hashed values in a batch.
                if (taskOutputs.Length > 100000)
                {
                    Console.Write(taskOutputs.ToString());
                    taskOutputs.Clear();
                    lineCount = 0;
                }
            }

            // Output the last hashed values.
            Console.Write(taskOutputs.ToString());
        }