org.bouncycastle.asn1.ASN1InputStream Java Examples

The following examples show how to use org.bouncycastle.asn1.ASN1InputStream. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ECDSASignatureProvider.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static byte[] asn1derToConcatenatedRS(final byte[] derEncodedSignatureValue, int signLength) throws IOException {
    int len = signLength / 2;

    ASN1InputStream asn1InputStream = new ASN1InputStream(derEncodedSignatureValue);
    ASN1Primitive asn1Primitive = asn1InputStream.readObject();
    asn1InputStream.close();

    ASN1Sequence asn1Sequence = (ASN1Sequence.getInstance(asn1Primitive));
    ASN1Integer rASN1 = (ASN1Integer) asn1Sequence.getObjectAt(0);
    ASN1Integer sASN1 = (ASN1Integer) asn1Sequence.getObjectAt(1);
    X9IntegerConverter x9IntegerConverter = new X9IntegerConverter();
    byte[] r = x9IntegerConverter.integerToBytes(rASN1.getValue(), len);
    byte[] s = x9IntegerConverter.integerToBytes(sASN1.getValue(), len);

    byte[] concatenatedSignatureValue = new byte[signLength];
    System.arraycopy(r, 0, concatenatedSignatureValue, 0, len);
    System.arraycopy(s, 0, concatenatedSignatureValue, len, len);

    return concatenatedSignatureValue;
}
 
Example #2
Source File: CFDv3Debugger.java    From factura-electronica with Apache License 2.0 6 votes vote down vote up
private void dumpDigests() throws Exception {
    System.err.println(cfd.getCadenaOriginal());
    String certStr = cfd.document.getCertificado();
    Base64 b64 = new Base64();
    byte[] cbs = b64.decode(certStr);
    X509Certificate cert = (X509Certificate) KeyLoaderFactory.createInstance(
            KeyLoaderEnumeration.PUBLIC_KEY_LOADER,
            new ByteArrayInputStream(cbs)).getKey();
    cert.checkValidity();
    String sigStr = cfd.document.getSello();
    byte[] signature = b64.decode(sigStr);
    CFDv3.dump("Digestion firmada", signature, System.err);
    Cipher dec = Cipher.getInstance("RSA");
    dec.init(Cipher.DECRYPT_MODE, cert);
    byte[] result = dec.doFinal(signature);
    CFDv3.dump("Digestion decriptada", result, System.err);
    ASN1InputStream aIn = new ASN1InputStream(result);
    ASN1Sequence seq = (ASN1Sequence) aIn.readObject();
    ASN1OctetString sigHash = (ASN1OctetString) seq.getObjectAt(1);
    CFDv3.dump("Sello", sigHash.getOctets(), System.err);
}
 
Example #3
Source File: rsasign.java    From JrebelBrainsLicenseServerforJava with Apache License 2.0 6 votes vote down vote up
public static String Sign(byte[] content, String privateKey) {
try {
	byte[] keybyte = Base64.decode(privateKey.toString());
	ASN1InputStream in = new ASN1InputStream(keybyte);
	ASN1Primitive obj = in.readObject();
	RSAPrivateKeyStructure pStruct = RSAPrivateKeyStructure.getInstance(obj);
	RSAPrivateKeySpec spec = new RSAPrivateKeySpec(pStruct.getModulus(), pStruct.getPrivateExponent());
	KeyFactory keyFactory = KeyFactory.getInstance("RSA");
	PrivateKey priKey = keyFactory.generatePrivate(spec);
	java.security.Signature signature = java.security.Signature.getInstance("MD5WithRSA");
	signature.initSign(priKey);
	signature.update(content);
	byte[] signed = signature.sign();
	return Hex.bytesToHexString(signed);
       }
       catch (Exception e) {
           e.printStackTrace();
       }
       return null;
   }
 
