public override void PerformTest() { NamingAuthority auth = new NamingAuthority(new DerObjectIdentifier("1.2.3"), "url", new DirectoryString("fred")); DirectoryString[] professionItems = { new DirectoryString("substitution") }; DerObjectIdentifier[] professionOids = { new DerObjectIdentifier("1.2.3") }; string registrationNumber = "12345"; DerOctetString addProfInfo = new DerOctetString(new byte[20]); ProfessionInfo info = new ProfessionInfo(auth, professionItems, professionOids, registrationNumber, addProfInfo); checkConstruction(info, auth, professionItems, professionOids, registrationNumber, addProfInfo); info = new ProfessionInfo(null, professionItems, professionOids, registrationNumber, addProfInfo); checkConstruction(info, null, professionItems, professionOids, registrationNumber, addProfInfo); info = new ProfessionInfo(auth, professionItems, null, registrationNumber, addProfInfo); checkConstruction(info, auth, professionItems, null, registrationNumber, addProfInfo); info = new ProfessionInfo(auth, professionItems, professionOids, null, addProfInfo); checkConstruction(info, auth, professionItems, professionOids, null, addProfInfo); info = new ProfessionInfo(auth, professionItems, professionOids, registrationNumber, null); checkConstruction(info, auth, professionItems, professionOids, registrationNumber, null); info = ProfessionInfo.GetInstance(null); if (info != null) { Fail("null GetInstance() failed."); } try { ProcurationSyntax.GetInstance(new Object()); Fail("GetInstance() failed to detect bad object."); } catch (ArgumentException) { // expected } }
private void checkConstruction( ProfessionInfo profInfo, NamingAuthority auth, DirectoryString[] professionItems, DerObjectIdentifier[] professionOids, string registrationNumber, DerOctetString addProfInfo) { checkValues(profInfo, auth, professionItems, professionOids, registrationNumber, addProfInfo); profInfo = ProfessionInfo.GetInstance(profInfo); checkValues(profInfo, auth, professionItems, professionOids, registrationNumber, addProfInfo); Asn1InputStream aIn = new Asn1InputStream(profInfo.ToAsn1Object().GetEncoded()); Asn1Sequence seq = (Asn1Sequence) aIn.ReadObject(); profInfo = ProfessionInfo.GetInstance(seq); checkValues(profInfo, auth, professionItems, professionOids, registrationNumber, addProfInfo); }
public static byte[] PostSign(String digestAlgorithmName, byte[] content, X509Certificate2[] signerCertificateChain, byte[] signature, byte[] signedAttributes) { if (signerCertificateChain == null || signerCertificateChain.Length == 0) { throw new ArgumentException("La cadena de certificados debe contener al menos una entrada"); } TbsCertificateStructure tbsCertificateStructure; //TODO Revisar esta parte del cĂłdigo /** * * Revisar esta parte del cĂłdigo * */ tbsCertificateStructure = TbsCertificateStructure.GetInstance( Asn1Object.FromByteArray( new Org.BouncyCastle.X509.X509Certificate( X509CertificateStructure.GetInstance(Asn1Object.FromByteArray(signerCertificateChain[0].GetRawCertData()))).GetTbsCertificate() ) ); SignerIdentifier signerIdentifier = new SignerIdentifier( new IssuerAndSerialNumber(X509Name.GetInstance(tbsCertificateStructure.Issuer), tbsCertificateStructure.SerialNumber) ); // Algoritmo de huella digital AlgorithmIdentifier digestAlgorithmOID; digestAlgorithmOID = SigUtils.MakeAlgId(AOAlgorithmID.GetOID(digestAlgorithmName)); // EncryptionAlgorithm AlgorithmIdentifier keyAlgorithmIdentifier; keyAlgorithmIdentifier = SigUtils.MakeAlgId(AOAlgorithmID.GetOID("RSA")); // Firma PKCS#1 codificada Asn1OctetString encodedPKCS1Signature = new DerOctetString(signature); // Atributos firmados Asn1Set asn1SignedAttributes; asn1SignedAttributes = (Asn1Set)Asn1Object.FromByteArray(signedAttributes); // SignerInfo Asn1EncodableVector signerInfo = new Asn1EncodableVector(); signerInfo.Add(new SignerInfo(signerIdentifier, digestAlgorithmOID, asn1SignedAttributes, keyAlgorithmIdentifier, encodedPKCS1Signature, null)); // ContentInfo ContentInfo contentInfo; if (content != null) { MemoryStream baos = new MemoryStream(); CmsProcessable msg = new CmsProcessableByteArray(content); msg.Write(baos); contentInfo = new ContentInfo(new DerObjectIdentifier(Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.Data.Id), new BerOctetString(baos.ToArray())); } else { contentInfo = new ContentInfo(new DerObjectIdentifier(Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.Data.Id), null); } // Certificados List <Asn1Encodable> ce = new List <Asn1Encodable>(); foreach (X509Certificate2 cert in signerCertificateChain) { /** * * Revisar el uso que hacemos de X509CertificateStructure * ya que puede ser un posible punto de errores * */ ce.Add(X509CertificateStructure.GetInstance(Asn1Object.FromByteArray(cert.GetRawCertData()))); } Asn1Set certificates = SigUtils.CreateBerSetFromList(ce); // Algoritmos de huella digital Asn1EncodableVector digestAlgorithms = new Asn1EncodableVector(); digestAlgorithms.Add(digestAlgorithmOID); return(new ContentInfo( Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.SignedData, new SignedData( new DerSet(digestAlgorithms), contentInfo, certificates, null, new DerSet(signerInfo) ) ).GetEncoded("DER")); }
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 x9; if (para.IsNamedCurve) { x9 = ECKeyPairGenerator.FindECCurveByOid((DerObjectIdentifier)para.Parameters); } else { x9 = new X9ECParameters((Asn1Sequence)para.Parameters); } Asn1OctetString key = new DerOctetString(keyInfo.PublicKeyData.GetBytes()); X9ECPoint derQ = new X9ECPoint(x9.Curve, key); ECPoint q = derQ.Point; if (para.IsNamedCurve) { return new ECPublicKeyParameters("EC", q, (DerObjectIdentifier)para.Parameters); } ECDomainParameters dParams = new ECDomainParameters(x9.Curve, x9.G, x9.N, x9.H, x9.GetSeed()); return new ECPublicKeyParameters(q, 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)); 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.Close(); bOut.Close(); 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)); }
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(PkcsObjectIdentifiers.DhKeyAgreement) || algOid.Equals(X9ObjectIdentifiers.DHPublicNumber)) { DHParameter para = new DHParameter( Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object())); DerInteger derY = (DerInteger)keyInfo.GetPublicKey(); BigInteger lVal = para.L; int l = lVal == null ? 0 : lVal.IntValue; DHParameters dhParams = new DHParameters(para.P, para.G, null, l); return(new DHPublicKeyParameters(derY.Value, dhParams)); } 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) { // TODO ECGost3410NamedCurves support (returns ECDomainParameters though) DerObjectIdentifier oid = (DerObjectIdentifier)para.Parameters; ecP = X962NamedCurves.GetByOid(oid); if (ecP == null) { ecP = SecNamedCurves.GetByOid(oid); if (ecP == null) { ecP = NistNamedCurves.GetByOid(oid); if (ecP == null) { ecP = TeleTrusTNamedCurves.GetByOid(oid); } } } } 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(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); } }
public static AsymmetricKeyParameter CreateKey( SubjectPublicKeyInfo keyInfo) { AlgorithmIdentifier algID = keyInfo.AlgorithmID; DerObjectIdentifier algOid = algID.Algorithm; // 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 x9; if (para.IsNamedCurve) { x9 = ECKeyPairGenerator.FindECCurveByOid((DerObjectIdentifier)para.Parameters); } else { x9 = new X9ECParameters((Asn1Sequence)para.Parameters); } Asn1OctetString key = new DerOctetString(keyInfo.PublicKeyData.GetBytes()); X9ECPoint derQ = new X9ECPoint(x9.Curve, key); ECPoint q = derQ.Point; if (para.IsNamedCurve) { return(new ECPublicKeyParameters("EC", q, (DerObjectIdentifier)para.Parameters)); } ECDomainParameters dParams = new ECDomainParameters(x9.Curve, x9.G, x9.N, x9.H, x9.GetSeed()); return(new ECPublicKeyParameters(q, 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)); 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); } }
/** * This method provides that encoding and the parameters must be * exactly the same as in {@link #getEncodedPKCS7(byte[],Calendar)}. * * @param secondDigest the content digest * @param signingTime the signing time * @return the byte array representation of the authenticatedAttributes ready to be signed */ private DerSet GetAuthenticatedAttributeSet(byte[] secondDigest, DateTime signingTime, byte[] ocsp, ICollection <byte[]> crlBytes, bool cades) { Asn1EncodableVector attribute = new Asn1EncodableVector(); Asn1EncodableVector v = new Asn1EncodableVector(); v.Add(new DerObjectIdentifier(SecurityIDs.ID_CONTENT_TYPE)); v.Add(new DerSet(new DerObjectIdentifier(SecurityIDs.ID_PKCS7_DATA))); attribute.Add(new DerSequence(v)); v = new Asn1EncodableVector(); v.Add(new DerObjectIdentifier(SecurityIDs.ID_SIGNING_TIME)); v.Add(new DerSet(new DerUtcTime(signingTime))); attribute.Add(new DerSequence(v)); v = new Asn1EncodableVector(); v.Add(new DerObjectIdentifier(SecurityIDs.ID_MESSAGE_DIGEST)); v.Add(new DerSet(new DerOctetString(secondDigest))); attribute.Add(new DerSequence(v)); bool haveCrl = false; if (crlBytes != null) { foreach (byte[] bCrl in crlBytes) { if (bCrl != null) { haveCrl = true; break; } } } if (ocsp != null || haveCrl) { v = new Asn1EncodableVector(); v.Add(new DerObjectIdentifier(SecurityIDs.ID_ADBE_REVOCATION)); Asn1EncodableVector revocationV = new Asn1EncodableVector(); if (haveCrl) { Asn1EncodableVector v2 = new Asn1EncodableVector(); foreach (byte[] bCrl in crlBytes) { if (bCrl == null) { continue; } Asn1InputStream t = new Asn1InputStream(bCrl); v2.Add(t.ReadObject()); } revocationV.Add(new DerTaggedObject(true, 0, new DerSequence(v2))); } if (ocsp != null) { DerOctetString doctet = new DerOctetString(ocsp); Asn1EncodableVector vo1 = new Asn1EncodableVector(); Asn1EncodableVector v2 = new Asn1EncodableVector(); v2.Add(OcspObjectIdentifiers.PkixOcspBasic); v2.Add(doctet); DerEnumerated den = new DerEnumerated(0); Asn1EncodableVector v3 = new Asn1EncodableVector(); v3.Add(den); v3.Add(new DerTaggedObject(true, 0, new DerSequence(v2))); vo1.Add(new DerSequence(v3)); revocationV.Add(new DerTaggedObject(true, 1, new DerSequence(vo1))); } v.Add(new DerSet(new DerSequence(revocationV))); attribute.Add(new DerSequence(v)); } if (cades) { v = new Asn1EncodableVector(); v.Add(new DerObjectIdentifier(SecurityIDs.ID_AA_SIGNING_CERTIFICATE_V2)); Asn1EncodableVector aaV2 = new Asn1EncodableVector(); AlgorithmIdentifier algoId = new AlgorithmIdentifier(new DerObjectIdentifier(digestAlgorithmOid), null); aaV2.Add(algoId); byte[] dig = PdfEncryption.DigestComputeHash(GetHashAlgorithm(), signCert.GetEncoded()); aaV2.Add(new DerOctetString(dig)); v.Add(new DerSet(new DerSequence(new DerSequence(new DerSequence(aaV2))))); attribute.Add(new DerSequence(v)); } return(new DerSet(attribute)); }
private CmsAuthenticatedData Generate(CmsProcessable content, string macOid, CipherKeyGenerator keyGen) { //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Expected O, but got Unknown //IL_009f: Expected O, but got Unknown KeyParameter keyParameter; AlgorithmIdentifier algorithmIdentifier; Asn1OctetString content2; Asn1OctetString mac2; try { byte[] array = keyGen.GenerateKey(); keyParameter = ParameterUtilities.CreateKeyParameter(macOid, array); Asn1Encodable asn1Params = GenerateAsn1Parameters(macOid, array); algorithmIdentifier = GetAlgorithmIdentifier(macOid, keyParameter, asn1Params, out var _); IMac mac = MacUtilities.GetMac(macOid); mac.Init(keyParameter); MemoryStream val = new MemoryStream(); Stream val2 = (Stream)(object)new TeeOutputStream((Stream)(object)val, (Stream)(object)new MacOutputStream(mac)); content.Write(val2); Platform.Dispose(val2); content2 = new BerOctetString(val.ToArray()); byte[] str = MacUtilities.DoFinal(mac); mac2 = new DerOctetString(str); } catch (SecurityUtilityException e) { throw new CmsException("couldn't create cipher.", e); } catch (InvalidKeyException e2) { throw new CmsException("key invalid in message.", e2); } catch (IOException val3) { IOException e3 = val3; throw new CmsException("exception decoding algorithm parameters.", (global::System.Exception)(object) e3); } Asn1EncodableVector asn1EncodableVector = new Asn1EncodableVector(); global::System.Collections.IEnumerator enumerator = ((global::System.Collections.IEnumerable)recipientInfoGenerators).GetEnumerator(); try { while (enumerator.MoveNext()) { RecipientInfoGenerator recipientInfoGenerator = (RecipientInfoGenerator)enumerator.get_Current(); try { asn1EncodableVector.Add(recipientInfoGenerator.Generate(keyParameter, rand)); } catch (InvalidKeyException e4) { throw new CmsException("key inappropriate for algorithm.", e4); } catch (GeneralSecurityException e5) { throw new CmsException("error making encrypted content.", e5); } } } finally { global::System.IDisposable disposable = enumerator as global::System.IDisposable; if (disposable != null) { disposable.Dispose(); } } ContentInfo encapsulatedContent = new ContentInfo(CmsObjectIdentifiers.Data, content2); ContentInfo contentInfo = new ContentInfo(CmsObjectIdentifiers.AuthenticatedData, new AuthenticatedData(null, new DerSet(asn1EncodableVector), algorithmIdentifier, null, encapsulatedContent, null, mac2, null)); return(new CmsAuthenticatedData(contentInfo)); }
private void EncodePublicKey() { X9ECParameters ecP = X962NamedCurves.GetByOid(X9ObjectIdentifiers.Prime239v3); if (X9IntegerConverter.GetByteLength(ecP.Curve) != 30) { Fail("wrong byte length reported for curve"); } if (ecP.Curve.FieldSize != 239) { Fail("wrong field size reported for curve"); } // // named curve // X962Parameters _params = new X962Parameters(X9ObjectIdentifiers.Prime192v1); ECPoint point = ecP.G.Multiply(BigInteger.ValueOf(100)); DerOctetString p = new DerOctetString(point.GetEncoded(true)); SubjectPublicKeyInfo info = new SubjectPublicKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.IdECPublicKey, _params), p.GetOctets()); if (!Arrays.AreEqual(info.GetEncoded(), namedPub)) { Fail("failed public named generation"); } X9ECPoint x9P = new X9ECPoint(ecP.Curve, p); if (!Arrays.AreEqual(p.GetOctets(), x9P.Point.GetEncoded())) { Fail("point encoding not preserved"); } Asn1Object o = Asn1Object.FromByteArray(namedPub); if (!info.Equals(o)) { Fail("failed public named equality"); } // // explicit curve parameters // _params = new X962Parameters(ecP); info = new SubjectPublicKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.IdECPublicKey, _params), p.GetOctets()); if (!Arrays.AreEqual(info.GetEncoded(), expPub)) { Fail("failed public explicit generation"); } o = Asn1Object.FromByteArray(expPub); if (!info.Equals(o)) { Fail("failed public explicit equality"); } }
public SeSeal SetCert(byte[] cert) { Cert = new DerOctetString(cert); return(this); }
private void CheckAttribute(byte[] expected, Asn1.Cms.Attribute attr) { DerOctetString value = (DerOctetString)attr.AttrValues[0]; Assert.AreEqual(new DerOctetString(expected), value); }
internal Asn1.Cms.SignerInfo ToSignerInfo( DerObjectIdentifier contentType, CmsProcessable content) { AlgorithmIdentifier digAlgId = new AlgorithmIdentifier( new DerObjectIdentifier(this.DigestAlgOid), DerNull.Instance); AlgorithmIdentifier encAlgId = CmsSignedGenerator.GetEncAlgorithmIdentifier(this.EncryptionAlgOid); string digestName = Helper.GetDigestAlgName(digestOID); string signatureName = digestName + "with" + Helper.GetEncryptionAlgName(encOID); ISigner sig = Helper.GetSignatureInstance(signatureName); IDigest dig = Helper.GetDigestInstance(digestName); byte[] hash = null; if (content != null) { content.Write(new DigOutputStream(dig)); hash = DigestUtilities.DoFinal(dig); outer._digests.Add(digestOID, hash.Clone()); } IDictionary parameters = outer.GetBaseParameters(contentType, digAlgId, hash); Asn1.Cms.AttributeTable signed = (sAttr != null) // ? sAttr.GetAttributes(Collections.unmodifiableMap(parameters)) ? sAttr.GetAttributes(parameters) : null; Asn1Set signedAttr = outer.GetAttributeSet(signed); // // sig must be composed from the DER encoding. // byte[] tmp; if (signedAttr != null) { tmp = signedAttr.GetDerEncoded(); } else { MemoryStream bOut = new MemoryStream(); content.Write(bOut); tmp = bOut.ToArray(); } sig.Init(true, key); sig.BlockUpdate(tmp, 0, tmp.Length); Asn1OctetString encDigest = new DerOctetString(sig.GenerateSignature()); IDictionary baseParameters = outer.GetBaseParameters(contentType, digAlgId, hash); baseParameters[CmsAttributeTableParameter.Signature] = encDigest.GetOctets().Clone(); Asn1.Cms.AttributeTable unsigned = (unsAttr != null) // ? unsAttr.GetAttributes(Collections.unmodifiableMap(baseParameters)) ? unsAttr.GetAttributes(baseParameters) : null; Asn1Set unsignedAttr = outer.GetAttributeSet(unsigned); X509Certificate cert = this.GetCertificate(); TbsCertificateStructure tbs = TbsCertificateStructure.GetInstance( Asn1Object.FromByteArray(cert.GetTbsCertificate())); Asn1.Cms.IssuerAndSerialNumber encSid = new Asn1.Cms.IssuerAndSerialNumber( tbs.Issuer, tbs.SerialNumber.Value); return(new Asn1.Cms.SignerInfo(new SignerIdentifier(encSid), digAlgId, signedAttr, encAlgId, encDigest, unsignedAttr)); }
public static AsymmetricKeyParameter CreateKey(PrivateKeyInfo keyInfo) { AlgorithmIdentifier privateKeyAlgorithm = keyInfo.PrivateKeyAlgorithm; DerObjectIdentifier objectID = privateKeyAlgorithm.ObjectID; if (objectID.Equals(PkcsObjectIdentifiers.RsaEncryption) || objectID.Equals(X509ObjectIdentifiers.IdEARsa) || objectID.Equals(PkcsObjectIdentifiers.IdRsassaPss) || objectID.Equals(PkcsObjectIdentifiers.IdRsaesOaep)) { RsaPrivateKeyStructure instance = RsaPrivateKeyStructure.GetInstance(keyInfo.ParsePrivateKey()); return(new RsaPrivateCrtKeyParameters(instance.Modulus, instance.PublicExponent, instance.PrivateExponent, instance.Prime1, instance.Prime2, instance.Exponent1, instance.Exponent2, instance.Coefficient)); } if (objectID.Equals(PkcsObjectIdentifiers.DhKeyAgreement)) { DHParameter dHParameter = new DHParameter(Asn1Sequence.GetInstance(privateKeyAlgorithm.Parameters.ToAsn1Object())); DerInteger derInteger = (DerInteger)keyInfo.ParsePrivateKey(); BigInteger l = dHParameter.L; int l2 = (l == null) ? 0 : l.IntValue; DHParameters parameters = new DHParameters(dHParameter.P, dHParameter.G, null, l2); return(new DHPrivateKeyParameters(derInteger.Value, parameters, objectID)); } if (objectID.Equals(OiwObjectIdentifiers.ElGamalAlgorithm)) { ElGamalParameter elGamalParameter = new ElGamalParameter(Asn1Sequence.GetInstance(privateKeyAlgorithm.Parameters.ToAsn1Object())); DerInteger derInteger2 = (DerInteger)keyInfo.ParsePrivateKey(); return(new ElGamalPrivateKeyParameters(derInteger2.Value, new ElGamalParameters(elGamalParameter.P, elGamalParameter.G))); } if (objectID.Equals(X9ObjectIdentifiers.IdDsa)) { DerInteger derInteger3 = (DerInteger)keyInfo.ParsePrivateKey(); Asn1Encodable parameters2 = privateKeyAlgorithm.Parameters; DsaParameters parameters3 = null; if (parameters2 != null) { DsaParameter instance2 = DsaParameter.GetInstance(parameters2.ToAsn1Object()); parameters3 = new DsaParameters(instance2.P, instance2.Q, instance2.G); } return(new DsaPrivateKeyParameters(derInteger3.Value, parameters3)); } if (objectID.Equals(X9ObjectIdentifiers.IdECPublicKey)) { X962Parameters x962Parameters = new X962Parameters(privateKeyAlgorithm.Parameters.ToAsn1Object()); X9ECParameters x9ECParameters; if (x962Parameters.IsNamedCurve) { x9ECParameters = ECKeyPairGenerator.FindECCurveByOid((DerObjectIdentifier)x962Parameters.Parameters); } else { x9ECParameters = new X9ECParameters((Asn1Sequence)x962Parameters.Parameters); } ECPrivateKeyStructure eCPrivateKeyStructure = new ECPrivateKeyStructure(Asn1Sequence.GetInstance(keyInfo.ParsePrivateKey())); BigInteger key = eCPrivateKeyStructure.GetKey(); if (x962Parameters.IsNamedCurve) { return(new ECPrivateKeyParameters("EC", key, (DerObjectIdentifier)x962Parameters.Parameters)); } ECDomainParameters parameters4 = new ECDomainParameters(x9ECParameters.Curve, x9ECParameters.G, x9ECParameters.N, x9ECParameters.H, x9ECParameters.GetSeed()); return(new ECPrivateKeyParameters(key, parameters4)); } else if (objectID.Equals(CryptoProObjectIdentifiers.GostR3410x2001)) { Gost3410PublicKeyAlgParameters gost3410PublicKeyAlgParameters = new Gost3410PublicKeyAlgParameters(Asn1Sequence.GetInstance(privateKeyAlgorithm.Parameters.ToAsn1Object())); Asn1Object asn1Object = keyInfo.ParsePrivateKey(); ECPrivateKeyStructure eCPrivateKeyStructure2; if (asn1Object is DerInteger) { eCPrivateKeyStructure2 = new ECPrivateKeyStructure(((DerInteger)asn1Object).Value); } else { eCPrivateKeyStructure2 = ECPrivateKeyStructure.GetInstance(asn1Object); } if (ECGost3410NamedCurves.GetByOid(gost3410PublicKeyAlgParameters.PublicKeyParamSet) == null) { throw new ArgumentException("Unrecognized curve OID for GostR3410x2001 private key"); } return(new ECPrivateKeyParameters("ECGOST3410", eCPrivateKeyStructure2.GetKey(), gost3410PublicKeyAlgParameters.PublicKeyParamSet)); } else { if (objectID.Equals(CryptoProObjectIdentifiers.GostR3410x94)) { Gost3410PublicKeyAlgParameters gost3410PublicKeyAlgParameters2 = new Gost3410PublicKeyAlgParameters(Asn1Sequence.GetInstance(privateKeyAlgorithm.Parameters.ToAsn1Object())); DerOctetString derOctetString = (DerOctetString)keyInfo.ParsePrivateKey(); BigInteger x = new BigInteger(1, Arrays.Reverse(derOctetString.GetOctets())); return(new Gost3410PrivateKeyParameters(x, gost3410PublicKeyAlgParameters2.PublicKeyParamSet)); } throw new SecurityUtilityException("algorithm identifier in key not recognised"); } }
internal RecipientInfo ToRecipientInfo( KeyParameter key, SecureRandom random) { byte[] keyBytes = key.GetKey(); if (pubKey != null) { IWrapper keyWrapper = Helper.CreateWrapper(keyEncAlg.ObjectID.Id); keyWrapper.Init(true, new ParametersWithRandom(pubKey, random)); Asn1OctetString encKey = new DerOctetString( keyWrapper.Wrap(keyBytes, 0, keyBytes.Length)); RecipientIdentifier recipId; if (cert != null) { TbsCertificateStructure tbs = TbsCertificateStructure.GetInstance( Asn1Object.FromByteArray(cert.GetTbsCertificate())); Asn1.Cms.IssuerAndSerialNumber encSid = new Asn1.Cms.IssuerAndSerialNumber( tbs.Issuer, tbs.SerialNumber.Value); recipId = new RecipientIdentifier(encSid); } else { recipId = new RecipientIdentifier(subKeyId); } return(new RecipientInfo(new KeyTransRecipientInfo(recipId, keyEncAlg, encKey))); } else if (originator != null) { IWrapper keyWrapper = Helper.CreateWrapper( DerObjectIdentifier.GetInstance( Asn1Sequence.GetInstance(keyEncAlg.Parameters)[0]).Id); keyWrapper.Init(true, new ParametersWithRandom(secKey, random)); Asn1OctetString encKey = new DerOctetString( keyWrapper.Wrap(keyBytes, 0, keyBytes.Length)); RecipientEncryptedKey rKey = new RecipientEncryptedKey( new KeyAgreeRecipientIdentifier( new Asn1.Cms.IssuerAndSerialNumber( PrincipalUtilities.GetIssuerX509Principal(cert), cert.SerialNumber)), encKey); return(new RecipientInfo( new KeyAgreeRecipientInfo(originator, ukm, keyEncAlg, new DerSequence(rKey)))); } else if (derivationAlg != null) { string rfc3211WrapperName = Helper.GetRfc3211WrapperName(secKeyAlgorithm); 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(secKey, iv); keyWrapper.Init(true, new ParametersWithRandom(parameters, random)); Asn1OctetString encKey = new DerOctetString( keyWrapper.Wrap(keyBytes, 0, keyBytes.Length)); // byte[] iv = keyWrapper.GetIV(); DerSequence seq = new DerSequence( new DerObjectIdentifier(secKeyAlgorithm), new DerOctetString(iv)); keyEncAlg = new AlgorithmIdentifier(PkcsObjectIdentifiers.IdAlgPwriKek, seq); return(new RecipientInfo(new PasswordRecipientInfo(derivationAlg, keyEncAlg, encKey))); } else { IWrapper keyWrapper = Helper.CreateWrapper(keyEncAlg.ObjectID.Id); keyWrapper.Init(true, new ParametersWithRandom(secKey, random)); Asn1OctetString encKey = new DerOctetString( keyWrapper.Wrap(keyBytes, 0, keyBytes.Length)); return(new RecipientInfo(new KekRecipientInfo(secKeyId, keyEncAlg, encKey))); } }
/// <summary> /// Create a CSR and submit it to the Acme server for signing. Returns the certificate chain. /// </summary> /// <param name="domains">The list of domains that this certificate will be for. The first domain listed will be the CommonName.</param> /// <param name="keyPair">The RSA key pair for signing the certificate request, this is the key that will be used in conjunction with the certificate.</param> /// <returns>A tuple whose first value is the private key data and whose second value is a list of certificates. Everything is encoded in DER format, the first certificate is the signed certificate.</returns> public Tuple <byte[], List <byte[]> > GetCertificate(ICollection <string> domains) { // // Generate a new key for the certificate. // var generator = new RsaKeyPairGenerator(); generator.Init(new KeyGenerationParameters(new SecureRandom(), 2048)); var keyPair = generator.GenerateKeyPair(); var sig = new Asn1SignatureFactory("SHA256WITHRSA", keyPair.Private); var commonName = new X509Name(new DerObjectIdentifier[] { X509Name.CN }, new string[] { domains.First() }); // // Generate the list of subject alternative names. // List <GeneralName> names = new List <GeneralName>(); foreach (var domain in domains) { names.Add(new GeneralName(GeneralName.DnsName, domain)); } var sanOctect = new DerOctetString(new GeneralNames(names.ToArray())); var sanSequence = new DerSequence(X509Extensions.SubjectAlternativeName, sanOctect); var extensionSet = new DerSet(new DerSequence(sanSequence)); var attributes = new DerSet(new DerSequence(PkcsObjectIdentifiers.Pkcs9AtExtensionRequest, extensionSet)); // // Generate the CSR from all the data. // var csr = new Pkcs10CertificationRequest(sig, commonName, keyPair.Public, attributes, keyPair.Private); var payload = new { resource = "new-cert", csr = UrlBase64Encode(csr.GetDerEncoded()) }; var certificates = new List <X509Certificate>(); var certParser = new X509CertificateParser(); byte[] certData; // // Send the request and fetch the certificate data. // certData = SendMessage <byte[]>(Directory.NewCert, payload, GetNonce(), out WebHeaderCollection headers); certificates.Add(certParser.ReadCertificate(certData)); // // Fetch all the certificates in the chain. // foreach (var link in headers.GetValues("Link")) { var match = System.Text.RegularExpressions.Regex.Match(link, "\\<(.*)\\>;rel=\"(.*)\""); if (match.Success && match.Groups[2].Value == "up") { certData = GetRequest <byte[]>(match.Groups[1].Value); certificates.Add(certParser.ReadCertificate(certData)); } } var privateKeyData = PrivateKeyInfoFactory.CreatePrivateKeyInfo(keyPair.Private).ToAsn1Object().GetDerEncoded(); var certificateData = certificates.Select(c => c.GetEncoded()).ToList(); return(new Tuple <byte[], List <byte[]> >(privateKeyData, certificateData)); }
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)))); }
/// <summary> /// Adds or removes Content to P7mFile /// </summary> /// <param name="CmsData">Signature Info</param> /// <param name="File">File, if null returns only Signature Info</param> /// <returns></returns> public static byte[] EmbedFileToPkcs(byte[] CmsData, byte[] File) { DerObjectIdentifier contentTypeOID = CmsObjectIdentifiers.Data; Asn1EncodableVector digestAlgs = new Asn1EncodableVector(); Asn1EncodableVector signerInfos = new Asn1EncodableVector(); Asn1OctetString octs = null; if (File != null) { octs = new DerOctetString(File); } Org.BouncyCastle.Asn1.Cms.ContentInfo encInfo = new Org.BouncyCastle.Asn1.Cms.ContentInfo(contentTypeOID, octs); CmsProcessable content = new CmsProcessableByteArray(CmsData); Asn1Set certificates = null; Asn1Set certrevlist = null; ArrayList _certs = new ArrayList(); ArrayList _crls = new ArrayList(); ICollection certsColl = new ArrayList(); ICollection crlsColl = new ArrayList(); CmsSignedData cms = new CmsSignedData(CmsData); SignerInformationStore signers = cms.GetSignerInfos(); IX509Store store = cms.GetCertificates("Collection"); IX509Store crls = cms.GetCrls("Collection"); certsColl = store.GetMatches(null); crlsColl = crls.GetMatches(null); foreach (SignerInformation signer in signers.GetSigners()) { //digestAlgs.Add(Helper.FixAlgID(signer.DigestAlgorithmID)); digestAlgs.Add(signer.DigestAlgorithmID); signerInfos.Add(signer.ToSignerInfo()); } foreach (Org.BouncyCastle.X509.X509Certificate cert in certsColl) { _certs.Add(Asn1Object.FromByteArray(cert.GetEncoded())); } foreach (Org.BouncyCastle.X509.X509Certificate clr in crlsColl) { _crls.Add(Asn1Object.FromByteArray(clr.GetEncoded())); } if (_certs.Count != 0) { certificates = CreateBerSetFromList(_certs); } if (_crls.Count != 0) { certrevlist = CreateBerSetFromList(_crls); } SignedData sd = new SignedData( new DerSet(digestAlgs), encInfo, certificates, certrevlist, new DerSet(signerInfos)); Org.BouncyCastle.Asn1.Cms.ContentInfo contentInfo = new Org.BouncyCastle.Asn1.Cms.ContentInfo(CmsObjectIdentifiers.SignedData, sd); byte[] retval = new CmsSignedData(content, contentInfo.GetDerEncoded()).GetEncoded(); string asn = BitConverter.ToString(retval).Replace("-", ""); return(retval); }
public virtual PkiHeaderBuilder SetRecipKID(DerOctetString kid) { recipKID = kid; return(this); }
public static AsymmetricKeyParameter CreateKey( SubjectPublicKeyInfo keyInfo) { AlgorithmIdentifier algID = keyInfo.AlgorithmID; DerObjectIdentifier algOid = algID.Algorithm; // 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.ParsePublicKey()); 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.ParsePublicKey()); 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.ParsePublicKey(); 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.ParsePublicKey(); 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.ParsePublicKey(); 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 x9; if (para.IsNamedCurve) { x9 = ECKeyPairGenerator.FindECCurveByOid((DerObjectIdentifier)para.Parameters); } else { x9 = new X9ECParameters((Asn1Sequence)para.Parameters); } Asn1OctetString key = new DerOctetString(keyInfo.PublicKeyData.GetBytes()); X9ECPoint derQ = new X9ECPoint(x9.Curve, key); ECPoint q = derQ.Point; if (para.IsNamedCurve) { return(new ECPublicKeyParameters("EC", q, (DerObjectIdentifier)para.Parameters)); } ECDomainParameters dParams = new ECDomainParameters(x9.Curve, x9.G, x9.N, x9.H, x9.GetSeed()); return(new ECPublicKeyParameters(q, dParams)); } else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x2001)) { Gost3410PublicKeyAlgParameters gostParams = Gost3410PublicKeyAlgParameters.GetInstance(algID.Parameters); DerObjectIdentifier publicKeyParamSet = gostParams.PublicKeyParamSet; ECDomainParameters ecP = ECGost3410NamedCurves.GetByOid(publicKeyParamSet); if (ecP == null) { return(null); } Asn1OctetString key; try { key = (Asn1OctetString)keyInfo.ParsePublicKey(); } catch (IOException e) { throw new ArgumentException("error recovering GOST3410_2001 public key", e); } int fieldSize = 32; int keySize = 2 * fieldSize; byte[] keyEnc = key.GetOctets(); if (keyEnc.Length != keySize) { throw new ArgumentException("invalid length for GOST3410_2001 public key"); } byte[] x9Encoding = new byte[1 + keySize]; x9Encoding[0] = 0x04; for (int i = 1; i <= fieldSize; ++i) { x9Encoding[i] = keyEnc[fieldSize - i]; x9Encoding[i + fieldSize] = keyEnc[keySize - i]; } ECPoint q = ecP.Curve.DecodePoint(x9Encoding); return(new ECPublicKeyParameters("ECGOST3410", q, publicKeyParamSet)); } else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x94)) { Gost3410PublicKeyAlgParameters algParams = Gost3410PublicKeyAlgParameters.GetInstance(algID.Parameters); Asn1OctetString key; try { key = (Asn1OctetString)keyInfo.ParsePublicKey(); } catch (IOException e) { throw new ArgumentException("error recovering GOST3410_94 public key", e); } byte[] keyBytes = Arrays.Reverse(key.GetOctets()); // was little endian BigInteger y = new BigInteger(1, keyBytes); return(new Gost3410PublicKeyParameters(y, algParams.PublicKeyParamSet)); } else if (algOid.Equals(EdECObjectIdentifiers.id_X25519)) { return(new X25519PublicKeyParameters(GetRawKey(keyInfo, X25519PublicKeyParameters.KeySize), 0)); } else if (algOid.Equals(EdECObjectIdentifiers.id_X448)) { return(new X448PublicKeyParameters(GetRawKey(keyInfo, X448PublicKeyParameters.KeySize), 0)); } else if (algOid.Equals(EdECObjectIdentifiers.id_Ed25519)) { return(new Ed25519PublicKeyParameters(GetRawKey(keyInfo, Ed25519PublicKeyParameters.KeySize), 0)); } else if (algOid.Equals(EdECObjectIdentifiers.id_Ed448)) { return(new Ed448PublicKeyParameters(GetRawKey(keyInfo, Ed448PublicKeyParameters.KeySize), 0)); } else if (algOid.Equals(RosstandartObjectIdentifiers.id_tc26_gost_3410_12_256) || algOid.Equals(RosstandartObjectIdentifiers.id_tc26_gost_3410_12_512)) { Gost3410PublicKeyAlgParameters gostParams = Gost3410PublicKeyAlgParameters.GetInstance(algID.Parameters); DerObjectIdentifier publicKeyParamSet = gostParams.PublicKeyParamSet; ECGost3410Parameters ecDomainParameters = new ECGost3410Parameters( new ECNamedDomainParameters(publicKeyParamSet, ECGost3410NamedCurves.GetByOid(publicKeyParamSet)), publicKeyParamSet, gostParams.DigestParamSet, gostParams.EncryptionParamSet); Asn1OctetString key; try { key = (Asn1OctetString)keyInfo.ParsePublicKey(); } catch (IOException e) { throw new ArgumentException("error recovering GOST3410_2012 public key", e); } int fieldSize = 32; if (algOid.Equals(RosstandartObjectIdentifiers.id_tc26_gost_3410_12_512)) { fieldSize = 64; } int keySize = 2 * fieldSize; byte[] keyEnc = key.GetOctets(); if (keyEnc.Length != keySize) { throw new ArgumentException("invalid length for GOST3410_2012 public key"); } byte[] x9Encoding = new byte[1 + keySize]; x9Encoding[0] = 0x04; for (int i = 1; i <= fieldSize; ++i) { x9Encoding[i] = keyEnc[fieldSize - i]; x9Encoding[i + fieldSize] = keyEnc[keySize - i]; } ECPoint q = ecDomainParameters.Curve.DecodePoint(x9Encoding); return(new ECPublicKeyParameters(q, ecDomainParameters)); } else { throw new SecurityUtilityException("algorithm identifier in public key not recognised: " + algOid); } }
public static IAsymmetricKeyParameter CreateKey( PrivateKeyInfo 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)) { RsaPrivateKeyStructure keyStructure = new RsaPrivateKeyStructure( Asn1Sequence.GetInstance(keyInfo.PrivateKey)); return(new RsaPrivateCrtKeyParameters( keyStructure.Modulus, keyStructure.PublicExponent, keyStructure.PrivateExponent, keyStructure.Prime1, keyStructure.Prime2, keyStructure.Exponent1, keyStructure.Exponent2, keyStructure.Coefficient)); } // TODO? // else if (algOid.Equals(X9ObjectIdentifiers.DHPublicNumber)) else if (algOid.Equals(PkcsObjectIdentifiers.DhKeyAgreement)) { DHParameter para = new DHParameter( Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object())); DerInteger derX = (DerInteger)keyInfo.PrivateKey; IBigInteger lVal = para.L; int l = lVal == null ? 0 : lVal.IntValue; DHParameters dhParams = new DHParameters(para.P, para.G, null, l); return(new DHPrivateKeyParameters(derX.Value, dhParams, algOid)); } else if (algOid.Equals(OiwObjectIdentifiers.ElGamalAlgorithm)) { ElGamalParameter para = new ElGamalParameter( Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object())); DerInteger derX = (DerInteger)keyInfo.PrivateKey; return(new ElGamalPrivateKeyParameters( derX.Value, new ElGamalParameters(para.P, para.G))); } else if (algOid.Equals(X9ObjectIdentifiers.IdDsa)) { DerInteger derX = (DerInteger)keyInfo.PrivateKey; 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 DsaPrivateKeyParameters(derX.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()); ECPrivateKeyStructure ec = new ECPrivateKeyStructure( Asn1Sequence.GetInstance(keyInfo.PrivateKey)); return(new ECPrivateKeyParameters(ec.GetKey(), dParams)); } else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x2001)) { Gost3410PublicKeyAlgParameters gostParams = new Gost3410PublicKeyAlgParameters( Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object())); ECPrivateKeyStructure ec = new ECPrivateKeyStructure( Asn1Sequence.GetInstance(keyInfo.PrivateKey)); ECDomainParameters ecP = ECGost3410NamedCurves.GetByOid(gostParams.PublicKeyParamSet); if (ecP == null) { return(null); } return(new ECPrivateKeyParameters("ECGOST3410", ec.GetKey(), gostParams.PublicKeyParamSet)); } else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x94)) { Gost3410PublicKeyAlgParameters gostParams = new Gost3410PublicKeyAlgParameters( Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object())); DerOctetString derX = (DerOctetString)keyInfo.PrivateKey; byte[] keyEnc = derX.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 } IBigInteger x = new BigInteger(1, keyBytes); return(new Gost3410PrivateKeyParameters(x, gostParams.PublicKeyParamSet)); } else { throw new SecurityUtilityException("algorithm identifier in key not recognised"); } }
public static AsymmetricKeyParameter CreateKey( PrivateKeyInfo keyInfo) { AlgorithmIdentifier algID = keyInfo.AlgorithmID; if (algID.ObjectID.Equals(PkcsObjectIdentifiers.RsaEncryption)) { RsaPrivateKeyStructure keyStructure = new RsaPrivateKeyStructure( (Asn1Sequence)keyInfo.PrivateKey); return(new RsaPrivateCrtKeyParameters( keyStructure.Modulus, keyStructure.PublicExponent, keyStructure.PrivateExponent, keyStructure.Prime1, keyStructure.Prime2, keyStructure.Exponent1, keyStructure.Exponent2, keyStructure.Coefficient)); } else if (algID.ObjectID.Equals(PkcsObjectIdentifiers.DhKeyAgreement)) { DHParameter para = new DHParameter((Asn1Sequence)algID.Parameters); DerInteger derX = (DerInteger)keyInfo.PrivateKey; return(new DHPrivateKeyParameters(derX.Value, new DHParameters(para.P, para.G))); } else if (algID.ObjectID.Equals(OiwObjectIdentifiers.ElGamalAlgorithm)) { ElGamalParameter para = new ElGamalParameter((Asn1Sequence)algID.Parameters); DerInteger derX = (DerInteger)keyInfo.PrivateKey; return(new ElGamalPrivateKeyParameters(derX.Value, new ElGamalParameters(para.P, para.G))); } else if (algID.ObjectID.Equals(X9ObjectIdentifiers.IdDsa)) { DsaParameter para = DsaParameter.GetInstance(algID.Parameters); DerInteger derX = (DerInteger)keyInfo.PrivateKey; return(new DsaPrivateKeyParameters(derX.Value, new DsaParameters(para.P, para.Q, para.G))); } else if (algID.ObjectID.Equals(X9ObjectIdentifiers.IdECPublicKey)) { X962Parameters para = new X962Parameters((Asn1Object)algID.Parameters); ECDomainParameters dParams = null; if (para.IsNamedCurve) { DerObjectIdentifier oid = (DerObjectIdentifier)para.Parameters; X9ECParameters ecP = X962NamedCurves.GetByOid(oid); if (ecP == null) { ecP = SecNamedCurves.GetByOid(oid); if (ecP == null) { ecP = NistNamedCurves.GetByOid(oid); } } dParams = new ECDomainParameters( ecP.Curve, ecP.G, ecP.N, ecP.H, ecP.GetSeed()); } else { X9ECParameters ecP = new X9ECParameters( (Asn1Sequence)para.Parameters); dParams = new ECDomainParameters( ecP.Curve, ecP.G, ecP.N, ecP.H, ecP.GetSeed()); } ECPrivateKeyStructure ec = new ECPrivateKeyStructure((Asn1Sequence)keyInfo.PrivateKey); return(new ECPrivateKeyParameters(ec.GetKey(), dParams)); } else if (algID.ObjectID.Equals(CryptoProObjectIdentifiers.GostR3410x2001)) { throw new NotImplementedException(); } else if (algID.ObjectID.Equals(CryptoProObjectIdentifiers.GostR3410x94)) { Gost3410PublicKeyAlgParameters algParams = new Gost3410PublicKeyAlgParameters( (Asn1Sequence)algID.Parameters); DerOctetString derX = (DerOctetString)keyInfo.PrivateKey; byte[] keyEnc = derX.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 x = new BigInteger(1, keyBytes); return(new Gost3410PrivateKeyParameters(x, algParams.PublicKeyParamSet)); } else { throw new SecurityUtilityException("algorithm identifier in key not recognised"); } }
public virtual PkiHeaderBuilder SetRecipKID(DerOctetString kid) { recipKID = kid; return this; }
public static AsymmetricKeyParameter CreateKey(PrivateKeyInfo keyInfo) { //IL_02a2: Unknown result type (might be due to invalid IL or missing references) AlgorithmIdentifier privateKeyAlgorithm = keyInfo.PrivateKeyAlgorithm; DerObjectIdentifier algorithm = privateKeyAlgorithm.Algorithm; if (algorithm.Equals(PkcsObjectIdentifiers.RsaEncryption) || algorithm.Equals(X509ObjectIdentifiers.IdEARsa) || algorithm.Equals(PkcsObjectIdentifiers.IdRsassaPss) || algorithm.Equals(PkcsObjectIdentifiers.IdRsaesOaep)) { RsaPrivateKeyStructure instance = RsaPrivateKeyStructure.GetInstance(keyInfo.ParsePrivateKey()); return(new RsaPrivateCrtKeyParameters(instance.Modulus, instance.PublicExponent, instance.PrivateExponent, instance.Prime1, instance.Prime2, instance.Exponent1, instance.Exponent2, instance.Coefficient)); } if (algorithm.Equals(PkcsObjectIdentifiers.DhKeyAgreement)) { DHParameter dHParameter = new DHParameter(Asn1Sequence.GetInstance(privateKeyAlgorithm.Parameters.ToAsn1Object())); DerInteger derInteger = (DerInteger)keyInfo.ParsePrivateKey(); int l = dHParameter.L?.IntValue ?? 0; DHParameters parameters = new DHParameters(dHParameter.P, dHParameter.G, null, l); return(new DHPrivateKeyParameters(derInteger.Value, parameters, algorithm)); } if (algorithm.Equals(OiwObjectIdentifiers.ElGamalAlgorithm)) { ElGamalParameter elGamalParameter = new ElGamalParameter(Asn1Sequence.GetInstance(privateKeyAlgorithm.Parameters.ToAsn1Object())); DerInteger derInteger2 = (DerInteger)keyInfo.ParsePrivateKey(); return(new ElGamalPrivateKeyParameters(derInteger2.Value, new ElGamalParameters(elGamalParameter.P, elGamalParameter.G))); } if (algorithm.Equals(X9ObjectIdentifiers.IdDsa)) { DerInteger derInteger3 = (DerInteger)keyInfo.ParsePrivateKey(); Asn1Encodable parameters2 = privateKeyAlgorithm.Parameters; DsaParameters parameters3 = null; if (parameters2 != null) { DsaParameter instance2 = DsaParameter.GetInstance(parameters2.ToAsn1Object()); parameters3 = new DsaParameters(instance2.P, instance2.Q, instance2.G); } return(new DsaPrivateKeyParameters(derInteger3.Value, parameters3)); } if (algorithm.Equals(X9ObjectIdentifiers.IdECPublicKey)) { X962Parameters x962Parameters = new X962Parameters(privateKeyAlgorithm.Parameters.ToAsn1Object()); X9ECParameters x9ECParameters = ((!x962Parameters.IsNamedCurve) ? new X9ECParameters((Asn1Sequence)x962Parameters.Parameters) : ECKeyPairGenerator.FindECCurveByOid((DerObjectIdentifier)x962Parameters.Parameters)); ECPrivateKeyStructure instance3 = ECPrivateKeyStructure.GetInstance(keyInfo.ParsePrivateKey()); BigInteger key = instance3.GetKey(); if (x962Parameters.IsNamedCurve) { return(new ECPrivateKeyParameters("EC", key, (DerObjectIdentifier)x962Parameters.Parameters)); } ECDomainParameters parameters4 = new ECDomainParameters(x9ECParameters.Curve, x9ECParameters.G, x9ECParameters.N, x9ECParameters.H, x9ECParameters.GetSeed()); return(new ECPrivateKeyParameters(key, parameters4)); } if (algorithm.Equals(CryptoProObjectIdentifiers.GostR3410x2001)) { Gost3410PublicKeyAlgParameters gost3410PublicKeyAlgParameters = new Gost3410PublicKeyAlgParameters(Asn1Sequence.GetInstance(privateKeyAlgorithm.Parameters.ToAsn1Object())); ECDomainParameters byOid = ECGost3410NamedCurves.GetByOid(gost3410PublicKeyAlgParameters.PublicKeyParamSet); if (byOid == null) { throw new ArgumentException("Unrecognized curve OID for GostR3410x2001 private key"); } Asn1Object asn1Object = keyInfo.ParsePrivateKey(); ECPrivateKeyStructure eCPrivateKeyStructure = ((!(asn1Object is DerInteger)) ? ECPrivateKeyStructure.GetInstance(asn1Object) : new ECPrivateKeyStructure(byOid.N.BitLength, ((DerInteger)asn1Object).Value)); return(new ECPrivateKeyParameters("ECGOST3410", eCPrivateKeyStructure.GetKey(), gost3410PublicKeyAlgParameters.PublicKeyParamSet)); } if (algorithm.Equals(CryptoProObjectIdentifiers.GostR3410x94)) { Gost3410PublicKeyAlgParameters gost3410PublicKeyAlgParameters2 = new Gost3410PublicKeyAlgParameters(Asn1Sequence.GetInstance(privateKeyAlgorithm.Parameters.ToAsn1Object())); DerOctetString derOctetString = (DerOctetString)keyInfo.ParsePrivateKey(); BigInteger x = new BigInteger(1, Arrays.Reverse(derOctetString.GetOctets())); return(new Gost3410PrivateKeyParameters(x, gost3410PublicKeyAlgParameters2.PublicKeyParamSet)); } throw new SecurityUtilityException("algorithm identifier in key not recognised"); }
public static AsymmetricKeyParameter CreateKey( PrivateKeyInfo keyInfo) { AlgorithmIdentifier algID = keyInfo.PrivateKeyAlgorithm; 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)) { RsaPrivateKeyStructure keyStructure = new RsaPrivateKeyStructure( Asn1Sequence.GetInstance(keyInfo.ParsePrivateKey())); return(new RsaPrivateCrtKeyParameters( keyStructure.Modulus, keyStructure.PublicExponent, keyStructure.PrivateExponent, keyStructure.Prime1, keyStructure.Prime2, keyStructure.Exponent1, keyStructure.Exponent2, keyStructure.Coefficient)); } // TODO? // else if (algOid.Equals(X9ObjectIdentifiers.DHPublicNumber)) else if (algOid.Equals(PkcsObjectIdentifiers.DhKeyAgreement)) { DHParameter para = new DHParameter( Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object())); DerInteger derX = (DerInteger)keyInfo.ParsePrivateKey(); BigInteger lVal = para.L; int l = lVal == null ? 0 : lVal.IntValue; DHParameters dhParams = new DHParameters(para.P, para.G, null, l); return(new DHPrivateKeyParameters(derX.Value, dhParams, algOid)); } else if (algOid.Equals(OiwObjectIdentifiers.ElGamalAlgorithm)) { ElGamalParameter para = new ElGamalParameter( Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object())); DerInteger derX = (DerInteger)keyInfo.ParsePrivateKey(); return(new ElGamalPrivateKeyParameters( derX.Value, new ElGamalParameters(para.P, para.G))); } else if (algOid.Equals(X9ObjectIdentifiers.IdDsa)) { DerInteger derX = (DerInteger)keyInfo.ParsePrivateKey(); 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 DsaPrivateKeyParameters(derX.Value, parameters)); } else if (algOid.Equals(X9ObjectIdentifiers.IdECPublicKey)) { X962Parameters para = new X962Parameters(algID.Parameters.ToAsn1Object()); X9ECParameters x9; if (para.IsNamedCurve) { x9 = ECKeyPairGenerator.FindECCurveByOid((DerObjectIdentifier)para.Parameters); } else { x9 = new X9ECParameters((Asn1Sequence)para.Parameters); } ECPrivateKeyStructure ec = new ECPrivateKeyStructure( Asn1Sequence.GetInstance(keyInfo.ParsePrivateKey())); BigInteger d = ec.GetKey(); if (para.IsNamedCurve) { return(new ECPrivateKeyParameters("EC", d, (DerObjectIdentifier)para.Parameters)); } ECDomainParameters dParams = new ECDomainParameters(x9.Curve, x9.G, x9.N, x9.H, x9.GetSeed()); return(new ECPrivateKeyParameters(d, dParams)); } else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x2001)) { Gost3410PublicKeyAlgParameters gostParams = new Gost3410PublicKeyAlgParameters( Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object())); Asn1Object privKey = keyInfo.ParsePrivateKey(); ECPrivateKeyStructure ec; if (privKey is DerInteger) { // TODO Do we need to pass any parameters here? ec = new ECPrivateKeyStructure(((DerInteger)privKey).Value); } else { ec = ECPrivateKeyStructure.GetInstance(privKey); } ECDomainParameters ecP = ECGost3410NamedCurves.GetByOid(gostParams.PublicKeyParamSet); if (ecP == null) { throw new ArgumentException("Unrecognized curve OID for GostR3410x2001 private key"); } return(new ECPrivateKeyParameters("ECGOST3410", ec.GetKey(), gostParams.PublicKeyParamSet)); } else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x94)) { Gost3410PublicKeyAlgParameters gostParams = new Gost3410PublicKeyAlgParameters( Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object())); DerOctetString derX = (DerOctetString)keyInfo.ParsePrivateKey(); BigInteger x = new BigInteger(1, Arrays.Reverse(derX.GetOctets())); return(new Gost3410PrivateKeyParameters(x, gostParams.PublicKeyParamSet)); } else { throw new SecurityUtilityException("algorithm identifier in key not recognised"); } }
public static AsymmetricKeyParameter CreateKey(SubjectPublicKeyInfo keyInfo) { AlgorithmIdentifier algorithmID = keyInfo.AlgorithmID; DerObjectIdentifier objectID = algorithmID.ObjectID; if (objectID.Equals(PkcsObjectIdentifiers.RsaEncryption) || objectID.Equals(X509ObjectIdentifiers.IdEARsa) || objectID.Equals(PkcsObjectIdentifiers.IdRsassaPss) || objectID.Equals(PkcsObjectIdentifiers.IdRsaesOaep)) { RsaPublicKeyStructure instance = RsaPublicKeyStructure.GetInstance(keyInfo.GetPublicKey()); return(new RsaKeyParameters(isPrivate: false, instance.Modulus, instance.PublicExponent)); } if (objectID.Equals(X9ObjectIdentifiers.DHPublicNumber)) { Asn1Sequence instance2 = Asn1Sequence.GetInstance(algorithmID.Parameters.ToAsn1Object()); DHPublicKey instance3 = DHPublicKey.GetInstance(keyInfo.GetPublicKey()); BigInteger value = instance3.Y.Value; if (IsPkcsDHParam(instance2)) { return(ReadPkcsDHParam(objectID, value, instance2)); } DHDomainParameters instance4 = DHDomainParameters.GetInstance(instance2); BigInteger value2 = instance4.P.Value; BigInteger value3 = instance4.G.Value; BigInteger value4 = instance4.Q.Value; BigInteger j = null; if (instance4.J != null) { j = instance4.J.Value; } DHValidationParameters validation = null; DHValidationParms validationParms = instance4.ValidationParms; if (validationParms != null) { byte[] bytes = validationParms.Seed.GetBytes(); BigInteger value5 = validationParms.PgenCounter.Value; validation = new DHValidationParameters(bytes, value5.IntValue); } return(new DHPublicKeyParameters(value, new DHParameters(value2, value3, value4, j, validation))); } if (objectID.Equals(PkcsObjectIdentifiers.DhKeyAgreement)) { Asn1Sequence instance5 = Asn1Sequence.GetInstance(algorithmID.Parameters.ToAsn1Object()); DerInteger derInteger = (DerInteger)keyInfo.GetPublicKey(); return(ReadPkcsDHParam(objectID, derInteger.Value, instance5)); } if (objectID.Equals(OiwObjectIdentifiers.ElGamalAlgorithm)) { ElGamalParameter elGamalParameter = new ElGamalParameter(Asn1Sequence.GetInstance(algorithmID.Parameters.ToAsn1Object())); DerInteger derInteger2 = (DerInteger)keyInfo.GetPublicKey(); return(new ElGamalPublicKeyParameters(derInteger2.Value, new ElGamalParameters(elGamalParameter.P, elGamalParameter.G))); } if (objectID.Equals(X9ObjectIdentifiers.IdDsa) || objectID.Equals(OiwObjectIdentifiers.DsaWithSha1)) { DerInteger derInteger3 = (DerInteger)keyInfo.GetPublicKey(); Asn1Encodable parameters = algorithmID.Parameters; DsaParameters parameters2 = null; if (parameters != null) { DsaParameter instance6 = DsaParameter.GetInstance(parameters.ToAsn1Object()); parameters2 = new DsaParameters(instance6.P, instance6.Q, instance6.G); } return(new DsaPublicKeyParameters(derInteger3.Value, parameters2)); } if (objectID.Equals(X9ObjectIdentifiers.IdECPublicKey)) { X962Parameters x962Parameters = new X962Parameters(algorithmID.Parameters.ToAsn1Object()); X9ECParameters x9ECParameters = (!x962Parameters.IsNamedCurve) ? new X9ECParameters((Asn1Sequence)x962Parameters.Parameters) : ECKeyPairGenerator.FindECCurveByOid((DerObjectIdentifier)x962Parameters.Parameters); Asn1OctetString s = new DerOctetString(keyInfo.PublicKeyData.GetBytes()); X9ECPoint x9ECPoint = new X9ECPoint(x9ECParameters.Curve, s); ECPoint point = x9ECPoint.Point; if (x962Parameters.IsNamedCurve) { return(new ECPublicKeyParameters("EC", point, (DerObjectIdentifier)x962Parameters.Parameters)); } ECDomainParameters parameters3 = new ECDomainParameters(x9ECParameters.Curve, x9ECParameters.G, x9ECParameters.N, x9ECParameters.H, x9ECParameters.GetSeed()); return(new ECPublicKeyParameters(point, parameters3)); } if (objectID.Equals(CryptoProObjectIdentifiers.GostR3410x2001)) { Gost3410PublicKeyAlgParameters gost3410PublicKeyAlgParameters = new Gost3410PublicKeyAlgParameters((Asn1Sequence)algorithmID.Parameters); Asn1OctetString asn1OctetString; try { asn1OctetString = (Asn1OctetString)keyInfo.GetPublicKey(); } catch (IOException) { throw new ArgumentException("invalid info structure in GOST3410 public key"); IL_038b :; } byte[] octets = asn1OctetString.GetOctets(); byte[] array = new byte[32]; byte[] array2 = new byte[32]; for (int i = 0; i != array2.Length; i++) { array[i] = octets[31 - i]; } for (int k = 0; k != array.Length; k++) { array2[k] = octets[63 - k]; } ECDomainParameters byOid = ECGost3410NamedCurves.GetByOid(gost3410PublicKeyAlgParameters.PublicKeyParamSet); if (byOid == null) { return(null); } ECPoint q = byOid.Curve.CreatePoint(new BigInteger(1, array), new BigInteger(1, array2)); return(new ECPublicKeyParameters("ECGOST3410", q, gost3410PublicKeyAlgParameters.PublicKeyParamSet)); } if (objectID.Equals(CryptoProObjectIdentifiers.GostR3410x94)) { Gost3410PublicKeyAlgParameters gost3410PublicKeyAlgParameters2 = new Gost3410PublicKeyAlgParameters((Asn1Sequence)algorithmID.Parameters); DerOctetString derOctetString; try { derOctetString = (DerOctetString)keyInfo.GetPublicKey(); } catch (IOException) { throw new ArgumentException("invalid info structure in GOST3410 public key"); IL_0480 :; } byte[] octets2 = derOctetString.GetOctets(); byte[] array3 = new byte[octets2.Length]; for (int l = 0; l != octets2.Length; l++) { array3[l] = octets2[octets2.Length - 1 - l]; } BigInteger y = new BigInteger(1, array3); return(new Gost3410PublicKeyParameters(y, gost3410PublicKeyAlgParameters2.PublicKeyParamSet)); } throw new SecurityUtilityException("algorithm identifier in key not recognised: " + objectID); }
private void checkValues( ProfessionInfo profInfo, NamingAuthority auth, DirectoryString[] professionItems, DerObjectIdentifier[] professionOids, string registrationNumber, DerOctetString addProfInfo) { checkOptionalField("auth", auth, profInfo.NamingAuthority); checkMandatoryField("professionItems", professionItems[0], profInfo.GetProfessionItems()[0]); if (professionOids != null) { checkOptionalField("professionOids", professionOids[0], profInfo.GetProfessionOids()[0]); } checkOptionalField("registrationNumber", registrationNumber, profInfo.RegistrationNumber); checkOptionalField("addProfessionInfo", addProfInfo, profInfo.AddProfessionInfo); }
/// <exception cref="System.IO.IOException"></exception> public virtual byte[] GetArchiveTimestampData(int index, Document originalDocument ) { ByteArrayOutputStream toTimestamp = new ByteArrayOutputStream(); BcCms.ContentInfo contentInfo = cmsSignedData.ContentInfo; BcCms.SignedData signedData = BcCms.SignedData.GetInstance(contentInfo.Content); // 5.4.1 if (signedData.EncapContentInfo == null || signedData.EncapContentInfo. Content == null) { if (originalDocument != null) { //jbonilla Hack para leer un InputStream en su totalidad. toTimestamp.Write(Streams.ReadAll( originalDocument.OpenStream())); } else { throw new RuntimeException("Signature is detached and no original data provided." ); } } else { BcCms.ContentInfo content = signedData.EncapContentInfo; DerOctetString octet = (DerOctetString)content.Content; BcCms.ContentInfo info2 = new BcCms.ContentInfo(new DerObjectIdentifier("1.2.840.113549.1.7.1" ), new BerOctetString(octet.GetOctets())); toTimestamp.Write(info2.GetEncoded()); } if (signedData.Certificates != null) { DerOutputStream output = new DerOutputStream(toTimestamp); output.WriteObject(signedData.Certificates); output.Close(); } if (signedData.CRLs != null) { toTimestamp.Write(signedData.CRLs.GetEncoded()); } if (signerInformation.UnsignedAttributes != null) { Asn1EncodableVector original = signerInformation.UnsignedAttributes.ToAsn1EncodableVector (); IList <BcCms.Attribute> timeStampToRemove = GetTimeStampToRemove(index); Asn1EncodableVector filtered = new Asn1EncodableVector(); for (int i = 0; i < original.Count; i++) { Asn1Encodable enc = original[i]; if (!timeStampToRemove.Contains(enc)) { filtered.Add(original[i]); } } SignerInformation filteredInfo = SignerInformation.ReplaceUnsignedAttributes(signerInformation , new BcCms.AttributeTable(filtered)); toTimestamp.Write(filteredInfo.ToSignerInfo().GetEncoded()); } return(toTimestamp.ToByteArray()); }