List of usage examples for org.bouncycastle.asn1 ASN1InputStream readObject
public ASN1Primitive readObject() throws IOException
From source file:eu.europa.esig.dss.DSSASN1Utils.java
License:Open Source License
/** * This method returns the {@code ASN1Sequence} encapsulated in {@code DEROctetString}. The {@code DEROctetString} * is represented as {@code byte} array. * * @param bytes//from ww w . j a v a 2s.com * {@code byte} representation of {@code DEROctetString} * @return encapsulated {@code ASN1Sequence} * @throws DSSException * in case of a decoding problem */ public static ASN1Sequence getAsn1SequenceFromDerOctetString(byte[] bytes) throws DSSException { ASN1InputStream input = null; try { input = new ASN1InputStream(bytes); final DEROctetString s = (DEROctetString) input.readObject(); final byte[] content = s.getOctets(); input.close(); input = new ASN1InputStream(content); final ASN1Sequence seq = (ASN1Sequence) input.readObject(); return seq; } catch (IOException e) { throw new DSSException("Error when computing certificate's extensions.", e); } finally { IOUtils.closeQuietly(input); } }
From source file:eu.europa.esig.dss.pades.InfiniteLoopDSS621Test.java
License:Open Source License
/** * These signatures are invalid because of non ordered signed attributes */// w ww . j a v a 2 s . co m @Test public void manualTest() throws Exception { File pdfFile = new File(FILE_PATH); FileInputStream fis = new FileInputStream(pdfFile); byte[] pdfBytes = IOUtils.toByteArray(fis); PDDocument document = PDDocument.load(pdfFile); List<PDSignature> signatures = document.getSignatureDictionaries(); assertEquals(6, signatures.size()); int idx = 0; for (PDSignature pdSignature : signatures) { byte[] contents = pdSignature.getContents(pdfBytes); byte[] signedContent = pdSignature.getSignedContent(pdfBytes); logger.info("Byte range : " + Arrays.toString(pdSignature.getByteRange())); IOUtils.write(contents, new FileOutputStream("target/sig" + (idx++) + ".p7s")); ASN1InputStream asn1sInput = new ASN1InputStream(contents); ASN1Sequence asn1Seq = (ASN1Sequence) asn1sInput.readObject(); logger.info("SEQ : " + asn1Seq.toString()); ASN1ObjectIdentifier oid = ASN1ObjectIdentifier.getInstance(asn1Seq.getObjectAt(0)); assertEquals(PKCSObjectIdentifiers.signedData, oid); SignedData signedData = SignedData .getInstance(DERTaggedObject.getInstance(asn1Seq.getObjectAt(1)).getObject()); ASN1Set digestAlgorithmSet = signedData.getDigestAlgorithms(); ASN1ObjectIdentifier oidDigestAlgo = ASN1ObjectIdentifier .getInstance(ASN1Sequence.getInstance(digestAlgorithmSet.getObjectAt(0)).getObjectAt(0)); DigestAlgorithm digestAlgorithm = DigestAlgorithm.forOID(oidDigestAlgo.getId()); logger.info("DIGEST ALGO : " + digestAlgorithm); ContentInfo encapContentInfo = signedData.getEncapContentInfo(); ASN1ObjectIdentifier contentTypeOID = encapContentInfo.getContentType(); logger.info("ENCAPSULATED CONTENT INFO TYPE : " + contentTypeOID); if (!PKCSObjectIdentifiers.id_ct_TSTInfo.equals(contentTypeOID)) { // If not timestamp assertEquals(PKCSObjectIdentifiers.data, contentTypeOID); ASN1Encodable content = encapContentInfo.getContent(); logger.info("ENCAPSULATED CONTENT INFO CONTENT : " + content); assertNull(content); List<X509Certificate> certificates = extractCertificates(signedData); ASN1Set signerInfosAsn1 = signedData.getSignerInfos(); logger.info("SIGNER INFO ASN1 : " + signerInfosAsn1.toString()); SignerInfo signedInfo = SignerInfo .getInstance(ASN1Sequence.getInstance(signerInfosAsn1.getObjectAt(0))); ASN1Set authenticatedAttributeSet = signedInfo.getAuthenticatedAttributes(); logger.info("AUTHENTICATED ATTR : " + authenticatedAttributeSet); Attribute attributeDigest = null; for (int i = 0; i < authenticatedAttributeSet.size(); i++) { Attribute attribute = Attribute.getInstance(authenticatedAttributeSet.getObjectAt(i)); if (PKCSObjectIdentifiers.pkcs_9_at_messageDigest.equals(attribute.getAttrType())) { attributeDigest = attribute; break; } } assertNotNull(attributeDigest); ASN1OctetString asn1ObjString = ASN1OctetString .getInstance(attributeDigest.getAttrValues().getObjectAt(0)); String embeddedDigest = Base64.encodeBase64String(asn1ObjString.getOctets()); logger.info("MESSAGE DIGEST : " + embeddedDigest); byte[] digestSignedContent = DSSUtils.digest(digestAlgorithm, signedContent); String computedDigestSignedContentEncodeBase64 = Base64.encodeBase64String(digestSignedContent); logger.info("COMPUTED DIGEST SIGNED CONTENT BASE64 : " + computedDigestSignedContentEncodeBase64); assertEquals(embeddedDigest, computedDigestSignedContentEncodeBase64); SignerIdentifier sid = signedInfo.getSID(); logger.info("SIGNER IDENTIFIER : " + sid.getId()); IssuerAndSerialNumber issuerAndSerialNumber = IssuerAndSerialNumber .getInstance(signedInfo.getSID()); ASN1Integer signerSerialNumber = issuerAndSerialNumber.getSerialNumber(); logger.info("ISSUER AND SN : " + issuerAndSerialNumber.getName() + " " + signerSerialNumber); BigInteger serial = issuerAndSerialNumber.getSerialNumber().getValue(); X509Certificate signerCertificate = null; for (X509Certificate x509Certificate : certificates) { if (serial.equals(x509Certificate.getSerialNumber())) { signerCertificate = x509Certificate; } } assertNotNull(signerCertificate); String algorithm = signerCertificate.getPublicKey().getAlgorithm(); EncryptionAlgorithm encryptionAlgorithm = EncryptionAlgorithm.forName(algorithm); ASN1OctetString encryptedInfoOctedString = signedInfo.getEncryptedDigest(); String signatureValue = Hex.toHexString(encryptedInfoOctedString.getOctets()); logger.info("SIGNATURE VALUE : " + signatureValue); Cipher cipher = Cipher.getInstance(encryptionAlgorithm.getName()); cipher.init(Cipher.DECRYPT_MODE, signerCertificate); byte[] decrypted = cipher.doFinal(encryptedInfoOctedString.getOctets()); ASN1InputStream inputDecrypted = new ASN1InputStream(decrypted); ASN1Sequence seqDecrypt = (ASN1Sequence) inputDecrypted.readObject(); logger.info("DECRYPTED : " + seqDecrypt); DigestInfo digestInfo = new DigestInfo(seqDecrypt); assertEquals(oidDigestAlgo, digestInfo.getAlgorithmId().getAlgorithm()); String decryptedDigestEncodeBase64 = Base64.encodeBase64String(digestInfo.getDigest()); logger.info("DECRYPTED BASE64 : " + decryptedDigestEncodeBase64); byte[] encoded = authenticatedAttributeSet.getEncoded(); byte[] digest = DSSUtils.digest(digestAlgorithm, encoded); String computedDigestFromSignatureEncodeBase64 = Base64.encodeBase64String(digest); logger.info("COMPUTED DIGEST FROM SIGNATURE BASE64 : " + computedDigestFromSignatureEncodeBase64); assertEquals(decryptedDigestEncodeBase64, computedDigestFromSignatureEncodeBase64); IOUtils.closeQuietly(inputDecrypted); } IOUtils.closeQuietly(asn1sInput); } IOUtils.closeQuietly(fis); document.close(); }
From source file:eu.europa.esig.dss.pades.signature.PAdESLevelBTest.java
License:Open Source License
@Override protected void onDocumentSigned(byte[] byteArray) { try {//from w ww. ja v a 2s . c o m InputStream inputStream = new ByteArrayInputStream(byteArray); PDDocument document = PDDocument.load(inputStream); List<PDSignature> signatures = document.getSignatureDictionaries(); assertEquals(1, signatures.size()); for (PDSignature pdSignature : signatures) { byte[] contents = pdSignature.getContents(byteArray); byte[] signedContent = pdSignature.getSignedContent(byteArray); logger.info("Byte range : " + Arrays.toString(pdSignature.getByteRange())); // IOUtils.write(contents, new FileOutputStream("sig.p7s")); ASN1InputStream asn1sInput = new ASN1InputStream(contents); ASN1Sequence asn1Seq = (ASN1Sequence) asn1sInput.readObject(); logger.info("SEQ : " + asn1Seq.toString()); ASN1ObjectIdentifier oid = ASN1ObjectIdentifier.getInstance(asn1Seq.getObjectAt(0)); assertEquals(PKCSObjectIdentifiers.signedData, oid); SignedData signedData = SignedData .getInstance(DERTaggedObject.getInstance(asn1Seq.getObjectAt(1)).getObject()); ASN1Set digestAlgorithmSet = signedData.getDigestAlgorithms(); ASN1ObjectIdentifier oidDigestAlgo = ASN1ObjectIdentifier .getInstance(ASN1Sequence.getInstance(digestAlgorithmSet.getObjectAt(0)).getObjectAt(0)); DigestAlgorithm digestAlgorithm = DigestAlgorithm.forOID(oidDigestAlgo.getId()); logger.info("DIGEST ALGO : " + digestAlgorithm); ContentInfo encapContentInfo = signedData.getEncapContentInfo(); ASN1ObjectIdentifier contentTypeOID = encapContentInfo.getContentType(); logger.info("ENCAPSULATED CONTENT INFO TYPE : " + contentTypeOID); assertEquals(PKCSObjectIdentifiers.data, contentTypeOID); ASN1Encodable content = encapContentInfo.getContent(); logger.info("ENCAPSULATED CONTENT INFO CONTENT : " + content); assertNull(content); List<X509Certificate> certificates = extractCertificates(signedData); ASN1Set signerInfosAsn1 = signedData.getSignerInfos(); logger.info("SIGNER INFO ASN1 : " + signerInfosAsn1.toString()); SignerInfo signedInfo = SignerInfo .getInstance(ASN1Sequence.getInstance(signerInfosAsn1.getObjectAt(0))); ASN1Set authenticatedAttributeSet = signedInfo.getAuthenticatedAttributes(); logger.info("AUTHENTICATED ATTR : " + authenticatedAttributeSet); List<ASN1ObjectIdentifier> attributeOids = new ArrayList<ASN1ObjectIdentifier>(); int previousSize = 0; for (int i = 0; i < authenticatedAttributeSet.size(); i++) { Attribute attribute = Attribute.getInstance(authenticatedAttributeSet.getObjectAt(i)); ASN1ObjectIdentifier attrTypeOid = attribute.getAttrType(); attributeOids.add(attrTypeOid); int size = attrTypeOid.getEncoded().length + attribute.getEncoded().length; assertTrue(size >= previousSize); previousSize = size; } logger.info("List of OID for Auth Attrb : " + attributeOids); Attribute attributeDigest = Attribute.getInstance(authenticatedAttributeSet.getObjectAt(1)); assertEquals(PKCSObjectIdentifiers.pkcs_9_at_messageDigest, attributeDigest.getAttrType()); ASN1OctetString asn1ObjString = ASN1OctetString .getInstance(attributeDigest.getAttrValues().getObjectAt(0)); String embeddedDigest = Base64.encodeBase64String(asn1ObjString.getOctets()); logger.info("MESSAGE DIGEST : " + embeddedDigest); byte[] digestSignedContent = DSSUtils.digest(digestAlgorithm, signedContent); String computedDigestSignedContentEncodeBase64 = Base64.encodeBase64String(digestSignedContent); logger.info("COMPUTED DIGEST SIGNED CONTENT BASE64 : " + computedDigestSignedContentEncodeBase64); assertEquals(embeddedDigest, computedDigestSignedContentEncodeBase64); SignerIdentifier sid = signedInfo.getSID(); logger.info("SIGNER IDENTIFIER : " + sid.getId()); IssuerAndSerialNumber issuerAndSerialNumber = IssuerAndSerialNumber .getInstance(signedInfo.getSID()); ASN1Integer signerSerialNumber = issuerAndSerialNumber.getSerialNumber(); logger.info("ISSUER AND SN : " + issuerAndSerialNumber.getName() + " " + signerSerialNumber); BigInteger serial = issuerAndSerialNumber.getSerialNumber().getValue(); X509Certificate signerCertificate = null; for (X509Certificate x509Certificate : certificates) { if (serial.equals(x509Certificate.getSerialNumber())) { signerCertificate = x509Certificate; } } assertNotNull(signerCertificate); String algorithm = signerCertificate.getPublicKey().getAlgorithm(); EncryptionAlgorithm encryptionAlgorithm = EncryptionAlgorithm.forName(algorithm); ASN1OctetString encryptedInfoOctedString = signedInfo.getEncryptedDigest(); String signatureValue = Hex.toHexString(encryptedInfoOctedString.getOctets()); logger.info("SIGNATURE VALUE : " + signatureValue); Cipher cipher = Cipher.getInstance(encryptionAlgorithm.getName()); cipher.init(Cipher.DECRYPT_MODE, signerCertificate); byte[] decrypted = cipher.doFinal(encryptedInfoOctedString.getOctets()); ASN1InputStream inputDecrypted = new ASN1InputStream(decrypted); ASN1Sequence seqDecrypt = (ASN1Sequence) inputDecrypted.readObject(); logger.info("DECRYPTED : " + seqDecrypt); DigestInfo digestInfo = new DigestInfo(seqDecrypt); assertEquals(oidDigestAlgo, digestInfo.getAlgorithmId().getAlgorithm()); String decryptedDigestEncodeBase64 = Base64.encodeBase64String(digestInfo.getDigest()); logger.info("DECRYPTED BASE64 : " + decryptedDigestEncodeBase64); byte[] encoded = authenticatedAttributeSet.getEncoded(); byte[] digest = DSSUtils.digest(digestAlgorithm, encoded); String computedDigestFromSignatureEncodeBase64 = Base64.encodeBase64String(digest); logger.info("COMPUTED DIGEST FROM SIGNATURE BASE64 : " + computedDigestFromSignatureEncodeBase64); assertEquals(decryptedDigestEncodeBase64, computedDigestFromSignatureEncodeBase64); IOUtils.closeQuietly(inputDecrypted); IOUtils.closeQuietly(asn1sInput); } IOUtils.closeQuietly(inputStream); document.close(); } catch (Exception e) { logger.error(e.getMessage(), e); fail(e.getMessage()); } }
From source file:eu.europa.esig.dss.xades.signature.DSSSignatureUtils.java
License:Open Source License
/** * Converts an ASN.1 ECDSA value to a XML Signature ECDSA Value. * * The JAVA JCE ECDSA Signature algorithm creates ASN.1 encoded (r,s) value pairs; the XML Signature requires the * core BigInteger values./*from w w w. j a v a 2s . co m*/ * * @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[] convertECDSAASN1toXMLDSIG(byte[] binaries) { ASN1InputStream is = null; try { 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 = r.getValue().toByteArray(); int rSize = rBytes.length; byte[] sBytes = s.getValue().toByteArray(); int sSize = sBytes.length; int max = Math.max(rSize, sSize); ByteArrayOutputStream buffer = new ByteArrayOutputStream(max * 2); if (sSize > rSize) { buffer.write(0x00); } buffer.write(rBytes); if (rSize > sSize) { buffer.write(0x00); } buffer.write(sBytes); return buffer.toByteArray(); } catch (Exception e) { throw new DSSException("Unable to convert to xmlDsig : " + e.getMessage(), e); } finally { IOUtils.closeQuietly(is); } }
From source file:eu.europa.esig.dss.xades.signature.DSSSignatureUtils.java
License:Open Source License
/** * Converts an ASN.1 DSA value to a XML Signature DSA Value. * * The JAVA JCE DSA Signature algorithm creates ASN.1 encoded (r,s) value pairs; the XML Signature requires the * core BigInteger values.//w w w . j a v a2s .co m * * @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[] convertDSAASN1toXMLDSIG(byte[] binaries) { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ASN1InputStream is = null; try { 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); buffer.write(BigIntegers.asUnsignedByteArray(r.getValue())); buffer.write(BigIntegers.asUnsignedByteArray(s.getValue())); } catch (Exception e) { throw new DSSException("Unable to convert to xmlDsig : " + e.getMessage(), e); } finally { IOUtils.closeQuietly(is); } return buffer.toByteArray(); }
From source file:eu.europa.esig.dss.xades.validation.XAdESSignature.java
License:Open Source License
@Override public void checkSigningCertificate() { final CandidatesForSigningCertificate candidates = getCandidatesForSigningCertificate(); /**//from w ww . j av a 2 s. co m * The ../SignedProperties/SignedSignatureProperties/SigningCertificate element MAY contain references and * digests values of other certificates (that * MAY form a chain up to the point of trust). */ boolean isEn319132 = false; NodeList list = DSSXMLUtils.getNodeList(signatureElement, xPathQueryHolder.XPATH_SIGNING_CERTIFICATE_CERT); int length = list.getLength(); if (length == 0) { list = DSSXMLUtils.getNodeList(signatureElement, xPathQueryHolder.XPATH_SIGNING_CERTIFICATE_CERT_V2); length = list.getLength(); isEn319132 = true; } if (length == 0) { final CertificateValidity theCertificateValidity = candidates.getTheCertificateValidity(); final CertificateToken certificateToken = theCertificateValidity == null ? null : theCertificateValidity.getCertificateToken(); // The check need to be done at the level of KeyInfo for (final Reference reference : references) { final String uri = reference.getURI(); if (!uri.startsWith("#")) { continue; } final String id = uri.substring(1); final Element element = signatureElement.getOwnerDocument().getElementById(id); // final Element element = // DSSXMLUtils.getElement(signatureElement, ""); if (!hasSignatureAsParent(element)) { continue; } if ((certificateToken != null) && id.equals(certificateToken.getXmlId())) { theCertificateValidity.setSigned(element.getNodeName()); return; } } } // This Map contains the list of the references to the certificate which // were already checked and which correspond to a certificate. Map<Element, Boolean> alreadyProcessedElements = new HashMap<Element, Boolean>(); final List<CertificateValidity> certificateValidityList = candidates.getCertificateValidityList(); for (final CertificateValidity certificateValidity : certificateValidityList) { final CertificateToken certificateToken = certificateValidity.getCertificateToken(); for (int ii = 0; ii < length; ii++) { certificateValidity.setAttributePresent(true); final Element element = (Element) list.item(ii); if (alreadyProcessedElements.containsKey(element)) { continue; } final Element certDigestElement = DSSXMLUtils.getElement(element, xPathQueryHolder.XPATH__CERT_DIGEST); certificateValidity.setDigestPresent(certDigestElement != null); final Element digestMethodElement = DSSXMLUtils.getElement(certDigestElement, xPathQueryHolder.XPATH__DIGEST_METHOD); if (digestMethodElement == null) { continue; } final String xmlAlgorithmName = digestMethodElement.getAttribute(XMLE_ALGORITHM); // The default algorithm is used in case of bad encoded // algorithm name final DigestAlgorithm digestAlgorithm = DigestAlgorithm.forXML(xmlAlgorithmName, DigestAlgorithm.SHA1); final Element digestValueElement = DSSXMLUtils.getElement(element, xPathQueryHolder.XPATH__CERT_DIGEST_DIGEST_VALUE); if (digestValueElement == null) { continue; } // That must be a binary comparison final byte[] storedBase64DigestValue = DSSUtils .base64StringToBase64Binary(digestValueElement.getTextContent()); /** * Step 1:<br> * Take the first child of the property and check that the content of ds:DigestValue matches the result * of digesting <i>the candidate for</i> * the signing certificate with the algorithm indicated in ds:DigestMethod. If they do not match, take * the next child and repeat this step until * a matching child element has been found or all children of the element have been checked. If they do * match, continue with step 2. If the last * element is reached without finding any match, the validation of this property shall be taken as * failed and INVALID/FORMAT_FAILURE is * returned. */ final byte[] digest = DSSUtils.digest(digestAlgorithm, certificateToken.getEncoded()); final byte[] recalculatedBase64DigestValue = Base64.encodeBase64(digest); certificateValidity.setDigestEqual(false); BigInteger serialNumber = new BigInteger("0"); if (Arrays.equals(recalculatedBase64DigestValue, storedBase64DigestValue)) { X500Principal issuerName = null; if (isEn319132) { final Element issuerNameEl = DSSXMLUtils.getElement(element, xPathQueryHolder.XPATH__X509_ISSUER_V2); if (issuerNameEl != null) { final String textContent = issuerNameEl.getTextContent(); ASN1InputStream is = null; GeneralName name = null; ASN1Integer serial = null; try { is = new ASN1InputStream(Base64.decodeBase64(textContent)); ASN1Sequence seq = (ASN1Sequence) is.readObject(); ASN1Sequence obj = (ASN1Sequence) seq.getObjectAt(0); name = GeneralName.getInstance(obj.getObjectAt(0)); serial = (ASN1Integer) seq.getObjectAt(1); } catch (IOException e) { LOG.error("Unable to decode textContent " + textContent + " : " + e.getMessage(), e); } finally { IOUtils.closeQuietly(is); } try { issuerName = new X500Principal(name.getName().toASN1Primitive().getEncoded()); } catch (Exception e) { LOG.error("Unable to decode X500Principal : " + e.getMessage(), e); } try { serialNumber = serial.getValue(); } catch (Exception e) { LOG.error("Unable to decode serialNumber : " + e.getMessage(), e); } } } else { final Element issuerNameEl = DSSXMLUtils.getElement(element, xPathQueryHolder.XPATH__X509_ISSUER_NAME); // This can be allayed when the distinguished name is not // correctly encoded // final String textContent = // DSSUtils.unescapeMultiByteUtf8Literals(issuerNameEl.getTextContent()); final String textContent = issuerNameEl.getTextContent(); issuerName = DSSUtils.getX500PrincipalOrNull(textContent); final Element serialNumberEl = DSSXMLUtils.getElement(element, xPathQueryHolder.XPATH__X509_SERIAL_NUMBER); final String serialNumberText = serialNumberEl.getTextContent(); // serial number can contain leading and trailing whitespace. serialNumber = new BigInteger(serialNumberText.trim()); } final X500Principal candidateIssuerName = certificateToken.getIssuerX500Principal(); final boolean issuerNameMatches = DSSUtils.x500PrincipalAreEquals(candidateIssuerName, issuerName); if (!issuerNameMatches) { final String c14nCandidateIssuerName = candidateIssuerName.getName(X500Principal.CANONICAL); LOG.info("candidateIssuerName: " + c14nCandidateIssuerName); final String c14nIssuerName = issuerName == null ? "" : issuerName.getName(X500Principal.CANONICAL); LOG.info("issuerName : " + c14nIssuerName); } final BigInteger candidateSerialNumber = certificateToken.getSerialNumber(); final boolean serialNumberMatches = candidateSerialNumber.equals(serialNumber); certificateValidity.setDigestEqual(true); certificateValidity.setSerialNumberEqual(serialNumberMatches); certificateValidity.setDistinguishedNameEqual(issuerNameMatches); // The certificate was identified alreadyProcessedElements.put(element, true); // If the signing certificate is not set yet then it must be // done now. Actually if the signature is tempered then the // method checkSignatureIntegrity cannot set the signing // certificate. if (candidates.getTheCertificateValidity() == null) { candidates.setTheCertificateValidity(certificateValidity); } break; } } } }
From source file:ezbake.crypto.RSAKeyCrypto.java
License:Apache License
private static PublicKey fixPubKey(byte[] orig) throws InvalidKeySpecException, NoSuchAlgorithmException { try {/* ww w. ja v a2s . c o m*/ ASN1InputStream in = new ASN1InputStream(orig); ASN1Primitive obj = in.readObject(); RSAPublicKeyStructure keyStruct = RSAPublicKeyStructure.getInstance(obj); RSAPublicKeySpec keySpec = new RSAPublicKeySpec(keyStruct.getModulus(), keyStruct.getPublicExponent()); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); return keyFactory.generatePublic(keySpec); } catch (IOException e) { throw new InvalidKeySpecException("Unable to load public key with stopgap ASN1 method", e); } }
From source file:fi.aalto.cs.drumbeat.CertificateCommons.java
License:Open Source License
public static SubjectKeyIdentifier createSubjectKeyIdentifier(Key key) throws IOException { ASN1InputStream is = null; try {//w ww .j a v a 2 s . c om is = new ASN1InputStream(new ByteArrayInputStream(key.getEncoded())); ASN1Sequence seq = (ASN1Sequence) is.readObject(); @SuppressWarnings("deprecation") SubjectPublicKeyInfo info = new SubjectPublicKeyInfo(seq); return new BcX509ExtensionUtils().createSubjectKeyIdentifier(info); } finally { is.close(); } }
From source file:fi.laverca.Pkcs7.java
License:Apache License
/** * Convert a byte array to a PKCS7 SignedData object * @param bytes byte array/*from w w w . j a v a 2s .com*/ * @return PKCS7 SignedData object */ public static SignedData bytesToPkcs7SignedData(byte[] bytes) { if (bytes == null) { throw new IllegalArgumentException("null bytes"); } ASN1InputStream ais = new ASN1InputStream(bytes); ASN1Object asn1 = null; try { asn1 = ais.readObject(); } catch (IOException ioe) { throw new IllegalArgumentException("not a pkcs7 signature"); } finally { try { ais.close(); } catch (IOException e) { // Ignore } } ContentInfo ci = ContentInfo.getInstance(asn1); DERObjectIdentifier typeId = ci.getContentType(); if (!typeId.equals(PKCSObjectIdentifiers.signedData)) { throw new IllegalArgumentException("not a pkcs7 signature"); } return SignedData.getInstance(ci.getContent()); }
From source file:fr.insalyon.creatis.vip.core.server.business.proxy.ProxyClient.java
License:Open Source License
private void printKey(PrivateKey key, PrintStream out) throws IOException { out.println("-----BEGIN RSA PRIVATE KEY-----"); ByteArrayInputStream inStream = new ByteArrayInputStream(key.getEncoded()); ASN1InputStream derInputStream = new ASN1InputStream(inStream); ASN1Primitive keyInfo = derInputStream.readObject(); PrivateKeyInfo pki;//from w w w . ja va 2 s . c om pki = PrivateKeyInfo.getInstance(keyInfo); ASN1Primitive innerType = pki.parsePrivateKey().toASN1Primitive(); // build and return the actual key ASN1Sequence privKey = (ASN1Sequence) innerType; ByteArrayOutputStream bout = new ByteArrayOutputStream(); DEROutputStream der = new DEROutputStream(bout); der.writeObject(privKey); printB64(bout.toByteArray(), out); out.println("-----END RSA PRIVATE KEY-----"); }