Example #4
Source File: Asn1Utils.java    From AttestationServer with MIT License 6 votes vote down vote up
public static ASN1Sequence getAsn1SequenceFromStream(final ASN1InputStream asn1InputStream)
        throws IOException, CertificateParsingException {
    ASN1Primitive asn1Primitive = asn1InputStream.readObject();
    if (!(asn1Primitive instanceof ASN1OctetString)) {
        throw new CertificateParsingException(
                "Expected octet stream, found " + asn1Primitive.getClass().getName());
    }
    try (ASN1InputStream seqInputStream = new ASN1InputStream(
            ((ASN1OctetString) asn1Primitive).getOctets())) {
        asn1Primitive = seqInputStream.readObject();
        if (!(asn1Primitive instanceof ASN1Sequence)) {
            throw new CertificateParsingException(
                    "Expected sequence, found " + asn1Primitive.getClass().getName());
        }
        return (ASN1Sequence) asn1Primitive;
    }
}
 
Example #5
Source File: Asn1Utils.java    From Auditor with MIT License 6 votes vote down vote up
public static ASN1Sequence getAsn1SequenceFromStream(final ASN1InputStream asn1InputStream)
        throws IOException, CertificateParsingException {
    ASN1Primitive asn1Primitive = asn1InputStream.readObject();
    if (!(asn1Primitive instanceof ASN1OctetString)) {
        throw new CertificateParsingException(
                "Expected octet stream, found " + asn1Primitive.getClass().getName());
    }
    try (ASN1InputStream seqInputStream = new ASN1InputStream(
            ((ASN1OctetString) asn1Primitive).getOctets())) {
        asn1Primitive = seqInputStream.readObject();
        if (!(asn1Primitive instanceof ASN1Sequence)) {
            throw new CertificateParsingException(
                    "Expected sequence, found " + asn1Primitive.getClass().getName());
        }
        return (ASN1Sequence) asn1Primitive;
    }
}
 
Example #6
Source File: PdfPKCS7.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Verifies a signature using the sub-filter adbe.x509.rsa_sha1.
 * @param contentsKey the /Contents key
 * @param certsKey the /Cert key
 * @param provider the provider or <code>null</code> for the default provider
 */    
public PdfPKCS7(byte[] contentsKey, byte[] certsKey, String provider) {
    try {
        this.provider = provider;
        X509CertParser cr = new X509CertParser();
        cr.engineInit(new ByteArrayInputStream(certsKey));
        certs = cr.engineReadAll();
        signCerts = certs;
        signCert = (X509Certificate)certs.iterator().next();
        crls = new ArrayList();
        ASN1InputStream in = new ASN1InputStream(new ByteArrayInputStream(contentsKey));
        digest = ((DEROctetString)in.readObject()).getOctets();
        if (provider == null)
            sig = Signature.getInstance("SHA1withRSA");
        else
            sig = Signature.getInstance("SHA1withRSA", provider);
        sig.initVerify(signCert.getPublicKey());
    }
    catch (Exception e) {
        throw new ExceptionConverter(e);
    }
}
 
Example #7
Source File: PdfPKCS7.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Added by Aiken Sam, 2006-11-15, modifed by Martin Brunecky 07/12/2007
 * to start with the timeStampToken (signedData 1.2.840.113549.1.7.2).
 * Token is the TSA response without response status, which is usually
 * handled by the (vendor supplied) TSA request/response interface).
 * @param timeStampToken byte[] - time stamp token, DER encoded signedData
 * @return ASN1EncodableVector
 * @throws IOException
 */
private ASN1EncodableVector buildUnauthenticatedAttributes(byte[] timeStampToken)  throws IOException {
    if (timeStampToken == null)
        return null;

    // @todo: move this together with the rest of the defintions
    String ID_TIME_STAMP_TOKEN = "1.2.840.113549.1.9.16.2.14"; // RFC 3161 id-aa-timeStampToken

    ASN1InputStream tempstream = new ASN1InputStream(new ByteArrayInputStream(timeStampToken));
    ASN1EncodableVector unauthAttributes = new ASN1EncodableVector();

    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(new ASN1ObjectIdentifier(ID_TIME_STAMP_TOKEN)); // id-aa-timeStampToken
    ASN1Sequence seq = (ASN1Sequence) tempstream.readObject();
    v.add(new DERSet(seq));

    unauthAttributes.add(new DERSequence(v));
    return unauthAttributes;
 }
 
