public const int Unauthorized = 6; // Request unauthorized public OcspResp Generate( int status, object response) { if (response == null) { return new OcspResp(new OcspResponse(new OcspResponseStatus(status),null)); } if (response is BasicOcspResp) { BasicOcspResp r = (BasicOcspResp)response; Asn1OctetString octs; try { octs = new DerOctetString(r.GetEncoded()); } catch (Exception e) { throw new OcspException("can't encode object.", e); } ResponseBytes rb = new ResponseBytes( OcspObjectIdentifiers.PkixOcspBasic, octs); return new OcspResp(new OcspResponse( new OcspResponseStatus(status), rb)); } throw new OcspException("unknown response object"); }
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)); }
public RecipientInfo Generate(KeyParameter contentEncryptionKey, SecureRandom random) { byte[] keyBytes = contentEncryptionKey.GetKey(); IWrapper keyWrapper = Helper.CreateWrapper(keyEncryptionAlgorithm.ObjectID.Id); keyWrapper.Init(true, new ParametersWithRandom(keyEncryptionKey, random)); Asn1OctetString encryptedKey = new DerOctetString( keyWrapper.Wrap(keyBytes, 0, keyBytes.Length)); return new RecipientInfo(new KekRecipientInfo(kekIdentifier, keyEncryptionAlgorithm, encryptedKey)); }
public RecipientInfo Generate(KeyParameter contentEncryptionKey, SecureRandom random) { byte[] keyBytes = contentEncryptionKey.GetKey(); AsymmetricKeyParameter senderPublicKey = senderKeyPair.Public; ICipherParameters senderPrivateParams = senderKeyPair.Private; OriginatorIdentifierOrKey originator; try { originator = new OriginatorIdentifierOrKey( CreateOriginatorPublicKey(senderPublicKey)); } catch (IOException e) { throw new InvalidKeyException("cannot extract originator public key: " + e); } Asn1OctetString ukm = null; if (keyAgreementOID.Id.Equals(CmsEnvelopedGenerator.ECMqvSha1Kdf)) { try { IAsymmetricCipherKeyPairGenerator ephemKPG = GeneratorUtilities.GetKeyPairGenerator(keyAgreementOID); ephemKPG.Init( ((ECPublicKeyParameters)senderPublicKey).CreateKeyGenerationParameters(random)); AsymmetricCipherKeyPair ephemKP = ephemKPG.GenerateKeyPair(); ukm = new DerOctetString( new MQVuserKeyingMaterial( CreateOriginatorPublicKey(ephemKP.Public), null)); senderPrivateParams = new MqvPrivateParameters( (ECPrivateKeyParameters)senderPrivateParams, (ECPrivateKeyParameters)ephemKP.Private, (ECPublicKeyParameters)ephemKP.Public); } catch (IOException e) { throw new InvalidKeyException("cannot extract MQV ephemeral public key: " + e); } catch (SecurityUtilityException e) { throw new InvalidKeyException("cannot determine MQV ephemeral key pair parameters from public key: " + e); } } DerSequence paramSeq = new DerSequence( keyEncryptionOID, DerNull.Instance); AlgorithmIdentifier keyEncAlg = new AlgorithmIdentifier(keyAgreementOID, paramSeq); Asn1EncodableVector recipientEncryptedKeys = new Asn1EncodableVector(); foreach (X509Certificate recipientCert in recipientCerts) { TbsCertificateStructure tbsCert; try { tbsCert = TbsCertificateStructure.GetInstance( Asn1Object.FromByteArray(recipientCert.GetTbsCertificate())); } catch (Exception) { throw new ArgumentException("can't extract TBS structure from certificate"); } // TODO Should there be a SubjectKeyIdentifier-based alternative? IssuerAndSerialNumber issuerSerial = new IssuerAndSerialNumber( tbsCert.Issuer, tbsCert.SerialNumber.Value); KeyAgreeRecipientIdentifier karid = new KeyAgreeRecipientIdentifier(issuerSerial); ICipherParameters recipientPublicParams = recipientCert.GetPublicKey(); if (keyAgreementOID.Id.Equals(CmsEnvelopedGenerator.ECMqvSha1Kdf)) { recipientPublicParams = new MqvPublicParameters( (ECPublicKeyParameters)recipientPublicParams, (ECPublicKeyParameters)recipientPublicParams); } // Use key agreement to choose a wrap key for this recipient IBasicAgreement keyAgreement = AgreementUtilities.GetBasicAgreementWithKdf( keyAgreementOID, keyEncryptionOID.Id); keyAgreement.Init(new ParametersWithRandom(senderPrivateParams, random)); BigInteger agreedValue = keyAgreement.CalculateAgreement(recipientPublicParams); int keyEncryptionKeySize = GeneratorUtilities.GetDefaultKeySize(keyEncryptionOID) / 8; byte[] keyEncryptionKeyBytes = X9IntegerConverter.IntegerToBytes(agreedValue, keyEncryptionKeySize); KeyParameter keyEncryptionKey = ParameterUtilities.CreateKeyParameter( keyEncryptionOID, keyEncryptionKeyBytes); // Wrap the content encryption key with the agreement key IWrapper keyWrapper = Helper.CreateWrapper(keyEncryptionOID.Id); keyWrapper.Init(true, new ParametersWithRandom(keyEncryptionKey, random)); byte[] encryptedKeyBytes = keyWrapper.Wrap(keyBytes, 0, keyBytes.Length); Asn1OctetString encryptedKey = new DerOctetString(encryptedKeyBytes); recipientEncryptedKeys.Add(new RecipientEncryptedKey(karid, encryptedKey)); } return new RecipientInfo(new KeyAgreeRecipientInfo(originator, ukm, keyEncAlg, new DerSequence(recipientEncryptedKeys))); }
public static AsymmetricKeyParameter CreateKey( SubjectPublicKeyInfo keyInfo) { AlgorithmIdentifier algID = keyInfo.AlgorithmID; DerObjectIdentifier algOid = algID.ObjectID; // TODO See RSAUtil.isRsaOid in Java build if (algOid.Equals(PkcsObjectIdentifiers.RsaEncryption) || algOid.Equals(X509ObjectIdentifiers.IdEARsa) || algOid.Equals(PkcsObjectIdentifiers.IdRsassaPss) || algOid.Equals(PkcsObjectIdentifiers.IdRsaesOaep)) { RsaPublicKeyStructure pubKey = RsaPublicKeyStructure.GetInstance( keyInfo.GetPublicKey()); return new RsaKeyParameters(false, pubKey.Modulus, pubKey.PublicExponent); } else if (algOid.Equals(X9ObjectIdentifiers.DHPublicNumber)) { Asn1Sequence seq = Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object()); DHPublicKey dhPublicKey = DHPublicKey.GetInstance(keyInfo.GetPublicKey()); BigInteger y = dhPublicKey.Y.Value; if (IsPkcsDHParam(seq)) return ReadPkcsDHParam(algOid, y, seq); DHDomainParameters dhParams = DHDomainParameters.GetInstance(seq); BigInteger p = dhParams.P.Value; BigInteger g = dhParams.G.Value; BigInteger q = dhParams.Q.Value; BigInteger j = null; if (dhParams.J != null) { j = dhParams.J.Value; } DHValidationParameters validation = null; DHValidationParms dhValidationParms = dhParams.ValidationParms; if (dhValidationParms != null) { byte[] seed = dhValidationParms.Seed.GetBytes(); BigInteger pgenCounter = dhValidationParms.PgenCounter.Value; // TODO Check pgenCounter size? validation = new DHValidationParameters(seed, pgenCounter.IntValue); } return new DHPublicKeyParameters(y, new DHParameters(p, g, q, j, validation)); } else if (algOid.Equals(PkcsObjectIdentifiers.DhKeyAgreement)) { Asn1Sequence seq = Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object()); DerInteger derY = (DerInteger) keyInfo.GetPublicKey(); return ReadPkcsDHParam(algOid, derY.Value, seq); } else if (algOid.Equals(OiwObjectIdentifiers.ElGamalAlgorithm)) { ElGamalParameter para = new ElGamalParameter( Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object())); DerInteger derY = (DerInteger) keyInfo.GetPublicKey(); return new ElGamalPublicKeyParameters( derY.Value, new ElGamalParameters(para.P, para.G)); } else if (algOid.Equals(X9ObjectIdentifiers.IdDsa) || algOid.Equals(OiwObjectIdentifiers.DsaWithSha1)) { DerInteger derY = (DerInteger) keyInfo.GetPublicKey(); Asn1Encodable ae = algID.Parameters; DsaParameters parameters = null; if (ae != null) { DsaParameter para = DsaParameter.GetInstance(ae.ToAsn1Object()); parameters = new DsaParameters(para.P, para.Q, para.G); } return new DsaPublicKeyParameters(derY.Value, parameters); } else if (algOid.Equals(X9ObjectIdentifiers.IdECPublicKey)) { X962Parameters para = new X962Parameters( algID.Parameters.ToAsn1Object()); X9ECParameters ecP; if (para.IsNamedCurve) { ecP = ECKeyPairGenerator.FindECCurveByOid((DerObjectIdentifier)para.Parameters); } else { ecP = new X9ECParameters((Asn1Sequence)para.Parameters); } ECDomainParameters dParams = new ECDomainParameters( ecP.Curve, ecP.G, ecP.N, ecP.H, ecP.GetSeed()); DerBitString bits = keyInfo.PublicKeyData; byte[] data = bits.GetBytes(); Asn1OctetString key = new DerOctetString(data); X9ECPoint derQ = new X9ECPoint(dParams.Curve, key); return new ECPublicKeyParameters(derQ.Point, dParams); } else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x2001)) { Gost3410PublicKeyAlgParameters gostParams = new Gost3410PublicKeyAlgParameters( (Asn1Sequence) algID.Parameters); Asn1OctetString key; try { key = (Asn1OctetString) keyInfo.GetPublicKey(); } catch (IOException) { throw new ArgumentException("invalid info structure in GOST3410 public key"); } byte[] keyEnc = key.GetOctets(); byte[] x = new byte[32]; byte[] y = new byte[32]; for (int i = 0; i != y.Length; i++) { x[i] = keyEnc[32 - 1 - i]; } for (int i = 0; i != x.Length; i++) { y[i] = keyEnc[64 - 1 - i]; } ECDomainParameters ecP = ECGost3410NamedCurves.GetByOid(gostParams.PublicKeyParamSet); if (ecP == null) return null; ECPoint q = ecP.Curve.CreatePoint(new BigInteger(1, x), new BigInteger(1, y), false); return new ECPublicKeyParameters("ECGOST3410", q, gostParams.PublicKeyParamSet); } else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x94)) { Gost3410PublicKeyAlgParameters algParams = new Gost3410PublicKeyAlgParameters( (Asn1Sequence) algID.Parameters); DerOctetString derY; try { derY = (DerOctetString) keyInfo.GetPublicKey(); } catch (IOException) { throw new ArgumentException("invalid info structure in GOST3410 public key"); } byte[] keyEnc = derY.GetOctets(); byte[] keyBytes = new byte[keyEnc.Length]; for (int i = 0; i != keyEnc.Length; i++) { keyBytes[i] = keyEnc[keyEnc.Length - 1 - i]; // was little endian } BigInteger y = new BigInteger(1, keyBytes); return new Gost3410PublicKeyParameters(y, algParams.PublicKeyParamSet); } else { throw new SecurityUtilityException("algorithm identifier in key not recognised: " + algOid); } }
/** * generate an enveloped object that contains an CMS Enveloped Data * object using the given provider and the passed in key generator. */ private CmsAuthenticatedData Generate( CmsProcessable content, string macOid, CipherKeyGenerator keyGen) { AlgorithmIdentifier macAlgId; KeyParameter encKey; Asn1OctetString encContent; Asn1OctetString macResult; try { // FIXME Will this work for macs? byte[] encKeyBytes = keyGen.GenerateKey(); encKey = ParameterUtilities.CreateKeyParameter(macOid, encKeyBytes); Asn1Encodable asn1Params = GenerateAsn1Parameters(macOid, encKeyBytes); ICipherParameters cipherParameters; macAlgId = GetAlgorithmIdentifier( macOid, encKey, asn1Params, out cipherParameters); IMac mac = MacUtilities.GetMac(macOid); // TODO Confirm no ParametersWithRandom needed // FIXME Only passing key at the moment // mac.Init(cipherParameters); mac.Init(encKey); MemoryStream bOut = new MemoryStream(); Stream mOut = new TeeOutputStream(bOut, new MacOutputStream(mac)); content.Write(mOut); mOut.Dispose(); bOut.Dispose(); encContent = new BerOctetString(bOut.ToArray()); byte[] macOctets = MacUtilities.DoFinal(mac); macResult = new DerOctetString(macOctets); } 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("exception decoding algorithm parameters.", e); } Asn1EncodableVector recipientInfos = new Asn1EncodableVector(); foreach (RecipientInfoGenerator rig in recipientInfoGenerators) { try { recipientInfos.Add(rig.Generate(encKey, rand)); } catch (InvalidKeyException e) { throw new CmsException("key inappropriate for algorithm.", e); } catch (GeneralSecurityException e) { throw new CmsException("error making encrypted content.", e); } } ContentInfo eci = new ContentInfo(CmsObjectIdentifiers.Data, encContent); ContentInfo contentInfo = new ContentInfo( CmsObjectIdentifiers.AuthenticatedData, new AuthenticatedData(null, new DerSet(recipientInfos), macAlgId, null, eci, null, macResult, null)); return new CmsAuthenticatedData(contentInfo); }