List of usage examples for org.bouncycastle.asn1 DERSequence getObjectAt
public ASN1Encodable getObjectAt(int index)
From source file:edu.vt.middleware.crypt.io.PrivateKeyCredentialReader.java
License:Open Source License
/** {@inheritDoc} */ protected PrivateKey decode(final byte[] encoded) throws CryptException { final KeySpec spec; final String algorithm; final ASN1Object o; try {//from ww w. j a v a2 s .c om o = ASN1Object.fromByteArray(encoded); } catch (Exception e) { throw new CryptException("Key is not ASN.1 encoded data."); } // Assume PKCS#8 and try OpenSSL "traditional" format as backup PrivateKeyInfo pi; try { pi = PrivateKeyInfo.getInstance(o); } catch (Exception e) { pi = null; } if (pi != null) { final String algOid = pi.getAlgorithmId().getObjectId().getId(); if (RSA_ID.equals(pi.getAlgorithmId().getObjectId())) { algorithm = "RSA"; } else if (EC_ID.equals(pi.getAlgorithmId().getObjectId())) { algorithm = "EC"; } else if (DSA_ID.equals(pi.getAlgorithmId().getObjectId())) { algorithm = "DSA"; } else { throw new CryptException("Unsupported PKCS#8 algorithm ID " + algOid); } try { spec = new PKCS8EncodedKeySpec(encoded); } catch (Exception e) { throw new CryptException("Invalid PKCS#8 private key format.", e); } } else if (o instanceof DERObjectIdentifier) { // Indicates we have an EC key in the default OpenSSL format emitted by // // openssl ecparam -name xxxx -genkey // // which is the concatenation of the named curve OID and a sequence of 1 // containing the private point algorithm = "EC"; final DERObjectIdentifier oid = (DERObjectIdentifier) o; final int len = encoded[1]; final byte[] privatePart = new byte[encoded.length - len - 2]; System.arraycopy(encoded, len + 2, privatePart, 0, privatePart.length); try { final ASN1Sequence seq = (ASN1Sequence) ASN1Sequence.fromByteArray(privatePart); spec = new ECPrivateKeySpec(DERInteger.getInstance(seq.getObjectAt(0)).getValue(), ECUtils.fromNamedCurve(oid)); } catch (IOException e) { throw new CryptException("Error reading elliptic curve key data.", e); } } else { // OpenSSL "traditional" format is an ASN.1 sequence of key parameters // Detect key type based on number and types of parameters: // RSA -> {version, mod, pubExp, privExp, prime1, prime2, exp1, exp2, c} // DSA -> {version, p, q, g, pubExp, privExp} // EC -> {version, privateKey, parameters, publicKey} final DERSequence sequence = (DERSequence) o; if (sequence.size() == 9) { if (logger.isDebugEnabled()) { logger.debug("Reading OpenSSL format RSA private key."); } algorithm = "RSA"; try { spec = new RSAPrivateCrtKeySpec(DERInteger.getInstance(sequence.getObjectAt(1)).getValue(), DERInteger.getInstance(sequence.getObjectAt(2)).getValue(), DERInteger.getInstance(sequence.getObjectAt(3)).getValue(), DERInteger.getInstance(sequence.getObjectAt(4)).getValue(), DERInteger.getInstance(sequence.getObjectAt(5)).getValue(), DERInteger.getInstance(sequence.getObjectAt(6)).getValue(), DERInteger.getInstance(sequence.getObjectAt(7)).getValue(), DERInteger.getInstance(sequence.getObjectAt(8)).getValue()); } catch (Exception e) { throw new CryptException("Invalid RSA key.", e); } } else if (sequence.size() == 6) { if (logger.isDebugEnabled()) { logger.debug("Reading OpenSSL format DSA private key."); } algorithm = "DSA"; try { spec = new DSAPrivateKeySpec(DERInteger.getInstance(sequence.getObjectAt(5)).getValue(), DERInteger.getInstance(sequence.getObjectAt(1)).getValue(), DERInteger.getInstance(sequence.getObjectAt(2)).getValue(), DERInteger.getInstance(sequence.getObjectAt(3)).getValue()); } catch (Exception e) { throw new CryptException("Invalid DSA key.", e); } } else if (sequence.size() == 4) { if (logger.isDebugEnabled()) { logger.debug("Reading OpenSSL format EC private key."); } algorithm = "EC"; spec = ECUtils.readEncodedPrivateKey(sequence); } else { throw new CryptException("Invalid OpenSSL traditional private key format."); } } try { return CryptProvider.getKeyFactory(algorithm).generatePrivate(spec); } catch (InvalidKeySpecException e) { throw new CryptException("Invalid key specification", e); } }
From source file:edu.vt.middleware.crypt.io.PrivateKeyCredentialReader.java
License:Open Source License
/** * Decrypts a DER-encoded private key in PKCS#8 format. * * @param encrypted Bytes of DER-encoded encrypted private key. * @param password Password to decrypt private key. * * @return ASN.1 encoded bytes of decrypted key. * * @throws CryptException On key decryption errors. *//*from w w w. ja va 2s . c o m*/ private byte[] decryptPKCS8Key(final byte[] encrypted, final char[] password) throws CryptException { final EncryptionScheme scheme; try { final EncryptedPrivateKeyInfo ki = EncryptedPrivateKeyInfo .getInstance(ASN1Object.fromByteArray(encrypted)); final AlgorithmIdentifier alg = ki.getEncryptionAlgorithm(); if (PKCSObjectIdentifiers.id_PBES2.equals(alg.getObjectId())) { // PBES2 has following parameters: // { // {id-PBKDF2, {salt, iterationCount, keyLength (optional)}} // {encryptionAlgorithmOid, iv} // } final DERSequence pbeSeq = (DERSequence) alg.getParameters(); final PBKDF2Parameters kdfParms = PBKDF2Parameters.decode((DERSequence) pbeSeq.getObjectAt(0)); final PBES2CipherGenerator cipherGen = new PBES2CipherGenerator( (DERSequence) pbeSeq.getObjectAt(1)); if (kdfParms.getLength() == 0) { kdfParms.setLength(cipherGen.getKeySize() / 8); } scheme = new PBES2EncryptionScheme(cipherGen.generate(), kdfParms); } else { // Use PBES1 encryption scheme to decrypt key scheme = new PBES1EncryptionScheme(PBES1Algorithm.fromOid(alg.getObjectId().getId()), PBEParameter.decode((DERSequence) alg.getParameters())); } return scheme.decrypt(password, ki.getEncryptedData()); } catch (Exception e) { throw new CryptException("Failed decrypting PKCS#8 private key", e); } }
From source file:edu.vt.middleware.crypt.pkcs.PBEParameter.java
License:Open Source License
/** * Decodes a DER sequence of PBE parameters into an instance of this class. * * @param params PBE parameters as a DER sequence. * * @return Equivalent instance of {@link PBEParameter}. */// ww w. j a v a 2 s . c o m public static PBEParameter decode(final DERSequence params) { return new PBEParameter(DERHelper.asOctets(params.getObjectAt(0)), DERHelper.asInt(params.getObjectAt(1))); }
From source file:edu.vt.middleware.crypt.pkcs.PBES2CipherGenerator.java
License:Open Source License
/** * Creates a new cipher generator from DER-encoded data describing the cipher. * * @param seq DER-encoded sequence containing algorithm identifier and * parameters.//from ww w. ja v a 2s.c o m */ public PBES2CipherGenerator(final DERSequence seq) { // DER sequence is expected to be AlgorithmIdentifier type of PKCS#5 algorithm = PBES2Algorithm.fromOid(((DERObjectIdentifier) seq.getObjectAt(0)).getId()); final DEREncodable parms = seq.getObjectAt(1); DERSequence pSeq; switch (algorithm) { case RC2: pSeq = (DERSequence) parms; int effectiveBits = 32; int idx; if (pSeq.size() > 1) { idx = 1; effectiveBits = RC2.getEffectiveBits(DERHelper.asInt(pSeq.getObjectAt(0))); algParamSpec = new RC2ParameterSpec(effectiveBits, DERHelper.asOctets(pSeq.getObjectAt(idx))); } keySize = effectiveBits; break; case RC5: pSeq = (DERSequence) parms; final int version = DERHelper.asInt(pSeq.getObjectAt(0)); final int rounds = DERHelper.asInt(pSeq.getObjectAt(1)); final int blkSize = DERHelper.asInt(pSeq.getObjectAt(2)); if (pSeq.size() > 3) { algParamSpec = new RC5ParameterSpec(version, rounds, blkSize, DERHelper.asOctets(pSeq.getObjectAt(3))); } else { algParamSpec = new RC5ParameterSpec(version, rounds, blkSize); } keySize = algorithm.getKeySize(); break; default: algParamSpec = new IvParameterSpec(DERHelper.asOctets(parms)); keySize = algorithm.getKeySize(); } }
From source file:edu.vt.middleware.crypt.pkcs.PBKDF2Parameters.java
License:Open Source License
/** * Decodes a DER sequence of PBKDF2 parameters into an instance of this class. * * @param params PBKDF2 parameters as a DER sequence. * * @return Equivalent instance of {@link PBKDF2Parameters}. *//*from w ww. j ava 2 s. co m*/ public static PBKDF2Parameters decode(final DERSequence params) { final DERSequence kdfSeq = (DERSequence) params.getObjectAt(1); final PBKDF2Parameters instance = new PBKDF2Parameters(DERHelper.asOctets(kdfSeq.getObjectAt(0)), DERHelper.asInt(kdfSeq.getObjectAt(1))); if (kdfSeq.size() > 2) { instance.setLength(DERHelper.asInt(kdfSeq.getObjectAt(2)) * 8); } return instance; }
From source file:eu.europa.ec.markt.dss.validation.cades.CAdESCertificateSource.java
License:Open Source License
@Override @SuppressWarnings("unchecked") public List<X509Certificate> getCertificates() { List<X509Certificate> list = new ArrayList<X509Certificate>(); try {/*from www . jav a2 s . com*/ if (!onlyExtended) { LOG.fine(cmsSignedData.getCertificates().getMatches(null).size() + " certificate in collection"); for (X509CertificateHolder ch : (Collection<X509CertificateHolder>) cmsSignedData.getCertificates() .getMatches(null)) { X509Certificate c = new X509CertificateObject(ch.toASN1Structure()); LOG.fine("Certificate for subject " + c.getSubjectX500Principal()); if (!list.contains(c)) { list.add(c); } } } // Add certificates in CAdES-XL certificate-values inside SignerInfo attribute if present SignerInformation si = cmsSignedData.getSignerInfos().get(signerId); if (si != null && si.getUnsignedAttributes() != null && si.getUnsignedAttributes().get(PKCSObjectIdentifiers.id_aa_ets_certValues) != null) { DERSequence seq = (DERSequence) si.getUnsignedAttributes() .get(PKCSObjectIdentifiers.id_aa_ets_certValues).getAttrValues().getObjectAt(0); for (int i = 0; i < seq.size(); i++) { X509CertificateStructure cs = X509CertificateStructure.getInstance(seq.getObjectAt(i)); X509Certificate c = new X509CertificateObject(cs); if (!list.contains(c)) { list.add(c); } } } } catch (CertificateParsingException e) { throw new RuntimeException(e); } catch (StoreException e) { throw new RuntimeException(e); } return list; }
From source file:eu.europa.ec.markt.dss.validation.cades.CAdESSignature.java
License:Open Source License
@Override public List<CertificateRef> getCertificateRefs() { List<CertificateRef> list = new ArrayList<CertificateRef>(); if (signerInformation.getUnsignedAttributes() != null) { Attribute completeCertRefsAttr = signerInformation.getUnsignedAttributes() .get(PKCSObjectIdentifiers.id_aa_ets_certificateRefs); if (completeCertRefsAttr != null && completeCertRefsAttr.getAttrValues().size() > 0) { DERSequence completeCertificateRefs = (DERSequence) completeCertRefsAttr.getAttrValues() .getObjectAt(0);/*from w w w .ja v a2 s .com*/ for (int i1 = 0; i1 < completeCertificateRefs.size(); i1++) { OtherCertID otherCertId = OtherCertID.getInstance(completeCertificateRefs.getObjectAt(i1)); CertificateRef certId = new CertificateRef(); certId.setDigestAlgorithm(otherCertId.getAlgorithmHash().getAlgorithm().getId()); certId.setDigestValue(otherCertId.getCertHash()); if (otherCertId.getIssuerSerial() != null) { if (otherCertId.getIssuerSerial().getIssuer() != null) { certId.setIssuerName(otherCertId.getIssuerSerial().getIssuer().toString()); } if (otherCertId.getIssuerSerial().getSerial() != null) { certId.setIssuerSerial(otherCertId.getIssuerSerial().getSerial().toString()); } } list.add(certId); } } } return list; }
From source file:eu.europa.ec.markt.dss.validation.cades.CAdESSignature.java
License:Open Source License
@Override public List<CRLRef> getCRLRefs() { List<CRLRef> list = new ArrayList<CRLRef>(); if (signerInformation.getUnsignedAttributes() != null) { Attribute completeRevocationRefsAttr = signerInformation.getUnsignedAttributes() .get(PKCSObjectIdentifiers.id_aa_ets_revocationRefs); if (completeRevocationRefsAttr != null && completeRevocationRefsAttr.getAttrValues().size() > 0) { DERSequence completeCertificateRefs = (DERSequence) completeRevocationRefsAttr.getAttrValues() .getObjectAt(0);//from w ww . j a v a 2 s. c o m for (int i1 = 0; i1 < completeCertificateRefs.size(); i1++) { CrlOcspRef otherCertId = CrlOcspRef.getInstance(completeCertificateRefs.getObjectAt(i1)); for (CrlValidatedID id : otherCertId.getCrlids().getCrls()) { list.add(new CRLRef(id)); } } } } return list; }
From source file:eu.europa.ec.markt.dss.validation.cades.CAdESSignature.java
License:Open Source License
@Override public List<OCSPRef> getOCSPRefs() { List<OCSPRef> list = new ArrayList<OCSPRef>(); if (signerInformation.getUnsignedAttributes() != null) { Attribute completeRevocationRefsAttr = signerInformation.getUnsignedAttributes() .get(PKCSObjectIdentifiers.id_aa_ets_revocationRefs); if (completeRevocationRefsAttr != null && completeRevocationRefsAttr.getAttrValues().size() > 0) { DERSequence completeRevocationRefs = (DERSequence) completeRevocationRefsAttr.getAttrValues() .getObjectAt(0);/*from www. ja va2 s . co m*/ for (int i1 = 0; i1 < completeRevocationRefs.size(); i1++) { CrlOcspRef otherCertId = CrlOcspRef.getInstance(completeRevocationRefs.getObjectAt(i1)); for (OcspResponsesID id : otherCertId.getOcspids().getOcspResponses()) { list.add(new OCSPRef(id, true)); } } } } return list; }
From source file:eu.europa.ec.markt.dss.validation.tsl.PolicyIdCondition.java
License:Open Source License
@SuppressWarnings("deprecation") @Override//from ww w . ja v a2s. c o m public boolean check(CertificateAndContext cert) { byte[] certificatePolicies = cert.getCertificate() .getExtensionValue(X509Extensions.CertificatePolicies.getId()); if (certificatePolicies != null) { try { ASN1InputStream input = new ASN1InputStream(certificatePolicies); DEROctetString s = (DEROctetString) input.readObject(); byte[] content = s.getOctets(); input = new ASN1InputStream(content); DERSequence seq = (DERSequence) input.readObject(); for (int i = 0; i < seq.size(); i++) { PolicyInformation policyInfo = PolicyInformation.getInstance(seq.getObjectAt(i)); if (policyInfo.getPolicyIdentifier().getId().equals(policyOid)) { return true; } } } catch (IOException e) { throw new RuntimeException(e); } } return false; }