Example #8
Source File: PdfPublicKeySecurityHandler.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
private KeyTransRecipientInfo computeRecipientInfo(X509Certificate x509certificate, byte[] abyte0)
    throws GeneralSecurityException, IOException
{
    ASN1InputStream asn1inputstream = 
        new ASN1InputStream(new ByteArrayInputStream(x509certificate.getTBSCertificate()));
    TBSCertificateStructure tbscertificatestructure = 
        TBSCertificateStructure.getInstance(asn1inputstream.readObject());
    AlgorithmIdentifier algorithmidentifier = tbscertificatestructure.getSubjectPublicKeyInfo().getAlgorithm();
    IssuerAndSerialNumber issuerandserialnumber = 
        new IssuerAndSerialNumber(
            tbscertificatestructure.getIssuer(), 
            tbscertificatestructure.getSerialNumber().getValue());
    Cipher cipher = Cipher.getInstance(algorithmidentifier.getAlgorithm().getId());        
    cipher.init(1, x509certificate);
    DEROctetString deroctetstring = new DEROctetString(cipher.doFinal(abyte0));
    RecipientIdentifier recipId = new RecipientIdentifier(issuerandserialnumber);
    return new KeyTransRecipientInfo( recipId, algorithmidentifier, deroctetstring);
}
 
Example #9
Source File: KerberosRelevantAuthData.java    From jcifs with GNU Lesser General Public License v2.1 6 votes vote down vote up
public KerberosRelevantAuthData ( byte[] token, Map<Integer, KerberosKey> keys ) throws PACDecodingException {
    DLSequence authSequence;
    try {
        try ( ASN1InputStream stream = new ASN1InputStream(new ByteArrayInputStream(token)) ) {
            authSequence = ASN1Util.as(DLSequence.class, stream);
        }
    }
    catch ( IOException e ) {
        throw new PACDecodingException("Malformed kerberos ticket", e);
    }

    this.authorizations = new ArrayList<>();
    Enumeration<?> authElements = authSequence.getObjects();
    while ( authElements.hasMoreElements() ) {
        DLSequence authElement = ASN1Util.as(DLSequence.class, authElements);
        ASN1Integer authType = ASN1Util.as(ASN1Integer.class, ASN1Util.as(DERTaggedObject.class, authElement, 0));
        DEROctetString authData = ASN1Util.as(DEROctetString.class, ASN1Util.as(DERTaggedObject.class, authElement, 1));

        this.authorizations.addAll(KerberosAuthData.parse(authType.getValue().intValue(), authData.getOctets(), keys));
    }
}
 
Example #10
Source File: CAdESTimeStampSigner.java    From signer with GNU Lesser General Public License v3.0 6 votes vote down vote up
private Timestamp checkTimeStamp(byte[] timeStamp, byte[] content,  byte[] hash){
	try {
		Security.addProvider(new BouncyCastleProvider());
		ais = new ASN1InputStream(new ByteArrayInputStream(timeStamp));
	    ASN1Sequence seq=(ASN1Sequence)ais.readObject();
        Attribute attributeTimeStamp = new Attribute((ASN1ObjectIdentifier)seq.getObjectAt(0), (ASN1Set)seq.getObjectAt(1));
        byte[] varTimeStamp = attributeTimeStamp.getAttrValues().getObjectAt(0).toASN1Primitive().getEncoded();
        TimeStampOperator timeStampOperator = new TimeStampOperator();
        if (content != null){
        	timeStampOperator.validate(content, varTimeStamp,null);
        }else{
        	timeStampOperator.validate(null, varTimeStamp,hash);
        }			
		TimeStampToken timeStampToken = new TimeStampToken(new CMSSignedData(varTimeStamp));
		Timestamp timeStampSigner = new Timestamp(timeStampToken);
		return timeStampSigner;
	} catch (CertificateCoreException | IOException | TSPException
			| CMSException e) {
		throw new SignerException(e);
	}

}
 
