public TestResult pkcs10Test(String testName, byte[] req) { try { ByteArrayInputStream bIn = new ByteArrayInputStream(req); ASN1InputStream aIn = new ASN1InputStream(bIn); CertificationRequest r = new CertificationRequest((ASN1Sequence) aIn.readObject()); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); DEROutputStream dOut = new DEROutputStream(bOut); dOut.writeObject(r.getDERObject()); byte[] bytes = bOut.toByteArray(); if (bytes.length != req.length) { return new SimpleTestResult(false, getName() + ": " + testName + " failed length test"); } for (int i = 0; i != req.length; i++) { if (bytes[i] != req[i]) { return new SimpleTestResult( false, getName() + ": " + testName + " failed comparison test"); } } } catch (Exception e) { return new SimpleTestResult( false, getName() + ": Exception - " + testName + " " + e.toString()); } return new SimpleTestResult(true, getName() + ": Okay"); }
/** * Parse the given X.509 name into DER encoded byte array representation. * * @param the X.509 name in well known String format * @return the X.509 name as byte array * @exception IOException if the String could not be parsed */ private static byte[] parseX509Name(String data) throws IOException { // TODO more test for illegal charateers ByteArrayOutputStream outStream = new ByteArrayOutputStream(); DEROutputStream derOutStream = new DEROutputStream(outStream); derOutStream.writeObject(new X509Name(trimX509Name(data))); derOutStream.close(); return outStream.toByteArray(); }
/** * Returns the ASN.1 encoding of this object. * * @returns the ASN.1 encoding. * @throws IOException if error occurs when constructing its ASN.1 encoding. */ public byte[] getEncoded() throws IOException { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); DEROutputStream dOut = new DEROutputStream(bOut); dOut.writeObject(infoObj); dOut.close(); return bOut.toByteArray(); }
/** * Parse the given DNS name into DER encoded byte array representation. The String must be in den * preffered name syntax as defined in RFC 1034. * * @param the DNS name in well known String format * @return the DNS name as byte array * @exception IOException if the String could not be parsed */ private static byte[] parseDNSName(String data) throws IOException { // TODO more test for illegal charateers ASN1Object derData = new DERIA5String(data); ByteArrayOutputStream outStream = new ByteArrayOutputStream(); DEROutputStream derOutStream = new DEROutputStream(outStream); derOutStream.writeObject(derData); derOutStream.close(); return outStream.toByteArray(); }
/** * Parse the given URI into DER encoded byte array representation. * * @param the URI in well known String format * @return the URI as byte array * @exception IOException if the String could not be parsed */ private static byte[] parseURI(String data) throws IOException { // TODO do parsing test ASN1Object derData = new DERIA5String(data); ByteArrayOutputStream outStream = new ByteArrayOutputStream(); DEROutputStream derOutStream = new DEROutputStream(outStream); derOutStream.writeObject(derData); derOutStream.close(); return outStream.toByteArray(); }
/** * Parse the given rfc822 addr-spec into DER encoded byte array representation. * * @param the rfc822 addr-spec in well known String format * @return the rfc822 addr-spec as byte array * @exception IOException if the String could not be parsed */ private static byte[] parseRfc822(String data) throws IOException { int tmpInt = data.indexOf('@'); if (tmpInt < 0 || tmpInt >= data.length() - 1) { throw new IOException("wrong format of rfc822Name:" + data); } // TODO more test for illegal charateers ASN1Object derData = new DERIA5String(data); ByteArrayOutputStream outStream = new ByteArrayOutputStream(); DEROutputStream derOutStream = new DEROutputStream(outStream); derOutStream.writeObject(derData); derOutStream.close(); return outStream.toByteArray(); }
private AlgorithmParameters getParameters() throws NoSuchAlgorithmException { AlgorithmParameters ap = AlgorithmParameters.getInstance(this.getAlgName()); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); DEROutputStream dOut = new DEROutputStream(bOut); try { dOut.writeObject(infoObj.getEncryptionAlgorithm().getParameters()); dOut.close(); ap.init(bOut.toByteArray()); } catch (IOException e) { throw new NoSuchAlgorithmException("unable to parse parameters"); } return ap; }
/** * generate an X509 CRL, based on the current issuer and subject, using the passed in provider for * the signing. */ public X509CRL generateX509CRL(PrivateKey key, String provider, SecureRandom random) throws NoSuchProviderException, SecurityException, SignatureException, InvalidKeyException { Signature sig = null; try { sig = Signature.getInstance(sigOID.getId(), provider); } catch (NoSuchAlgorithmException ex) { try { sig = Signature.getInstance(signatureAlgorithm, provider); } catch (NoSuchAlgorithmException e) { throw new SecurityException("exception creating signature: " + e.toString()); } } if (random != null) { sig.initSign(key, random); } else { sig.initSign(key); } if (extensions != null) { tbsGen.setExtensions(new X509Extensions(extOrdering, extensions)); } TBSCertList tbsCrl = tbsGen.generateTBSCertList(); try { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); DEROutputStream dOut = new DEROutputStream(bOut); dOut.writeObject(tbsCrl); sig.update(bOut.toByteArray()); } catch (Exception e) { throw new SecurityException("exception encoding TBS cert - " + e); } // Construct the CRL ASN1EncodableVector v = new ASN1EncodableVector(); v.add(tbsCrl); v.add(sigAlgId); v.add(new DERBitString(sig.sign())); return new X509CRLObject(new CertificateList(new DERSequence(v))); }
/** add a given extension field for the standard extensions tag (tag 0) */ public void addExtension(DERObjectIdentifier OID, boolean critical, DEREncodable value) { if (extensions == null) { extensions = new Hashtable(); extOrdering = new Vector(); } ByteArrayOutputStream bOut = new ByteArrayOutputStream(); DEROutputStream dOut = new DEROutputStream(bOut); try { dOut.writeObject(value); } catch (IOException e) { throw new IllegalArgumentException("error encoding value: " + e); } this.addExtension(OID, critical, bOut.toByteArray()); }
public byte[] getExtensionValue(String oid) { X509Extensions extensions = cert.getAcinfo().getExtensions(); if (extensions != null) { X509Extension ext = extensions.getExtension(new DERObjectIdentifier(oid)); if (ext != null) { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); DEROutputStream dOut = new DEROutputStream(bOut); try { dOut.writeObject(ext.getValue()); return bOut.toByteArray(); } catch (Exception e) { throw new RuntimeException("error encoding " + e.toString()); } } } return null; }
/** * Check the format of an OID.<br> * Throw an IOException if the first component is not 0, 1 or 2 or the second component is greater * than 39.<br> * <br> * User {@link org.bouncycastle.asn1.OIDTokenizer OIDTokenizer} * * @param the OID to be checked. * @exception IOException if the first component is not 0, 1 or 2 or the second component is * greater than 39. */ static byte[] parseOID(String oid) throws IOException { OIDTokenizer tokenizer = new OIDTokenizer(oid); String token; if (!tokenizer.hasMoreTokens()) { throw new IOException("OID contains no tokens"); } token = tokenizer.nextToken(); if (token == null) { throw new IOException("OID contains no tokens"); } try { int test = (Integer.valueOf(token)).intValue(); if (test < 0 || test > 2) { throw new IOException("first token is not >= 0 and <=2"); } if (!tokenizer.hasMoreTokens()) { throw new IOException("OID contains only one token"); } token = tokenizer.nextToken(); if (token == null) { throw new IOException("OID contains only one token"); } test = (Integer.valueOf(token)).intValue(); if (test < 0 || test > 39) { throw new IOException("secon token is not >= 0 and <=39"); } } catch (NumberFormatException ex) { throw new IOException("token: " + token + ": " + ex.toString()); } ASN1Object derData = new ASN1ObjectIdentifier(oid); ByteArrayOutputStream outStream = new ByteArrayOutputStream(); DEROutputStream derOutStream = new DEROutputStream(outStream); derOutStream.writeObject(derData); derOutStream.close(); return outStream.toByteArray(); }
/** * Validate the signature on the attribute certificate in this holder. * * @param verifierProvider a ContentVerifierProvider that can generate a verifier for the * signature. * @return true if the signature is valid, false otherwise. * @throws CertException if the signature cannot be processed or is inappropriate. */ public boolean isSignatureValid(ContentVerifierProvider verifierProvider) throws CertException { AttributeCertificateInfo acinfo = attrCert.getAcinfo(); if (!CertUtils.isAlgIdEqual(acinfo.getSignature(), attrCert.getSignatureAlgorithm())) { throw new CertException("signature invalid - algorithm identifier mismatch"); } ContentVerifier verifier; try { verifier = verifierProvider.get((acinfo.getSignature())); OutputStream sOut = verifier.getOutputStream(); DEROutputStream dOut = new DEROutputStream(sOut); dOut.writeObject(acinfo); sOut.close(); } catch (Exception e) { throw new CertException("unable to process signature: " + e.getMessage(), e); } return verifier.verify(attrCert.getSignatureValue().getBytes()); }
/** * Prepare the document for encryption. * * @param doc The document that will be encrypted. * @throws CryptographyException If there is an error while encrypting. */ public void prepareDocumentForEncryption(PDDocument doc) throws CryptographyException { try { Security.addProvider(new BouncyCastleProvider()); PDEncryptionDictionary dictionary = doc.getEncryptionDictionary(); if (dictionary == null) { dictionary = new PDEncryptionDictionary(); } dictionary.setFilter(FILTER); dictionary.setLength(this.keyLength); dictionary.setVersion(2); dictionary.setSubFilter(SUBFILTER); byte[][] recipientsField = new byte[policy.getRecipientsNumber()][]; // create the 20 bytes seed byte[] seed = new byte[20]; KeyGenerator key = KeyGenerator.getInstance("AES"); key.init(192, new SecureRandom()); SecretKey sk = key.generateKey(); System.arraycopy(sk.getEncoded(), 0, seed, 0, 20); // create the 20 bytes seed Iterator it = policy.getRecipientsIterator(); int i = 0; while (it.hasNext()) { PublicKeyRecipient recipient = (PublicKeyRecipient) it.next(); X509Certificate certificate = recipient.getX509(); int permission = recipient.getPermission().getPermissionBytesForPublicKey(); byte[] pkcs7input = new byte[24]; byte one = (byte) (permission); byte two = (byte) (permission >>> 8); byte three = (byte) (permission >>> 16); byte four = (byte) (permission >>> 24); System.arraycopy(seed, 0, pkcs7input, 0, 20); // put this seed in the pkcs7 input pkcs7input[20] = four; pkcs7input[21] = three; pkcs7input[22] = two; pkcs7input[23] = one; DERObject obj = createDERForRecipient(pkcs7input, certificate); ByteArrayOutputStream baos = new ByteArrayOutputStream(); DEROutputStream k = new DEROutputStream(baos); k.writeObject(obj); recipientsField[i] = baos.toByteArray(); i++; } dictionary.setRecipients(recipientsField); int sha1InputLength = seed.length; for (int j = 0; j < dictionary.getRecipientsLength(); j++) { COSString string = dictionary.getRecipientStringAt(j); sha1InputLength += string.getBytes().length; } byte[] sha1Input = new byte[sha1InputLength]; System.arraycopy(seed, 0, sha1Input, 0, 20); int sha1InputOffset = 20; for (int j = 0; j < dictionary.getRecipientsLength(); j++) { COSString string = dictionary.getRecipientStringAt(j); System.arraycopy( string.getBytes(), 0, sha1Input, sha1InputOffset, string.getBytes().length); sha1InputOffset += string.getBytes().length; } MessageDigest md = MessageDigest.getInstance("SHA-1"); byte[] mdResult = md.digest(sha1Input); this.encryptionKey = new byte[this.keyLength / 8]; System.arraycopy(mdResult, 0, this.encryptionKey, 0, this.keyLength / 8); doc.setEncryptionDictionary(dictionary); doc.getDocument().setEncryptionDictionary(dictionary.encryptionDictionary); } catch (NoSuchAlgorithmException ex) { throw new CryptographyException(ex); } catch (NoSuchProviderException ex) { throw new CryptographyException(ex); } catch (Exception e) { e.printStackTrace(); throw new CryptographyException(e); } }