/// <summary> /// Copies the contents of one stream to another, transforming it with the specified cipher. /// </summary> /// <param name="source">The source stream.</param> /// <param name="destination">The destination stream.</param> /// <param name="cipher">The cipher to use.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A task that completes with the completion of the async work.</returns> private static async Task CipherStreamCopyAsync(Stream source, Stream destination, IBufferedCipher cipher, CancellationToken cancellationToken) { Requires.NotNull(source, "source"); Requires.NotNull(destination, "destination"); Requires.NotNull(cipher, "cipher"); byte[] sourceBuffer = new byte[cipher.GetBlockSize()]; byte[] destinationBuffer = new byte[cipher.GetBlockSize() * 2]; while (true) { cancellationToken.ThrowIfCancellationRequested(); int bytesRead = await source.ReadAsync(sourceBuffer, 0, sourceBuffer.Length, cancellationToken); if (bytesRead == 0) { break; } int bytesWritten = cipher.ProcessBytes(sourceBuffer, 0, bytesRead, destinationBuffer, 0); await destination.WriteAsync(destinationBuffer, 0, bytesWritten, cancellationToken); } int finalBytes = cipher.DoFinal(destinationBuffer, 0); await destination.WriteAsync(destinationBuffer, 0, finalBytes); }
// Encrypt data using AES public byte[] encryptWithAES(byte[] input, byte[] key, bool use_GCM) { string algo = AES_algorithm; if (use_GCM) { algo = AES_GCM_algorithm; } IBufferedCipher outCipher = CipherUtilities.GetCipher(algo); int blockSize = outCipher.GetBlockSize(); // Perform key expansion byte[] salt = getSecureRandomBytes(blockSize); ParametersWithIV withIV = new ParametersWithIV(new KeyParameter(key), salt); try { outCipher.Init(true, withIV); } catch (Exception e) { Logging.error(string.Format("Error initializing encryption. {0}", e.ToString())); return(null); } List <byte> bytes = new List <byte>(); bytes.AddRange(salt); bytes.AddRange(outCipher.DoFinal(input)); return(bytes.ToArray()); }
// Decrypt data using AES public byte[] decryptDataAES(byte[] input, byte [] key, int inOffset = 0) { IBufferedCipher inCipher = CipherUtilities.GetCipher(AES_algorithm); int blockSize = inCipher.GetBlockSize(); // Perform key expansion byte[] salt = new byte[blockSize]; for (int i = 0; i < blockSize; i++) { salt[i] = input[inOffset + i]; } ParametersWithIV withIV = new ParametersWithIV(new KeyParameter(key), salt); try { inCipher.Init(false, withIV); } catch (Exception e) { Logging.error(string.Format("Error initializing decryption. {0}", e.ToString())); } byte[] bytes = inCipher.DoFinal(input, inOffset + blockSize, input.Length - inOffset - blockSize); return(bytes); }
// Encrypt data using AES public byte[] encryptDataAES(byte[] input, byte[] key) { IBufferedCipher outCipher = CipherUtilities.GetCipher(AES_algorithm); int blockSize = outCipher.GetBlockSize(); // Perform key expansion byte[] salt = new byte[blockSize]; using (RNGCryptoServiceProvider rngCsp = new RNGCryptoServiceProvider()) { // Fill the array with a random value. rngCsp.GetBytes(salt); } ParametersWithIV withIV = new ParametersWithIV(new KeyParameter(key), salt); try { outCipher.Init(true, withIV); } catch (Exception e) { Logging.error(string.Format("Error initializing encryption. {0}", e.ToString())); return(null); } List <byte> bytes = new List <byte>(); bytes.AddRange(salt); bytes.AddRange(outCipher.DoFinal(input)); return(bytes.ToArray()); }
private byte[] ReadAndProcessBlock() { int blockSize = inCipher.GetBlockSize(); int num = ((blockSize == 0) ? 256 : blockSize); byte[] array = new byte[num]; int num2 = 0; do { int num3 = stream.Read(array, num2, array.Length - num2); if (num3 < 1) { inStreamEnded = true; break; } num2 += num3; }while (num2 < array.Length); byte[] array2 = (inStreamEnded ? inCipher.DoFinal(array, 0, num2) : inCipher.ProcessBytes(array)); if (array2 != null && array2.Length == 0) { array2 = null; } return(array2); }
/// <summary> /// Initializes a new instance of the <see cref="Crypto"/> class. /// May I have a new Crypto? /// </summary> public Crypto() { _random = new SecureRandom(); _keyGen = GeneratorUtilities.GetKeyPairGenerator("ElGamal"); var parameterGenerator = new ElGamalParametersGenerator(); parameterGenerator.Init(512, 10, _random); var parameters = parameterGenerator.GenerateParameters(); _keyGen.Init(new ElGamalKeyGenerationParameters(_random, parameters)); _keys = _keyGen.GenerateKeyPair(); _aCipher = CipherUtilities.GetCipher("ElGamal/NONE/PKCS1Padding"); _cipher = CipherUtilities.GetCipher("AES/CBC/PKCS7Padding"); //new PaddedBufferedBlockCipher(new CbcBlockCipher(new AesEngine())); Iv = new byte[_cipher.GetBlockSize()]; _random.NextBytes(Iv); _hasher = new Sha256Digest(); KeyPair = new AsymmetricCipherKeyPair( new AsymmetricKey(_keys.Public), new AsymmetricKey(_keys.Private)); }
/// <exception cref="System.IO.IOException"/> /// <exception cref="Org.BouncyCastle.Security.GeneralSecurityException"/> internal static DERForRecipientParams CalculateDERForRecipientParams(byte[] @in) { String s = "1.2.840.113549.3.2"; DERForRecipientParams parameters = new DERForRecipientParams(); byte[] outp = new byte[100]; DerObjectIdentifier derob = new DerObjectIdentifier(s); byte[] abyte0 = IVGenerator.GetIV(16); // keyp IBufferedCipher cf = CipherUtilities.GetCipher(derob); KeyParameter kp = new KeyParameter(abyte0); byte[] iv = IVGenerator.GetIV(cf.GetBlockSize()); ParametersWithIV piv = new ParametersWithIV(kp, iv); cf.Init(true, piv); int len = cf.DoFinal(@in, outp, 0); byte[] abyte1 = new byte[len]; Array.Copy(outp, 0, abyte1, 0, len); Asn1EncodableVector ev = new Asn1EncodableVector(); ev.Add(new DerInteger(58)); ev.Add(new DerOctetString(iv)); DerSequence seq = new DerSequence(ev); parameters.abyte0 = abyte0; parameters.abyte1 = abyte1; parameters.algorithmIdentifier = new AlgorithmIdentifier(derob, seq); return(parameters); }
private int GetIVLength( string algorithm) { string[] parts = algorithm.Split('/'); if (parts.Length < 2) { return(0); } string mode = parts[1]; int pos = mode.IndexOfAny(new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }); string baseMode = pos < 0 ? mode : mode.Substring(0, pos); if (!validModes.Contains(baseMode)) { throw new Exception("Unhandled mode: " + mode); } if (baseMode == "ECB") { return(0); } string baseAlgorithm = parts[0]; IBufferedCipher baseCipher = CipherUtilities.GetCipher(baseAlgorithm); return(baseCipher.GetBlockSize()); }
public static string AESEncrypt(string saltString, string plainText) { if (secretKeyParameter == null) { secretKeyParameter = KeyGen(saltString); } string empty = string.Empty; IBufferedCipher cipher = CipherUtilities.GetCipher(ENCRYPTION_ALGORITHM + "/CBC/PKCS5PADDING"); byte[] array = new byte[cipher.GetBlockSize()]; SecureRandom instance = SecureRandom.GetInstance("SHA1PRNG"); instance.NextBytes(array); ParametersWithIV parametersWithIV = new ParametersWithIV(secretKeyParameter, array); cipher.Init(forEncryption: true, parametersWithIV); int num = array.Length; byte[] array2 = cipher.DoFinal(Encoding.UTF8.GetBytes(plainText)); Debug.Log("AESEncrypt:: IV as string: " + Convert.ToBase64String(parametersWithIV.GetIV())); Debug.Log("AESEncrypt:: encryptedByte as string: " + Convert.ToBase64String(array2)); byte[] array3 = new byte[num + array2.Length]; Array.Copy(parametersWithIV.GetIV(), 0, array3, 0, num); Array.Copy(array2, 0, array3, num, array2.Length); empty = Convert.ToBase64String(array3, Base64FormattingOptions.None); Debug.Log("AESEncrypt:: encryptedString: " + empty); return(empty); }
private byte[] ReadAndProcessBlock() { int blockSize = inCipher.GetBlockSize(); int readSize = (blockSize == 0) ? 256 : blockSize; byte[] block = new byte[readSize]; int numRead = 0; do { int count = stream.Read(block, numRead, block.Length - numRead); if (count < 1) { inStreamEnded = true; break; } numRead += count; }while (numRead < block.Length); Debug.Assert(inStreamEnded || numRead == block.Length); byte[] bytes = inStreamEnded ? inCipher.DoFinal(block, 0, numRead) : inCipher.ProcessBytes(block); if (bytes != null && bytes.Length == 0) { bytes = null; } return(bytes); }
public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset) { if (!initialized) { var iv = new byte[cypher.GetBlockSize()]; Array.Copy(inputBuffer, inputOffset, iv, 0, iv.Length); inputOffset += iv.Length; inputCount -= iv.Length; cypher.Init(false, new ParametersWithIV(new KeyParameter(key), iv)); initialized = true; } var res = cypher.ProcessBytes(inputBuffer, inputOffset, inputCount, outputBuffer, outputOffset); DecryptedBytes += res; return(res); }
public EncryptTransform(IBufferedCipher cypher, byte[] key) { _cypher = cypher; var iv = CryptoUtils.GetRandomBytes(cypher.GetBlockSize()); _cypher.Init(true, new ParametersWithIV(new KeyParameter(key), iv)); _tail = iv; EncryptedBytes = 0; }
public override void AddSessionInfo(byte[] si, SecureRandom random) { string symmetricCipherName = PgpUtilities.GetSymmetricCipherName(encAlgorithm); IBufferedCipher cipher = CipherUtilities.GetCipher(symmetricCipherName + "/CFB/NoPadding"); byte[] iv = new byte[cipher.GetBlockSize()]; cipher.Init(forEncryption: true, new ParametersWithRandom(new ParametersWithIV(key, iv), random)); sessionInfo = cipher.DoFinal(si, 0, si.Length - 2); }
public IMessage Encrypt(Boolean normal, byte[] data, out byte[] outdata) { IMessage msg = new TextMessage("Error.Unknown"); outdata = new byte[1]; switch (this.Type) { case "RSA": try { SecureRandom rand = new SecureRandom(); IBufferedCipher cipher = CipherUtilities.GetCipher("RSA/NONE/OAEPWithSHA1AndMGF1Padding"); if (normal == true) { cipher.Init(true, new ParametersWithRandom(this.PublicKey, rand)); } else { cipher.Init(true, new ParametersWithRandom(this.PrivateKey, rand)); } byte[] cipherTextBlock = null; int outputsize = cipher.GetOutputSize(data.Length); //Array size of ciphered data (encrypted data) int blockSize = cipher.GetBlockSize(); //Amount of data we can process at one time (-2 -2*hlen) List <byte> output = new List <byte>(); int outputLen = 0; byte[] dataToProcess = null; for (int chunkPosition = 0; chunkPosition < data.Length; chunkPosition += blockSize) { dataToProcess = new byte[blockSize]; int chunkSize = (data.Length - chunkPosition) < blockSize ? (data.Length - chunkPosition) : blockSize; //Math.Min(blockSize, data.Length - (chunkPosition * blockSize)); Buffer.BlockCopy(data, chunkPosition, dataToProcess, 0, chunkSize); cipherTextBlock = new byte[outputsize]; outputLen = cipher.ProcessBytes(dataToProcess, 0, chunkSize, cipherTextBlock, 0); cipher.DoFinal(cipherTextBlock, outputLen); //output.AddRange(e.ProcessBytes(data, chunkPosition, // chunkSize)); output.AddRange(cipherTextBlock); } outdata = output.ToArray(); msg.Type = "Error.OK"; } catch { } break; } return(msg); }
internal Stream DoGetDataStream(byte[] rawPassPhrase, bool clearPassPhrase) { //IL_012b: Unknown result type (might be due to invalid IL or missing references) //IL_015a: Unknown result type (might be due to invalid IL or missing references) try { SymmetricKeyAlgorithmTag symmetricKeyAlgorithmTag = keyData.EncAlgorithm; KeyParameter parameters = PgpUtilities.DoMakeKeyFromPassPhrase(symmetricKeyAlgorithmTag, keyData.S2k, rawPassPhrase, clearPassPhrase); byte[] secKeyData = keyData.GetSecKeyData(); if (secKeyData != null && secKeyData.Length > 0) { IBufferedCipher cipher = CipherUtilities.GetCipher(PgpUtilities.GetSymmetricCipherName(symmetricKeyAlgorithmTag) + "/CFB/NoPadding"); cipher.Init(forEncryption: false, new ParametersWithIV(parameters, new byte[cipher.GetBlockSize()])); byte[] array = cipher.DoFinal(secKeyData); symmetricKeyAlgorithmTag = (SymmetricKeyAlgorithmTag)array[0]; parameters = ParameterUtilities.CreateKeyParameter(PgpUtilities.GetSymmetricCipherName(symmetricKeyAlgorithmTag), array, 1, array.Length - 1); } IBufferedCipher bufferedCipher = CreateStreamCipher(symmetricKeyAlgorithmTag); byte[] array2 = new byte[bufferedCipher.GetBlockSize()]; bufferedCipher.Init(forEncryption: false, new ParametersWithIV(parameters, array2)); encStream = (Stream)(object)BcpgInputStream.Wrap((Stream)(object)new CipherStream((Stream)(object)encData.GetInputStream(), bufferedCipher, null)); if (encData is SymmetricEncIntegrityPacket) { truncStream = new TruncatedStream(encStream); string digestName = PgpUtilities.GetDigestName(HashAlgorithmTag.Sha1); IDigest digest = DigestUtilities.GetDigest(digestName); encStream = (Stream)(object)new DigestStream((Stream)(object)truncStream, digest, null); } if (Streams.ReadFully(encStream, array2, 0, array2.Length) < array2.Length) { throw new EndOfStreamException("unexpected end of stream."); } int num = encStream.ReadByte(); int num2 = encStream.ReadByte(); if (num < 0 || num2 < 0) { throw new EndOfStreamException("unexpected end of stream."); } bool flag = array2[array2.Length - 2] == (byte)num && array2[array2.Length - 1] == (byte)num2; bool flag2 = num == 0 && num2 == 0; if (!flag && !flag2) { throw new PgpDataValidationException("quick check failed."); } return(encStream); } catch (PgpException ex) { throw ex; } catch (global::System.Exception exception) { throw new PgpException("Exception creating cipher", exception); } }
public void NewIv() { var oldIv = _iv; do { _iv = new byte[_cipher.GetBlockSize()]; _random.NextBytes(Iv); oldIv = oldIv ?? _iv; } while (oldIv.SequenceEqual(_iv)); }
public static byte[] BlockCipherProcessMessage( IBufferedCipher cipher, bool forEncryption, byte[] message, byte[] key, byte[] iv = null) { cipher.Init(forEncryption, new ParametersWithIV( new KeyParameter(key), iv ?? GetRandomBytes(cipher.GetBlockSize()))); byte[] result = cipher.DoFinal(message); return(result); }
public static void CreateAESSchluesseldaten(string aesAlgorithmus, out string AesSchluessel, out string AesIv) { IBufferedCipher cipher = CipherUtilities.GetCipher(aesAlgorithmus); cipher.GetBlockSize(); AesSchluessel = ""; AesIv = ""; /* * AesSchluesselLaenge = GetSchluesselStaerke(schluesselStaerke); * AesSchluessel = CreateAESKey(schluesselStaerke); * AesIv = */ }
private byte[] encryptOnWrite(byte[] dataBytes) { MemoryStream encryptedDataStream = new MemoryStream(); IBufferedCipher outCipher = createCipher(true); CipherStream outCipherStream = new CipherStream(encryptedDataStream, null, outCipher); outCipherStream.Write(dataBytes, 0, dataBytes.Length); Assert.AreEqual(0L, encryptedDataStream.Position % outCipher.GetBlockSize()); outCipherStream.Close(); byte[] encryptedDataBytes = encryptedDataStream.ToArray(); Assert.AreEqual(dataBytes.Length, encryptedDataBytes.Length); return(encryptedDataBytes); }
/// <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)); }
// 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); }
/*加密核心 * 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); }
internal static DERForRecipientParams CalculateDERForRecipientParams(byte[] @in) { /* * According to ISO 32000-2 (7.6.5.3 Public-key encryption algorithms) RC-2 algorithm is outdated * and should be replaced with a safer one 256-bit AES-CBC: * The algorithms that shall be used to encrypt the enveloped data in the CMS object are: * - RC4 with key lengths up to 256-bits (deprecated); * - DES, Triple DES, RC2 with key lengths up to 128 bits (deprecated); * - 128-bit AES in Cipher Block Chaining (CBC) mode (deprecated); * - 192-bit AES in CBC mode (deprecated); * - 256-bit AES in CBC mode. */ String s = "1.2.840.113549.3.2"; DERForRecipientParams parameters = new DERForRecipientParams(); byte[] outp = new byte[100]; DerObjectIdentifier derob = new DerObjectIdentifier(s); // keyp byte[] abyte0 = IVGenerator.GetIV(16); IBufferedCipher cf = CipherUtilities.GetCipher(derob); KeyParameter kp = new KeyParameter(abyte0); byte[] iv = IVGenerator.GetIV(cf.GetBlockSize()); ParametersWithIV piv = new ParametersWithIV(kp, iv); cf.Init(true, piv); int len = cf.DoFinal(@in, outp, 0); byte[] abyte1 = new byte[len]; Array.Copy(outp, 0, abyte1, 0, len); Asn1EncodableVector ev = new Asn1EncodableVector(); ev.Add(new DerInteger(58)); ev.Add(new DerOctetString(iv)); DerSequence seq = new DerSequence(ev); parameters.abyte0 = abyte0; parameters.abyte1 = abyte1; parameters.algorithmIdentifier = new AlgorithmIdentifier(derob, seq); return(parameters); }
// Encrypt data using AES public byte[] encryptWithAES(byte[] input, byte[] key, bool use_GCM) { string algo = AES_algorithm; if (use_GCM) { algo = AES_GCM_algorithm; } IBufferedCipher outCipher = CipherUtilities.GetCipher(algo); int salt_size = outCipher.GetBlockSize(); if (use_GCM) { // TODO TODO GCM mode requires 12 bytes salt, enable it after the next release //salt_size = 12; } byte[] salt = getSecureRandomBytes(salt_size); byte[] bytes = null; ParametersWithIV withIV = new ParametersWithIV(new KeyParameter(key), salt); try { outCipher.Init(true, withIV); byte[] encrypted_data = outCipher.DoFinal(input); bytes = new byte[salt.Length + encrypted_data.Length]; Array.Copy(salt, bytes, salt.Length); Array.Copy(encrypted_data, 0, bytes, salt.Length, encrypted_data.Length); } catch (Exception e) { Logging.error(string.Format("Error initializing encryption. {0}", e.ToString())); return(null); } return(bytes); }
/** * signature with a "forged signature" (sig block not at end of plain text) */ private void DoTestBadSig( IAsymmetricKeyParameter priv, IAsymmetricKeyParameter pub) { IDigest sha1 = DigestUtilities.GetDigest("SHA1"); IBufferedCipher signer = CipherUtilities.GetCipher("RSA//PKCS1Padding"); signer.Init(true, priv); byte[] block = new byte[signer.GetBlockSize()]; sha1.Update((byte)0); byte[] sigHeader = Hex.Decode("3021300906052b0e03021a05000414"); Array.Copy(sigHeader, 0, block, 0, sigHeader.Length); // byte[] dig = sha1.digest(); byte[] dig = DigestUtilities.DoFinal(sha1); Array.Copy(dig, 0, block, sigHeader.Length, dig.Length); Array.Copy(sigHeader, 0, block, sigHeader.Length + dig.Length, sigHeader.Length); byte[] sig = signer.DoFinal(block); ISigner verifier = SignerUtilities.GetSigner("SHA1WithRSA"); verifier.Init(false, pub); verifier.Update((byte)0); if (verifier.VerifySignature(sig)) { Fail("bad signature passed"); } }
private Asn1Object CreateDERForRecipient(byte[] inp, X509Certificate cert) { String s = "1.2.840.113549.3.2"; byte[] outp = new byte[100]; DerObjectIdentifier derob = new DerObjectIdentifier(s); byte[] keyp = IVGenerator.GetIV(16); IBufferedCipher cf = CipherUtilities.GetCipher(derob); KeyParameter kp = new KeyParameter(keyp); byte[] iv = IVGenerator.GetIV(cf.GetBlockSize()); ParametersWithIV piv = new ParametersWithIV(kp, iv); cf.Init(true, piv); int len = cf.DoFinal(inp, outp, 0); byte[] abyte1 = new byte[len]; System.Array.Copy(outp, 0, abyte1, 0, len); DerOctetString deroctetstring = new DerOctetString(abyte1); KeyTransRecipientInfo keytransrecipientinfo = ComputeRecipientInfo(cert, keyp); DerSet derset = new DerSet(new RecipientInfo(keytransrecipientinfo)); Asn1EncodableVector ev = new Asn1EncodableVector(); ev.Add(new DerInteger(58)); ev.Add(new DerOctetString(iv)); DerSequence seq = new DerSequence(ev); AlgorithmIdentifier algorithmidentifier = new AlgorithmIdentifier(derob, seq); EncryptedContentInfo encryptedcontentinfo = new EncryptedContentInfo(PkcsObjectIdentifiers.Data, algorithmidentifier, deroctetstring); Asn1Set set = null; EnvelopedData env = new EnvelopedData(null, derset, encryptedcontentinfo, set); Org.BouncyCastle.Asn1.Cms.ContentInfo contentinfo = new Org.BouncyCastle.Asn1.Cms.ContentInfo(PkcsObjectIdentifiers.EnvelopedData, env); return(contentinfo.ToAsn1Object()); }
/// <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) { var pbeMethod = _methods[0] as PbeMethod; if (pbeMethod != null) { key = pbeMethod.GetKey(); } else { var pubMethod = (PubMethod)_methods[0]; key = PgpUtilities.MakeRandomKey(_defAlgorithm, _rand); var sessionInfo = CreateSessionInfo(_defAlgorithm, key); try { pubMethod.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); var sessionInfo = CreateSessionInfo(_defAlgorithm, key); for (var i = 0; i != _methods.Count; i++) { var m = (EncMethod)_methods[i]; try { m.AddSessionInfo(sessionInfo, _rand); } catch (Exception e) { throw new PgpException("exception encrypting session key", e); } _pOut.WritePacket(m); } } var 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) var 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); } } var blockSize = _c.GetBlockSize(); var 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) { var digestName = PgpUtilities.GetDigestName(HashAlgorithmTag.Sha1); var 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); } }
/// <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); } }
// Decrypt data using AES public byte[] decryptWithAES(byte[] input, byte [] key, bool use_GCM, int inOffset = 0) { string algo = AES_algorithm; if (use_GCM) { algo = AES_GCM_algorithm; } IBufferedCipher inCipher = CipherUtilities.GetCipher(algo); int block_size = inCipher.GetBlockSize(); int salt_size = block_size; if (use_GCM) { // GCM mode requires 12 bytes salt salt_size = 12; } byte[] bytes = null; try { try { byte[] salt = new byte[block_size]; Array.Copy(input, inOffset, salt, 0, salt.Length); ParametersWithIV withIV = new ParametersWithIV(new KeyParameter(key), salt); inCipher.Init(false, withIV); bytes = inCipher.DoFinal(input, inOffset + block_size, input.Length - inOffset - block_size); }catch (Exception) { // TODO TODO reverse contents in try and catch after next version release // try again using 12 bytes salt if (use_GCM) { byte[] salt = new byte[salt_size]; Array.Copy(input, inOffset, salt, 0, salt.Length); ParametersWithIV withIV = new ParametersWithIV(new KeyParameter(key), salt); inCipher.Init(false, withIV); bytes = inCipher.DoFinal(input, inOffset + salt_size, input.Length - inOffset - salt_size); } else { bytes = null; throw; } } } catch (Exception e) { bytes = null; Logging.error(string.Format("Error initializing decryption. {0}", e.ToString())); } return(bytes); }
private Stream Open(Stream outStr, long length, byte[] buffer) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) if (cOut != null) { throw new InvalidOperationException("generator already in open state"); } if (((global::System.Collections.ICollection)methods).get_Count() == 0) { throw new InvalidOperationException("No encryption methods specified"); } if (outStr == null) { throw new ArgumentNullException("outStr"); } pOut = new BcpgOutputStream(outStr); KeyParameter keyParameter; if (((global::System.Collections.ICollection)methods).get_Count() == 1) { if (methods.get_Item(0) is PbeMethod) { PbeMethod pbeMethod = (PbeMethod)methods.get_Item(0); keyParameter = pbeMethod.GetKey(); } else { keyParameter = PgpUtilities.MakeRandomKey(defAlgorithm, rand); byte[] si = CreateSessionInfo(defAlgorithm, keyParameter); PubMethod pubMethod = (PubMethod)methods.get_Item(0); try { pubMethod.AddSessionInfo(si, rand); } catch (global::System.Exception exception) { throw new PgpException("exception encrypting session key", exception); } } pOut.WritePacket((ContainedPacket)methods.get_Item(0)); } else { keyParameter = PgpUtilities.MakeRandomKey(defAlgorithm, rand); byte[] si2 = CreateSessionInfo(defAlgorithm, keyParameter); for (int i = 0; i != ((global::System.Collections.ICollection)methods).get_Count(); i++) { EncMethod encMethod = (EncMethod)methods.get_Item(i); try { encMethod.AddSessionInfo(si2, rand); } catch (global::System.Exception exception2) { throw new PgpException("exception encrypting session key", exception2); } pOut.WritePacket(encMethod); } } string symmetricCipherName = PgpUtilities.GetSymmetricCipherName(defAlgorithm); if (symmetricCipherName == null) { throw new PgpException("null cipher specified"); } try { symmetricCipherName = ((!withIntegrityPacket) ? (symmetricCipherName + "/OpenPGPCFB/NoPadding") : (symmetricCipherName + "/CFB/NoPadding")); c = CipherUtilities.GetCipher(symmetricCipherName); byte[] iv = new byte[c.GetBlockSize()]; c.Init(forEncryption: true, new ParametersWithRandom(new ParametersWithIV(keyParameter, iv), rand)); if (buffer == null) { if (withIntegrityPacket) { pOut = new BcpgOutputStream(outStr, PacketTag.SymmetricEncryptedIntegrityProtected, length + c.GetBlockSize() + 2 + 1 + 22); ((Stream)pOut).WriteByte((byte)1); } else { pOut = new BcpgOutputStream(outStr, PacketTag.SymmetricKeyEncrypted, length + c.GetBlockSize() + 2, oldFormat); } } else if (withIntegrityPacket) { pOut = new BcpgOutputStream(outStr, PacketTag.SymmetricEncryptedIntegrityProtected, buffer); ((Stream)pOut).WriteByte((byte)1); } else { pOut = new BcpgOutputStream(outStr, PacketTag.SymmetricKeyEncrypted, buffer); } int blockSize = c.GetBlockSize(); byte[] array = new byte[blockSize + 2]; rand.NextBytes(array, 0, blockSize); global::System.Array.Copy((global::System.Array)array, array.Length - 4, (global::System.Array)array, array.Length - 2, 2); Stream val = (Stream)(object)(cOut = new CipherStream((Stream)(object)pOut, null, c)); if (withIntegrityPacket) { string digestName = PgpUtilities.GetDigestName(HashAlgorithmTag.Sha1); IDigest digest = DigestUtilities.GetDigest(digestName); val = (Stream)(object)(digestOut = new DigestStream(val, null, digest)); } val.Write(array, 0, array.Length); return((Stream)(object)new WrappedGeneratorStream(this, val)); } catch (global::System.Exception exception3) { throw new PgpException("Exception creating cipher", exception3); } }
internal Stream DoGetDataStream(byte[] rawPassPhrase, bool clearPassPhrase) { try { SymmetricKeyAlgorithmTag keyAlgorithm = keyData.EncAlgorithm; KeyParameter key = PgpUtilities.DoMakeKeyFromPassPhrase( keyAlgorithm, keyData.S2k, rawPassPhrase, clearPassPhrase); byte[] secKeyData = keyData.GetSecKeyData(); if (secKeyData != null && secKeyData.Length > 0) { IBufferedCipher keyCipher = CipherUtilities.GetCipher( PgpUtilities.GetSymmetricCipherName(keyAlgorithm) + "/CFB/NoPadding"); keyCipher.Init(false, new ParametersWithIV(key, new byte[keyCipher.GetBlockSize()])); byte[] keyBytes = keyCipher.DoFinal(secKeyData); keyAlgorithm = (SymmetricKeyAlgorithmTag)keyBytes[0]; key = ParameterUtilities.CreateKeyParameter( PgpUtilities.GetSymmetricCipherName(keyAlgorithm), keyBytes, 1, keyBytes.Length - 1); } IBufferedCipher c = CreateStreamCipher(keyAlgorithm); byte[] iv = new byte[c.GetBlockSize()]; c.Init(false, new ParametersWithIV(key, iv)); encStream = BcpgInputStream.Wrap(new CipherStream(encData.GetInputStream(), c, null)); if (encData is SymmetricEncIntegrityPacket) { truncStream = new TruncatedStream(encStream); string digestName = PgpUtilities.GetDigestName(HashAlgorithmTag.Sha1); IDigest digest = DigestUtilities.GetDigest(digestName); encStream = new DigestStream(truncStream, digest, null); } if (Streams.ReadFully(encStream, iv, 0, iv.Length) < iv.Length) { throw new EndOfStreamException("unexpected end of stream."); } int v1 = encStream.ReadByte(); int v2 = encStream.ReadByte(); if (v1 < 0 || v2 < 0) { throw new EndOfStreamException("unexpected end of stream."); } // Note: the oracle attack on the "quick check" bytes is not deemed // a security risk for PBE (see PgpPublicKeyEncryptedData) bool repeatCheckPassed = iv[iv.Length - 2] == (byte)v1 && iv[iv.Length - 1] == (byte)v2; // Note: some versions of PGP appear to produce 0 for the extra // bytes rather than repeating the two previous bytes bool zeroesCheckPassed = v1 == 0 && v2 == 0; if (!repeatCheckPassed && !zeroesCheckPassed) { throw new PgpDataValidationException("quick check failed."); } return(encStream); } catch (PgpException e) { throw e; } catch (Exception e) { throw new PgpException("Exception creating cipher", e); } }