Example #11
Source File: KerberosRelevantAuthData.java    From jcifs-ng with GNU Lesser General Public License v2.1 6 votes vote down vote up
public KerberosRelevantAuthData ( byte[] token, Map<Integer, KerberosKey> keys ) throws PACDecodingException {
    DLSequence authSequence;
    try {
        try ( ASN1InputStream stream = new ASN1InputStream(new ByteArrayInputStream(token)) ) {
            authSequence = ASN1Util.as(DLSequence.class, stream);
        }
    }
    catch ( IOException e ) {
        throw new PACDecodingException("Malformed kerberos ticket", e);
    }

    this.authorizations = new ArrayList<>();
    Enumeration<?> authElements = authSequence.getObjects();
    while ( authElements.hasMoreElements() ) {
        DLSequence authElement = ASN1Util.as(DLSequence.class, authElements);
        ASN1Integer authType = ASN1Util.as(ASN1Integer.class, ASN1Util.as(DERTaggedObject.class, authElement, 0));
        DEROctetString authData = ASN1Util.as(DEROctetString.class, ASN1Util.as(DERTaggedObject.class, authElement, 1));

        this.authorizations.addAll(KerberosAuthData.parse(authType.getValue().intValue(), authData.getOctets(), keys));
    }
}
 
Example #12
Source File: ZipUtils.java    From isu with GNU General Public License v3.0 6 votes vote down vote up
/** Read a PKCS#8 format private key. */
private static PrivateKey readPrivateKey(InputStream input)
throws IOException, GeneralSecurityException {
    try {
        byte[] buffer = new byte[4096];
        int size = input.read(buffer);
        byte[] bytes = Arrays.copyOf(buffer, size);
        /* Check to see if this is in an EncryptedPrivateKeyInfo structure. */
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(bytes);
        /*
         * Now it's in a PKCS#8 PrivateKeyInfo structure. Read its Algorithm
         * OID and use that to construct a KeyFactory.
         */
        ASN1InputStream bIn = new ASN1InputStream(new ByteArrayInputStream(spec.getEncoded()));
        PrivateKeyInfo pki = PrivateKeyInfo.getInstance(bIn.readObject());
        String algOid = pki.getPrivateKeyAlgorithm().getAlgorithm().getId();
        return KeyFactory.getInstance(algOid).generatePrivate(spec);
    } finally {
        input.close();
    }
}
 
Example #13
Source File: DKeyUsage.java    From keystore-explorer with GNU General Public License v3.0 6 votes vote down vote up
private void prepopulateWithValue(byte[] value) throws IOException {
	try (ASN1InputStream asn1InputStream = new ASN1InputStream(value)) {
		DERBitString keyUsage = DERBitString.getInstance(asn1InputStream.readObject());

		int keyUsageValue = keyUsage.intValue();

		jcbDigitalSignature.setSelected(hasKeyUsage(keyUsageValue, KeyUsage.digitalSignature));
		jcbNonRepudiation.setSelected(hasKeyUsage(keyUsageValue, KeyUsage.nonRepudiation));
		jcbKeyEncipherment.setSelected(hasKeyUsage(keyUsageValue, KeyUsage.keyEncipherment));
		jcbDataEncipherment.setSelected(hasKeyUsage(keyUsageValue, KeyUsage.dataEncipherment));
		jcbKeyAgreement.setSelected(hasKeyUsage(keyUsageValue, KeyUsage.keyAgreement));
		jcbCertificateSigning.setSelected(hasKeyUsage(keyUsageValue, KeyUsage.keyCertSign));
		jcbCrlSign.setSelected(hasKeyUsage(keyUsageValue, KeyUsage.cRLSign));
		jcbEncipherOnly.setSelected(hasKeyUsage(keyUsageValue, KeyUsage.encipherOnly));
		jcbDecipherOnly.setSelected(hasKeyUsage(keyUsageValue, KeyUsage.decipherOnly));
	}
}
 
Example #14
Source File: DNetscapeCertificateType.java    From keystore-explorer with GNU General Public License v3.0 6 votes vote down vote up
private void prepopulateWithValue(byte[] value) throws IOException {
	try (ASN1InputStream asn1InputStream = new ASN1InputStream(value)) {
		DERBitString netscapeCertType = DERBitString.getInstance(asn1InputStream.readObject());

		int netscapeCertTypes = netscapeCertType.intValue();

		jcbSslClient.setSelected(isCertType(netscapeCertTypes, NetscapeCertType.sslClient));
		jcbSslServer.setSelected(isCertType(netscapeCertTypes, NetscapeCertType.sslServer));
		jcbSmime.setSelected(isCertType(netscapeCertTypes, NetscapeCertType.smime));
		jcbObjectSigning.setSelected(isCertType(netscapeCertTypes, NetscapeCertType.objectSigning));
		jcbReserved.setSelected(isCertType(netscapeCertTypes, NetscapeCertType.reserved));
		jcbSslCa.setSelected(isCertType(netscapeCertTypes, NetscapeCertType.sslCA));
		jcbSmimeCa.setSelected(isCertType(netscapeCertTypes, NetscapeCertType.smimeCA));
		jcbObjectSigningCa.setSelected(isCertType(netscapeCertTypes, NetscapeCertType.objectSigningCA));
	}
}
 
