protected virtual ParametersWithIV CreateParametersWithIV(KeyParameter key, byte[] buf, ref int off, int len) { ParametersWithIV ivParams = new ParametersWithIV(key, buf, off, len); off += len; return ivParams; }
public RecipientInfo Generate(KeyParameter contentEncryptionKey, SecureRandom random) { byte[] keyBytes = contentEncryptionKey.GetKey(); string rfc3211WrapperName = Helper.GetRfc3211WrapperName(keyEncryptionKeyOID); IWrapper keyWrapper = Helper.CreateWrapper(rfc3211WrapperName); // Note: In Java build, the IV is automatically generated in JCE layer int ivLength = rfc3211WrapperName.StartsWith("DESEDE") ? 8 : 16; byte[] iv = new byte[ivLength]; random.NextBytes(iv); ICipherParameters parameters = new ParametersWithIV(keyEncryptionKey, iv); keyWrapper.Init(true, new ParametersWithRandom(parameters, random)); Asn1OctetString encryptedKey = new DerOctetString( keyWrapper.Wrap(keyBytes, 0, keyBytes.Length)); DerSequence seq = new DerSequence( new DerObjectIdentifier(keyEncryptionKeyOID), new DerOctetString(iv)); AlgorithmIdentifier keyEncryptionAlgorithm = new AlgorithmIdentifier( PkcsObjectIdentifiers.IdAlgPwriKek, seq); return new RecipientInfo(new PasswordRecipientInfo( keyDerivationAlgorithm, keyEncryptionAlgorithm, encryptedKey)); }
/** * decrypt the content and return an input stream. */ public override CmsTypedStream GetContentStream( ICipherParameters key) { try { AlgorithmIdentifier kekAlg = AlgorithmIdentifier.GetInstance(info.KeyEncryptionAlgorithm); Asn1Sequence kekAlgParams = (Asn1Sequence)kekAlg.Parameters; byte[] encryptedKey = info.EncryptedKey.GetOctets(); string kekAlgName = DerObjectIdentifier.GetInstance(kekAlgParams[0]).Id; string cName = CmsEnvelopedHelper.Instance.GetRfc3211WrapperName(kekAlgName); IWrapper keyWrapper = WrapperUtilities.GetWrapper(cName); byte[] iv = Asn1OctetString.GetInstance(kekAlgParams[1]).GetOctets(); ICipherParameters parameters = ((CmsPbeKey)key).GetEncoded(kekAlgName); parameters = new ParametersWithIV(parameters, iv); keyWrapper.Init(false, parameters); KeyParameter sKey = ParameterUtilities.CreateKeyParameter( GetContentAlgorithmName(), keyWrapper.Unwrap(encryptedKey, 0, encryptedKey.Length)); return GetContentFromSessionKey(sKey); } catch (SecurityUtilityException e) { throw new CmsException("couldn't create cipher.", e); } catch (InvalidKeyException e) { throw new CmsException("key invalid in message.", e); } }
/** * Method init * * @param forWrapping * @param param */ public void Init( bool forWrapping, ICipherParameters parameters) { this.forWrapping = forWrapping; this.engine = new CbcBlockCipher(new DesEdeEngine()); SecureRandom sr; if (parameters is ParametersWithRandom) { ParametersWithRandom pr = (ParametersWithRandom) parameters; parameters = pr.Parameters; sr = pr.Random; } else { sr = new SecureRandom(); } if (parameters is KeyParameter) { this.param = (KeyParameter) parameters; if (this.forWrapping) { // Hm, we have no IV but we want to wrap ?!? // well, then we have to create our own IV. this.iv = new byte[8]; sr.NextBytes(iv); this.paramPlusIV = new ParametersWithIV(this.param, this.iv); } } else if (parameters is ParametersWithIV) { if (!forWrapping) throw new ArgumentException("You should not supply an IV for unwrapping"); this.paramPlusIV = (ParametersWithIV) parameters; this.iv = this.paramPlusIV.GetIV(); this.param = (KeyParameter) this.paramPlusIV.Parameters; if (this.iv.Length != 8) throw new ArgumentException("IV is not 8 octets", "parameters"); } }
public void Init( bool forWrapping, ICipherParameters param) { this.forWrapping = forWrapping; if (param is ParametersWithRandom) { ParametersWithRandom p = (ParametersWithRandom) param; this.rand = p.Random; this.param = (ParametersWithIV) p.Parameters; } else { if (forWrapping) { rand = new SecureRandom(); } this.param = (ParametersWithIV) param; } }
/** * Method unwrap * * @param in * @param inOff * @param inLen * @return * @throws InvalidCipherTextException */ public byte[] Unwrap( byte[] input, int inOff, int length) { if (forWrapping) { throw new InvalidOperationException("Not set for unwrapping"); } if (input == null) { throw new InvalidCipherTextException("Null pointer as ciphertext"); } if (length % engine.GetBlockSize() != 0) { throw new InvalidCipherTextException("Ciphertext not multiple of " + engine.GetBlockSize()); } /* // Check if the length of the cipher text is reasonable given the key // type. It must be 40 bytes for a 168 bit key and either 32, 40, or // 48 bytes for a 128, 192, or 256 bit key. If the length is not supported // or inconsistent with the algorithm for which the key is intended, // return error. // // we do not accept 168 bit keys. it has to be 192 bit. int lengthA = (estimatedKeyLengthInBit / 8) + 16; int lengthB = estimatedKeyLengthInBit % 8; if ((lengthA != keyToBeUnwrapped.Length) || (lengthB != 0)) { throw new XMLSecurityException("empty"); } */ // Decrypt the cipher text with TRIPLedeS in CBC mode using the KEK // and an initialization vector (IV) of 0x4adda22c79e82105. Call the output TEMP3. ParametersWithIV param2 = new ParametersWithIV(this.parameters, IV2); this.engine.Init(false, param2); byte [] TEMP3 = new byte[length]; Array.Copy(input, inOff, TEMP3, 0, length); for (int i = 0; i < (TEMP3.Length / engine.GetBlockSize()); i++) { int currentBytePos = i * engine.GetBlockSize(); engine.ProcessBlock(TEMP3, currentBytePos, TEMP3, currentBytePos); } // Reverse the order of the octets in TEMP3 and call the result TEMP2. byte[] TEMP2 = new byte[TEMP3.Length]; for (int i = 0; i < TEMP3.Length; i++) { TEMP2[i] = TEMP3[TEMP3.Length - (i + 1)]; } // Decompose TEMP2 into IV, the first 8 octets, and TEMP1, the remaining octets. this.iv = new byte[8]; byte[] TEMP1 = new byte[TEMP2.Length - 8]; Array.Copy(TEMP2, 0, this.iv, 0, 8); Array.Copy(TEMP2, 8, TEMP1, 0, TEMP2.Length - 8); // Decrypt TEMP1 using TRIPLedeS in CBC mode using the KEK and the IV // found in the previous step. Call the result WKCKS. this.paramPlusIV = new ParametersWithIV(this.parameters, this.iv); this.engine.Init(false, this.paramPlusIV); byte[] LCEKPADICV = new byte[TEMP1.Length]; Array.Copy(TEMP1, 0, LCEKPADICV, 0, TEMP1.Length); for (int i = 0; i < (LCEKPADICV.Length / engine.GetBlockSize()); i++) { int currentBytePos = i * engine.GetBlockSize(); engine.ProcessBlock(LCEKPADICV, currentBytePos, LCEKPADICV, currentBytePos); } // Decompose LCEKPADICV. CKS is the last 8 octets and WK, the wrapped key, are // those octets before the CKS. byte[] result = new byte[LCEKPADICV.Length - 8]; byte[] CKStoBeVerified = new byte[8]; Array.Copy(LCEKPADICV, 0, result, 0, LCEKPADICV.Length - 8); Array.Copy(LCEKPADICV, LCEKPADICV.Length - 8, CKStoBeVerified, 0, 8); // Calculate a CMS Key Checksum, (section 5.6.1), over the WK and compare // with the CKS extracted in the above step. If they are not equal, return error. if (!CheckCmsKeyChecksum(result, CKStoBeVerified)) { throw new InvalidCipherTextException( "Checksum inside ciphertext is corrupted"); } if ((result.Length - ((result[0] & 0xff) + 1)) > 7) { throw new InvalidCipherTextException( "too many pad bytes (" + (result.Length - ((result[0] & 0xff) + 1)) + ")"); } // CEK is the wrapped key, now extracted for use in data decryption. byte[] CEK = new byte[result[0]]; Array.Copy(result, 1, CEK, 0, CEK.Length); return CEK; }
/** * Method wrap * * @param in * @param inOff * @param inLen * @return */ public byte[] Wrap( byte[] input, int inOff, int length) { if (!forWrapping) { throw new InvalidOperationException("Not initialized for wrapping"); } int len = length + 1; if ((len % 8) != 0) { len += 8 - (len % 8); } byte [] keyToBeWrapped = new byte[len]; keyToBeWrapped[0] = (byte)length; Array.Copy(input, inOff, keyToBeWrapped, 1, length); byte[] pad = new byte[keyToBeWrapped.Length - length - 1]; if (pad.Length > 0) { sr.NextBytes(pad); Array.Copy(pad, 0, keyToBeWrapped, length + 1, pad.Length); } // Compute the CMS Key Checksum, (section 5.6.1), call this CKS. byte[] CKS = CalculateCmsKeyChecksum(keyToBeWrapped); // Let WKCKS = WK || CKS where || is concatenation. byte[] WKCKS = new byte[keyToBeWrapped.Length + CKS.Length]; Array.Copy(keyToBeWrapped, 0, WKCKS, 0, keyToBeWrapped.Length); Array.Copy(CKS, 0, WKCKS, keyToBeWrapped.Length, CKS.Length); // Encrypt WKCKS in CBC mode using KEK as the key and IV as the // initialization vector. Call the results TEMP1. byte [] TEMP1 = new byte[WKCKS.Length]; Array.Copy(WKCKS, 0, TEMP1, 0, WKCKS.Length); int noOfBlocks = WKCKS.Length / engine.GetBlockSize(); int extraBytes = WKCKS.Length % engine.GetBlockSize(); if (extraBytes != 0) { throw new InvalidOperationException("Not multiple of block length"); } engine.Init(true, paramPlusIV); for (int i = 0; i < noOfBlocks; i++) { int currentBytePos = i * engine.GetBlockSize(); engine.ProcessBlock(TEMP1, currentBytePos, TEMP1, currentBytePos); } // Left TEMP2 = IV || TEMP1. byte[] TEMP2 = new byte[this.iv.Length + TEMP1.Length]; Array.Copy(this.iv, 0, TEMP2, 0, this.iv.Length); Array.Copy(TEMP1, 0, TEMP2, this.iv.Length, TEMP1.Length); // Reverse the order of the octets in TEMP2 and call the result TEMP3. byte[] TEMP3 = new byte[TEMP2.Length]; for (int i = 0; i < TEMP2.Length; i++) { TEMP3[i] = TEMP2[TEMP2.Length - (i + 1)]; } // Encrypt TEMP3 in CBC mode using the KEK and an initialization vector // of 0x 4a dd a2 2c 79 e8 21 05. The resulting cipher text is the desired // result. It is 40 octets long if a 168 bit key is being wrapped. ParametersWithIV param2 = new ParametersWithIV(this.parameters, IV2); this.engine.Init(true, param2); for (int i = 0; i < noOfBlocks + 1; i++) { int currentBytePos = i * engine.GetBlockSize(); engine.ProcessBlock(TEMP3, currentBytePos, TEMP3, currentBytePos); } return TEMP3; }
public ICmsReadable 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); } }
public static ICipherParameters GenerateCipherParameters( string algorithm, char[] password, bool wrongPkcs12Zero, Asn1Encodable pbeParameters) { string mechanism = (string) algorithms[algorithm.ToUpperInvariant()]; byte[] keyBytes = null; byte[] salt = null; int iterationCount = 0; if (IsPkcs12(mechanism)) { Pkcs12PbeParams pbeParams = Pkcs12PbeParams.GetInstance(pbeParameters); salt = pbeParams.GetIV(); iterationCount = pbeParams.Iterations.IntValue; keyBytes = PbeParametersGenerator.Pkcs12PasswordToBytes(password, wrongPkcs12Zero); } else if (IsPkcs5Scheme2(mechanism)) { // See below } else { PbeParameter pbeParams = PbeParameter.GetInstance(pbeParameters); salt = pbeParams.GetSalt(); iterationCount = pbeParams.IterationCount.IntValue; keyBytes = PbeParametersGenerator.Pkcs5PasswordToBytes(password); } ICipherParameters parameters = null; if (IsPkcs5Scheme2(mechanism)) { PbeS2Parameters s2p = PbeS2Parameters.GetInstance(pbeParameters.ToAsn1Object()); AlgorithmIdentifier encScheme = s2p.EncryptionScheme; DerObjectIdentifier encOid = encScheme.ObjectID; Asn1Object encParams = encScheme.Parameters.ToAsn1Object(); // TODO What about s2p.KeyDerivationFunc.ObjectID? Pbkdf2Params pbeParams = Pbkdf2Params.GetInstance(s2p.KeyDerivationFunc.Parameters.ToAsn1Object()); byte[] iv; if (encOid.Equals(PkcsObjectIdentifiers.RC2Cbc)) // PKCS5.B.2.3 { RC2CbcParameter rc2Params = RC2CbcParameter.GetInstance(encParams); iv = rc2Params.GetIV(); } else { iv = Asn1OctetString.GetInstance(encParams).GetOctets(); } salt = pbeParams.GetSalt(); iterationCount = pbeParams.IterationCount.IntValue; keyBytes = PbeParametersGenerator.Pkcs5PasswordToBytes(password); int keyLength = pbeParams.KeyLength != null ? pbeParams.KeyLength.IntValue * 8 : GeneratorUtilities.GetDefaultKeySize(encOid); PbeParametersGenerator gen = MakePbeGenerator( (string)algorithmType[mechanism], null, keyBytes, salt, iterationCount); parameters = gen.GenerateDerivedParameters(encOid.Id, keyLength); if (iv != null) { // FIXME? OpenSSL weirdness with IV of zeros (for ECB keys?) if (Arrays.AreEqual(iv, new byte[iv.Length])) { //Console.Error.Write("***** IV all 0 (length " + iv.Length + ") *****"); } else { parameters = new ParametersWithIV(parameters, iv); } } } else if (mechanism.StartsWith("PBEwithSHA-1")) { PbeParametersGenerator generator = MakePbeGenerator( (string) algorithmType[mechanism], new Sha1Digest(), keyBytes, salt, iterationCount); if (mechanism.Equals("PBEwithSHA-1and128bitRC4")) { parameters = generator.GenerateDerivedParameters("RC4", 128); } else if (mechanism.Equals("PBEwithSHA-1and40bitRC4")) { parameters = generator.GenerateDerivedParameters("RC4", 40); } else if (mechanism.Equals("PBEwithSHA-1and3-keyDESEDE-CBC")) { parameters = generator.GenerateDerivedParameters("DESEDE", 192, 64); } else if (mechanism.Equals("PBEwithSHA-1and2-keyDESEDE-CBC")) { parameters = generator.GenerateDerivedParameters("DESEDE", 128, 64); } else if (mechanism.Equals("PBEwithSHA-1and128bitRC2-CBC")) { parameters = generator.GenerateDerivedParameters("RC2", 128, 64); } else if (mechanism.Equals("PBEwithSHA-1and40bitRC2-CBC")) { parameters = generator.GenerateDerivedParameters("RC2", 40, 64); } else if (mechanism.Equals("PBEwithSHA-1andDES-CBC")) { parameters = generator.GenerateDerivedParameters("DES", 64, 64); } else if (mechanism.Equals("PBEwithSHA-1andRC2-CBC")) { parameters = generator.GenerateDerivedParameters("RC2", 64, 64); } else if (mechanism.Equals("PBEwithSHA-1and128bitAES-CBC-BC")) { parameters = generator.GenerateDerivedParameters("AES", 128, 128); } else if (mechanism.Equals("PBEwithSHA-1and192bitAES-CBC-BC")) { parameters = generator.GenerateDerivedParameters("AES", 192, 128); } else if (mechanism.Equals("PBEwithSHA-1and256bitAES-CBC-BC")) { parameters = generator.GenerateDerivedParameters("AES", 256, 128); } } else if (mechanism.StartsWith("PBEwithSHA-256")) { PbeParametersGenerator generator = MakePbeGenerator( (string) algorithmType[mechanism], new Sha256Digest(), keyBytes, salt, iterationCount); if (mechanism.Equals("PBEwithSHA-256and128bitAES-CBC-BC")) { parameters = generator.GenerateDerivedParameters("AES", 128, 128); } else if (mechanism.Equals("PBEwithSHA-256and192bitAES-CBC-BC")) { parameters = generator.GenerateDerivedParameters("AES", 192, 128); } else if (mechanism.Equals("PBEwithSHA-256and256bitAES-CBC-BC")) { parameters = generator.GenerateDerivedParameters("AES", 256, 128); } } else if (mechanism.StartsWith("PBEwithMD5")) { PbeParametersGenerator generator = MakePbeGenerator( (string)algorithmType[mechanism], new MD5Digest(), keyBytes, salt, iterationCount); if (mechanism.Equals("PBEwithMD5andDES-CBC")) { parameters = generator.GenerateDerivedParameters("DES", 64, 64); } else if (mechanism.Equals("PBEwithMD5andRC2-CBC")) { parameters = generator.GenerateDerivedParameters("RC2", 64, 64); } else if (mechanism.Equals("PBEwithMD5and128bitAES-CBC-OpenSSL")) { parameters = generator.GenerateDerivedParameters("AES", 128, 128); } else if (mechanism.Equals("PBEwithMD5and192bitAES-CBC-OpenSSL")) { parameters = generator.GenerateDerivedParameters("AES", 192, 128); } else if (mechanism.Equals("PBEwithMD5and256bitAES-CBC-OpenSSL")) { parameters = generator.GenerateDerivedParameters("AES", 256, 128); } } else if (mechanism.StartsWith("PBEwithMD2")) { PbeParametersGenerator generator = MakePbeGenerator( (string)algorithmType[mechanism], new MD2Digest(), keyBytes, salt, iterationCount); if (mechanism.Equals("PBEwithMD2andDES-CBC")) { parameters = generator.GenerateDerivedParameters("DES", 64, 64); } else if (mechanism.Equals("PBEwithMD2andRC2-CBC")) { parameters = generator.GenerateDerivedParameters("RC2", 64, 64); } } else if (mechanism.StartsWith("PBEwithHmac")) { string digestName = mechanism.Substring("PBEwithHmac".Length); IDigest digest = DigestUtilities.GetDigest(digestName); PbeParametersGenerator generator = MakePbeGenerator( (string) algorithmType[mechanism], digest, keyBytes, salt, iterationCount); int bitLen = digest.GetDigestSize() * 8; parameters = generator.GenerateDerivedMacParameters(bitLen); } Array.Clear(keyBytes, 0, keyBytes.Length); return FixDesParity(mechanism, parameters); }
/** * Method wrap * * @param in * @param inOff * @param inLen * @return */ public byte[] Wrap( byte[] input, int inOff, int length) { if (!forWrapping) { throw new InvalidOperationException("Not initialized for wrapping"); } byte[] keyToBeWrapped = new byte[length]; Array.Copy(input, inOff, keyToBeWrapped, 0, length); // Compute the CMS Key Checksum, (section 5.6.1), call this CKS. byte[] CKS = CalculateCmsKeyChecksum(keyToBeWrapped); // Let WKCKS = WK || CKS where || is concatenation. byte[] WKCKS = new byte[keyToBeWrapped.Length + CKS.Length]; Array.Copy(keyToBeWrapped, 0, WKCKS, 0, keyToBeWrapped.Length); Array.Copy(CKS, 0, WKCKS, keyToBeWrapped.Length, CKS.Length); // Encrypt WKCKS in CBC mode using KEK as the key and IV as the // initialization vector. Call the results TEMP1. int blockSize = engine.GetBlockSize(); if (WKCKS.Length % blockSize != 0) throw new InvalidOperationException("Not multiple of block length"); engine.Init(true, paramPlusIV); byte [] TEMP1 = new byte[WKCKS.Length]; for (int currentBytePos = 0; currentBytePos != WKCKS.Length; currentBytePos += blockSize) { engine.ProcessBlock(WKCKS, currentBytePos, TEMP1, currentBytePos); } // Let TEMP2 = IV || TEMP1. byte[] TEMP2 = new byte[this.iv.Length + TEMP1.Length]; Array.Copy(this.iv, 0, TEMP2, 0, this.iv.Length); Array.Copy(TEMP1, 0, TEMP2, this.iv.Length, TEMP1.Length); // Reverse the order of the octets in TEMP2 and call the result TEMP3. byte[] TEMP3 = reverse(TEMP2); // Encrypt TEMP3 in CBC mode using the KEK and an initialization vector // of 0x 4a dd a2 2c 79 e8 21 05. The resulting cipher text is the desired // result. It is 40 octets long if a 168 bit key is being wrapped. ParametersWithIV param2 = new ParametersWithIV(this.param, IV2); this.engine.Init(true, param2); for (int currentBytePos = 0; currentBytePos != TEMP3.Length; currentBytePos += blockSize) { engine.ProcessBlock(TEMP3, currentBytePos, TEMP3, currentBytePos); } return TEMP3; }
internal static byte[] Crypt( bool encrypt, byte[] bytes, char[] password, string dekAlgName, byte[] iv) { PemBaseAlg baseAlg; PemMode mode; ParseDekAlgName(dekAlgName, out baseAlg, out mode); string padding; switch (mode) { case PemMode.CBC: case PemMode.ECB: padding = "PKCS5Padding"; break; case PemMode.CFB: case PemMode.OFB: padding = "NoPadding"; break; default: throw new EncryptionException("Unknown DEK algorithm: " + dekAlgName); } string algorithm; byte[] salt = iv; switch (baseAlg) { case PemBaseAlg.AES_128: case PemBaseAlg.AES_192: case PemBaseAlg.AES_256: algorithm = "AES"; if (salt.Length > 8) { salt = new byte[8]; Array.Copy(iv, 0, salt, 0, salt.Length); } break; case PemBaseAlg.BF: algorithm = "BLOWFISH"; break; case PemBaseAlg.DES: algorithm = "DES"; break; case PemBaseAlg.DES_EDE: case PemBaseAlg.DES_EDE3: algorithm = "DESede"; break; case PemBaseAlg.RC2: case PemBaseAlg.RC2_40: case PemBaseAlg.RC2_64: algorithm = "RC2"; break; default: throw new EncryptionException("Unknown DEK algorithm: " + dekAlgName); } string cipherName = algorithm + "/" + mode + "/" + padding; IBufferedCipher cipher = CipherUtilities.GetCipher(cipherName); ICipherParameters cParams = GetCipherParameters(password, baseAlg, salt); if (mode != PemMode.ECB) { cParams = new ParametersWithIV(cParams, iv); } cipher.Init(encrypt, cParams); return cipher.DoFinal(bytes); }