Example #15
Source File: AbstractRequirementChecks.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
@BeforeEach
public void init() throws Exception {
	DSSDocument signedDocument = getSignedDocument();

	ASN1InputStream asn1sInput = new ASN1InputStream(signedDocument.openStream());
	ASN1Sequence asn1Seq = (ASN1Sequence) asn1sInput.readObject();
	assertEquals(2, asn1Seq.size());
	ASN1ObjectIdentifier oid = ASN1ObjectIdentifier.getInstance(asn1Seq.getObjectAt(0));
	assertEquals(PKCSObjectIdentifiers.signedData, oid);

	ASN1TaggedObject taggedObj = ASN1TaggedObject.getInstance(asn1Seq.getObjectAt(1));
	signedData = SignedData.getInstance(taggedObj.getObject());

	ASN1Set signerInfosAsn1 = signedData.getSignerInfos();
	assertEquals(1, signerInfosAsn1.size());

	signerInfo = SignerInfo.getInstance(ASN1Sequence.getInstance(signerInfosAsn1.getObjectAt(0)));

	Utils.closeQuietly(asn1sInput);
}
 
Example #16
Source File: Asn1Utils.java    From android-testdpc with Apache License 2.0 6 votes vote down vote up
public static ASN1Sequence getAsn1SequenceFromStream(final ASN1InputStream asn1InputStream)
        throws IOException, CertificateParsingException {
    ASN1Primitive asn1Primitive = asn1InputStream.readObject();
    if (!(asn1Primitive instanceof ASN1OctetString)) {
        throw new CertificateParsingException(
                "Expected octet stream, found " + asn1Primitive.getClass().getName());
    }
    try (ASN1InputStream seqInputStream = new ASN1InputStream(
            ((ASN1OctetString) asn1Primitive).getOctets())) {
        asn1Primitive = seqInputStream.readObject();
        if (!(asn1Primitive instanceof ASN1Sequence)) {
            throw new CertificateParsingException(
                    "Expected sequence, found " + asn1Primitive.getClass().getName());
        }
        return (ASN1Sequence) asn1Primitive;
    }
}
 
Example #17
Source File: SoftKeymasterBlob.java    From keystore-decryptor with Apache License 2.0 6 votes vote down vote up
private void parseDsaKeyPair(byte[] blob) throws GeneralSecurityException,
        IOException {
    ASN1InputStream ain = new ASN1InputStream(new ByteArrayInputStream(
            blob));
    ASN1Sequence seq = (ASN1Sequence) ain.readObject();
    ain.close();

    ASN1Integer p = (ASN1Integer) seq.getObjectAt(1);
    ASN1Integer q = (ASN1Integer) seq.getObjectAt(2);
    ASN1Integer g = (ASN1Integer) seq.getObjectAt(3);
    ASN1Integer y = (ASN1Integer) seq.getObjectAt(4);
    ASN1Integer x = (ASN1Integer) seq.getObjectAt(5);
    DSAPrivateKeySpec privSpec = new DSAPrivateKeySpec(x.getValue(), p.getValue(),
            q.getValue(), g.getValue());
    DSAPublicKeySpec pubSpec = new DSAPublicKeySpec(y.getValue(), p.getValue(), q.getValue(),
            g.getValue());

    KeyFactory kf = KeyFactory.getInstance("DSA");
    privateKey = kf.generatePrivate(privSpec);
    publicKey = kf.generatePublic(pubSpec);
}
 
Example #18
Source File: BouncyCastleCrypto.java    From tutorials with MIT License 6 votes vote down vote up
public static boolean verifSignData(final byte[] signedData) throws CMSException, IOException, OperatorCreationException, CertificateException {
    ByteArrayInputStream bIn = new ByteArrayInputStream(signedData);
    ASN1InputStream aIn = new ASN1InputStream(bIn);
    CMSSignedData s = new CMSSignedData(ContentInfo.getInstance(aIn.readObject()));
    aIn.close();
    bIn.close();
    Store certs = s.getCertificates();
    SignerInformationStore signers = s.getSignerInfos();
    Collection<SignerInformation> c = signers.getSigners();
    SignerInformation signer = c.iterator().next();
    Collection<X509CertificateHolder> certCollection = certs.getMatches(signer.getSID());
    Iterator<X509CertificateHolder> certIt = certCollection.iterator();
    X509CertificateHolder certHolder = certIt.next();
    boolean verifResult = signer.verify(new JcaSimpleSignerInfoVerifierBuilder().build(certHolder));
    if (!verifResult) {
        return false;
    }
    return true;
}
 
Example #19
Source File: BouncyCastleCrypto.java    From fabric-api with Apache License 2.0 6 votes vote down vote up
@Override
public boolean verify(byte[] hash, byte[] signature, byte[] publicKey) {
    ASN1InputStream asn1 = new ASN1InputStream(signature);
    try {
        ECDSASigner signer = new ECDSASigner();
        signer.init(false, new ECPublicKeyParameters(curve.getCurve().decodePoint(publicKey), domain));

        DLSequence seq = (DLSequence) asn1.readObject();
        BigInteger r = ((ASN1Integer) seq.getObjectAt(0)).getPositiveValue();
        BigInteger s = ((ASN1Integer) seq.getObjectAt(1)).getPositiveValue();
        return signer.verifySignature(hash, r, s);
    } catch (Exception e) {
        return false;
    } finally {
        try {
            asn1.close();
        } catch (IOException ignored) {
        }
    }
}
 
Example #20
Source File: BouncyCastleCrypto.java    From fabric-api-archive with Apache License 2.0 6 votes vote down vote up
@Override
public boolean verify(byte[] hash, byte[] signature, byte[] publicKey) {
    ASN1InputStream asn1 = new ASN1InputStream(signature);
    try {
        ECDSASigner signer = new ECDSASigner();
        signer.init(false, new ECPublicKeyParameters(curve.getCurve().decodePoint(publicKey), domain));

        DLSequence seq = (DLSequence) asn1.readObject();
        BigInteger r = ((ASN1Integer) seq.getObjectAt(0)).getPositiveValue();
        BigInteger s = ((ASN1Integer) seq.getObjectAt(1)).getPositiveValue();
        return signer.verifySignature(hash, r, s);
    } catch (Exception e) {
        return false;
    } finally {
        try {
            asn1.close();
        } catch (IOException ignored) {
        }
    }
}
 
Example #21
Source File: DSSSignatureUtils.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Checks if the signature is ASN.1 encoded.
 *
 * @param signatureValue
 *            signature value to check.
 * @return if the signature is ASN.1 encoded.
 */
private static boolean isAsn1Encoded(byte[] signatureValue) {
	try (ASN1InputStream is = new ASN1InputStream(signatureValue)) {
		ASN1Sequence seq = (ASN1Sequence) is.readObject();
		return seq != null && seq.size() == 2;
	} catch (Exception e) {
		return false;
	}
}
 
Example #22
Source File: CAdESWithContentTimestampTest.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
protected DSSDocument getSignedDocument() {
	FileDocument fileDocument = new FileDocument("src/test/resources/validation/Signature-C-BES-4.p7m");
	
	try (InputStream is = fileDocument.openStream(); ASN1InputStream asn1sInput = new ASN1InputStream(is)) {
		ASN1Sequence asn1Seq = (ASN1Sequence) asn1sInput.readObject();

		ASN1TaggedObject taggedObj = ASN1TaggedObject.getInstance(asn1Seq.getObjectAt(1));
		ASN1Primitive object = taggedObj.getObject();
		SignedData signedData = SignedData.getInstance(object);

		ASN1Set signerInfosAsn1 = signedData.getSignerInfos();
		ASN1Sequence seqSignedInfo = ASN1Sequence.getInstance(signerInfosAsn1.getObjectAt(0));

		SignerInfo signedInfo = SignerInfo.getInstance(seqSignedInfo);
		ASN1Set authenticatedAttributes = signedInfo.getAuthenticatedAttributes();

		boolean found = false;
		for (int i = 0; i < authenticatedAttributes.size(); i++) {
			ASN1Sequence authAttrSeq = ASN1Sequence.getInstance(authenticatedAttributes.getObjectAt(i));
			ASN1ObjectIdentifier attrOid = ASN1ObjectIdentifier.getInstance(authAttrSeq.getObjectAt(0));
			if (PKCSObjectIdentifiers.id_aa_ets_contentTimestamp.equals(attrOid)) {
				found = true;
			}
		}
		assertTrue(found);
	} catch (Exception e) {
		fail(e);
	}
	
	return fileDocument;
}
 
Example #23
Source File: CMSUtils.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * This method returns an AttributeTable parsed from ASN.1 encoded representation
 *
 * @param encodedAttributes
 *            ASN.1 encoded AttributesTable
 * @return AttributeTable created from given encodedAttributes
 */
public static AttributeTable getAttributesFromByteArray(final byte[] encodedAttributes) {
	DLSet dlSet;
	try (ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(encodedAttributes))) {
		dlSet = (DLSet) asn1InputStream.readObject();
	} catch (IOException e) {
		throw new DSSException("Error while reading ASN.1 encoded attributes", e);
	}
	return new AttributeTable(dlSet);
}
 
Example #24
Source File: DSSSignatureUtils.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Converts an ASN.1 value to a XML Signature Value.
 *
 * The JAVA JCE ECDSA/DSA Signature algorithm creates ASN.1 encoded (r,s) value pairs; the XML Signature requires
 * the
 * core BigInteger values.
 *
 * @param binaries
 *            the ASN1 signature value
 * @return the decode bytes
 * @throws IOException
 * @see <A HREF="http://www.w3.org/TR/xmldsig-core/#dsa-sha1">6.4.1 DSA</A>
 * @see <A HREF="ftp://ftp.rfc-editor.org/in-notes/rfc4050.txt">3.3. ECDSA Signatures</A>
 */
private static byte[] convertASN1toXMLDSIG(byte[] binaries) {

	try (ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ASN1InputStream is = new ASN1InputStream(binaries)) {

		ASN1Sequence seq = (ASN1Sequence) is.readObject();
		if (seq.size() != 2) {
			throw new IllegalArgumentException("ASN1 Sequence size should be 2 !");
		}

		ASN1Integer r = (ASN1Integer) seq.getObjectAt(0);
		ASN1Integer s = (ASN1Integer) seq.getObjectAt(1);

		byte[] rBytes = BigIntegers.asUnsignedByteArray(r.getValue());
		int rSize = rBytes.length;
		byte[] sBytes = BigIntegers.asUnsignedByteArray(s.getValue());
		int sSize = sBytes.length;
		int max = Math.max(rSize, sSize);
		max = max % 2 == 0 ? max : max + 1;
		leftPad(buffer, max, rBytes);
		buffer.write(rBytes);
		leftPad(buffer, max, sBytes);
		buffer.write(sBytes);

		return buffer.toByteArray();
	} catch (Exception e) {
		throw new DSSException("Unable to convert to xmlDsig : " + e.getMessage(), e);
	}
}
 
Example #25
Source File: CAdESLevelBExternalSignatureTest.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
private ExternalSignatureResult simulateExternalSignature(ToBeSigned toBeSigned) {
	ExternalSignatureResult externalSignatureResult = new ExternalSignatureResult();

	// Get hold of signature certificate.
	CertificateToken signingCertificate = getSigningCert();
	externalSignatureResult.setSigningCertificate(signingCertificate);

	DigestAlgorithm digestAlgo = signatureParameters.getDigestAlgorithm();

	// Add the signing-certificate/signing-certificate-v2 attribute to DER encoded SignedAttributes.
	try (ASN1InputStream asn1InputStream = new ASN1InputStream(toBeSigned.getBytes())) {
		DLSet dlSet = (DLSet) asn1InputStream.readObject();
		AttributeTable signedAttribute = new AttributeTable(dlSet);
		ASN1EncodableVector signedAttributeEncodableVector = signedAttribute.toASN1EncodableVector();

		CMSUtils.addSigningCertificateAttribute(signedAttributeEncodableVector, digestAlgo, signingCertificate);

		DERSet signedAttributesData = new DERSet(signedAttributeEncodableVector);

		// Update toBeSigned
		toBeSigned.setBytes(signedAttributesData.getEncoded());
		externalSignatureResult.setSignedData(toBeSigned.getBytes());
	} catch (Exception e) {
		LOG.error("Error while simulating external CAdES signature", e);
	}

	SignatureValue signatureValue = getToken().sign(toBeSigned, getSignatureParameters().getDigestAlgorithm(),
			getSignatureParameters().getMaskGenerationFunction(), getPrivateKeyEntry());
	externalSignatureResult.setSignatureValue(signatureValue);

	return externalSignatureResult;
}
 
Example #26
Source File: PAdESLevelBExternalSignatureTest.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
private ExternalSignatureResult simulateExternalSignature(ToBeSigned toBeSigned) {
	ExternalSignatureResult externalSignatureResult = new ExternalSignatureResult();

	// Get hold of signature certificate.
	CertificateToken signingCertificate = getSigningCert();
	externalSignatureResult.setSigningCertificate(signingCertificate);

	DigestAlgorithm digestAlgo = signatureParameters.getDigestAlgorithm();

	// Add the signing-certificate/signing-certificate-v2 attribute to DER encoded SignedAttributes.
	try (ASN1InputStream asn1InputStream = new ASN1InputStream(toBeSigned.getBytes())) {
		DLSet dlSet = (DLSet) asn1InputStream.readObject();
		AttributeTable signedAttribute = new AttributeTable(dlSet);
		ASN1EncodableVector signedAttributeEncodableVector = signedAttribute.toASN1EncodableVector();

		CMSUtils.addSigningCertificateAttribute(signedAttributeEncodableVector, digestAlgo, signingCertificate);

		DERSet signedAttributesData = new DERSet(signedAttributeEncodableVector);

		// Update toBeSigned
		toBeSigned.setBytes(signedAttributesData.getEncoded());
		externalSignatureResult.setSignedData(toBeSigned.getBytes());
	} catch (Exception e) {
		LOG.error("Error while simulating external PAdES signature", e);
	}

	SignatureValue signatureValue = getToken().sign(toBeSigned, digestAlgo, getSignatureParameters().getMaskGenerationFunction(), getPrivateKeyEntry());
	externalSignatureResult.setSignatureValue(signatureValue);

	return externalSignatureResult;
}
 
Example #27
Source File: DERUtils.java    From InflatableDonkey with MIT License 5 votes vote down vote up
public static <T> Optional<T> parse(byte[] data, Function<ASN1Primitive, T> function) {
    try (ASN1InputStream asN1InputStream = new ASN1InputStream(data)) {
        ASN1Primitive primitive = asN1InputStream.readObject();

        return parse(primitive, function);

    } catch (IOException ex) {
        logger.warn("-- parse() - IOException: {}", ex);
        return Optional.empty();
    }
}
 
Example #28
Source File: DSSASN1Utils.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static byte[] getDEROctetStringContent(byte[] bytes) {
	try (ASN1InputStream input = new ASN1InputStream(bytes)) {
		final DEROctetString s = (DEROctetString) input.readObject();
		return s.getOctets();
	} catch (IOException e) {
		throw new DSSException("Unable to retrieve the DEROctetString content", e);
	}
}
 
Example #29
Source File: DSSASN1Utils.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static ASN1Sequence getASN1Sequence(byte[] bytes) {
	try (ASN1InputStream input = new ASN1InputStream(bytes)) {
		return (ASN1Sequence) input.readObject();
	} catch (IOException e) {
		throw new DSSException("Unable to retrieve the ASN1Sequence", e);
	}
}
 
Example #30
Source File: Asn1Utils.java    From Auditor with MIT License 5 votes vote down vote up
public static ASN1Encodable getAsn1EncodableFromBytes(byte[] bytes)
        throws CertificateParsingException {
    try (ASN1InputStream asn1InputStream = new ASN1InputStream(bytes)) {
        return asn1InputStream.readObject();
    } catch (IOException e) {
        throw new CertificateParsingException("Failed to parse Encodable", e);
    }
}