public ECPrivateKey( BigInteger key, DERBitString publicKey, ASN1Object parameters) { byte[] bytes = BigIntegers.asUnsignedByteArray(key); ASN1EncodableVector v = new ASN1EncodableVector(); v.add(new ASN1Integer(1)); v.add(new DEROctetString(bytes)); if (parameters != null) { v.add(new DERTaggedObject(true, 0, parameters)); } if (publicKey != null) { v.add(new DERTaggedObject(true, 1, publicKey)); } seq = new DERSequence(v); }
/** * ANS.1 parser * * @param dis * @throws IOException */ void parse(DerInputStream dis) throws IOException { ASN1Object[] dvs = (ASN1Object[]) dis.getSequence(2); for (int i = 0; i < dvs.length; i++) { switch (((DERTaggedObject) dvs[i]).getTagNo()) { case 0: // keytype[0] INTEGER keyType = ASN1Integer.getInstance(((DERTaggedObject) dvs[i]).getObject()).getValue().intValue(); break; case 1: // keyvalue[1] OCTET STRING keyValue = DEROctetString.getInstance(((DERTaggedObject) dvs[i]).getObject()).getOctets(); break; default: LOG.error("unknown tag:" + (((DERTaggedObject) dvs[i]).getTagNo() & (byte) 0x1F)); } } }
@Override public boolean equals(Object paramObject) { if (paramObject == null) { return false; } try { return Arrays.equals(((ASN1Object) paramObject).getEncoded(), getEncoded()); } catch (Exception e) { // ignore } return false; }
/** * Extract a {@link ASN1OctetString} that represents the value of a given extension * * @param cert is X509 certificate out of which an extension should be extracted * @param Oid is the Object IDentifier for the extension * @return a {@link ASN1OctetString} that represents an extension or {@code null} if no such * extension is found. * @throws CertificateParsingException if a parsing error occurs */ public static ASN1OctetString extractExtensionValue(X509Certificate cert, String Oid) throws CertificateParsingException { byte[] extensionValue = cert.getExtensionValue(Oid); if (extensionValue == null || extensionValue.length == 0) { // Did not find extension return null; } ASN1Object asn1Object = getAsn1Object(extensionValue); if (asn1Object == null || !(asn1Object instanceof ASN1OctetString)) { throw new CertificateParsingException("Expected ASN1OctetString."); } return (ASN1OctetString) asn1Object; }
private static ASN1Sequence getKeyDescriptionSequence(ASN1OctetString octet) throws CertificateParsingException { // Read out the Sequence ASN1Object asn1Object = X509ExtensionParsingUtil.getAsn1Object(octet.getOctets()); if (asn1Object == null || !(asn1Object instanceof ASN1Sequence)) { throw new CertificateParsingException("Expected KeyDescription Sequence."); } ASN1Sequence sequence = (ASN1Sequence) asn1Object; if (sequence.size() != DESCRIPTION_LENGTH) { throw new CertificateParsingException("KeyDescription Sequence has " + sequence.size() + " elements. Expected " + DESCRIPTION_LENGTH + " elements "); } return sequence; }
@Override public ASN1Object toASN1Object() throws SmartCardException { ASN1EncodableVector certList = new ASN1EncodableVector(); for (Certificate cert : certs) { ASN1EncodableVector essCertID1 = new ASN1EncodableVector(); essCertID1.add(getCertificateHash(cert)); essCertID1.add(getIssuerAndSerialForESSCertId(cert)); DERSequence essCertID = new DERSequence(essCertID1); certList.add(essCertID); } DERSequence certListSeq = new DERSequence(certList); DERSequence signSeq = new DERSequence(certListSeq); return signSeq; }
private ASN1Object getObjectInTag(int tagNo) { Enumeration e = seq.getObjects(); while (e.hasMoreElements()) { DEREncodable obj = (DEREncodable)e.nextElement(); if (obj instanceof ASN1TaggedObject) { ASN1TaggedObject tag = (ASN1TaggedObject)obj; if (tag.getTagNo() == tagNo) { return (ASN1Object)((DEREncodable)tag.getObject()).getDERObject(); } } } return null; }
/** {@inheritDoc} */ protected PublicKey decode(final byte[] encoded) throws CryptException { try { final ASN1Sequence seq = (ASN1Sequence) ASN1Object .fromByteArray(encoded); final ASN1Sequence innerSeq = (ASN1Sequence) seq.getObjectAt(0); final DEREncodable algId = innerSeq.getObjectAt(0); final String algorithm; if (RSA_ID.equals(algId)) { algorithm = "RSA"; } else if (EC_ID.equals(algId)) { algorithm = "EC"; } else if (DSA_ID.equals(algId)) { algorithm = "DSA"; } else { throw new CryptException("Unsupported public key algorithm ID " + algId); } return CryptProvider.getKeyFactory(algorithm).generatePublic( new X509EncodedKeySpec(encoded)); } catch (Exception e) { throw new CryptException("Invalid public key.", e); } }
/** * 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(); }
/** * Sets the subject criterion. The specified distinguished name must match * the subject distinguished name in the <code>X509Certificate</code>. If * null, any subject distinguished name will do.<br /> * <br /> * If <code>subjectDN</code> is not <code>null</code>, it should * contain a single DER encoded distinguished name, as defined in X.501. For * the ASN.1 notation for this structure, see * {@link #setIssuer(byte []) setIssuer(byte [] issuerDN)}.<br /> * <br /> * Uses {@link org.bouncycastle.asn1.ASN1InputStream ASN1InputStream}, * {@link org.bouncycastle.asn1.ASN1Object ASN1Object}, * {@link org.bouncycastle.asn1.ASN1Sequence ASN1Sequence}, * {@link org.bouncycastle.asn1.x509.X509Name X509Name} * * @param subjectDN * a byte array containing the distinguished name in ASN.1 DER * format (or <code>null</code>) * * @exception IOException * if an encoding error occurs (incorrect form for DN) */ public void setSubject(byte[] subjectDN) throws IOException { if (subjectDN == null) { this.subjectDN = null; this.subjectDNX509 = null; } else { ByteArrayInputStream inStream = new ByteArrayInputStream(subjectDN); ASN1InputStream derInStream = new ASN1InputStream(inStream); ASN1Object obj = derInStream.readObject(); if (obj instanceof ASN1Sequence) { this.subjectDNX509 = new X509Name((ASN1Sequence)obj); } else { throw new IOException("parsing error"); } this.subjectDN = (byte[])subjectDN.clone(); } }
/** * Return a printable representation of this * <code>PolicyQualifierInfo</code>.<br /> * <br /> * Uses {@link org.bouncycastle.asn1.ASN1InputStream ASN1InputStream}, * {@link org.bouncycastle.asn1.ASN1Object ASN1Object} * * @return a <code>String</code> describing the contents of this * <code>PolicyQualifierInfo</code> */ public String toString() { StringBuffer s = new StringBuffer(); s.append("PolicyQualifierInfo: [\n"); s.append("qualifierID: ").append(id).append('\n'); try { ByteArrayInputStream inStream = new ByteArrayInputStream(qualifier); ASN1InputStream derInStream = new ASN1InputStream(inStream); ASN1Object derObject = derInStream.readObject(); s .append(" qualifier:\n").append(ASN1Dump.dumpAsString(derObject)) .append('\n'); } catch (IOException ex) { s.append(ex.getMessage()); } s.append("qualifier: ").append(id).append('\n'); s.append(']'); return s.toString(); }
/** * Check given DER encoded nameConstraints for correct decoding. Currently * only basic DER decoding test.<br /> * <br /> * <b>TODO: implement more testing.</b> * * @param data * the DER encoded nameConstrains to be checked or * <code>null</code> * @exception IllegalArgumentException * if the check failed. */ private void checkNameConstraints(byte[] data) { if (data != null) { try { ByteArrayInputStream inStream = new ByteArrayInputStream(data); ASN1InputStream derInStream = new ASN1InputStream(inStream); ASN1Object derObject = derInStream.readObject(); if (!(derObject instanceof ASN1Sequence)) { throw new IllegalArgumentException( "nameConstraints parameter decoding error"); } } catch (IOException ex) { throw new IllegalArgumentException( "nameConstraints parameter decoding error: " + ex); } } }
/** * Returns an instance of <code>ProxyCertInfo</code> from given object. * * @param obj * the object to create the instance from. * @return <code>ProxyCertInfo</code> instance. * @exception IllegalArgumentException * if unable to convert the object to * <code>ProxyCertInfo</code> instance. */ public static ProxyCertInfo getInstance(Object obj) { if (obj instanceof ProxyCertInfo) return (ProxyCertInfo) obj; if (obj instanceof byte[]) { try { obj = ASN1Object.fromByteArray((byte[]) obj); } catch (IOException ignored) { } } if (obj instanceof ASN1Sequence) return new ProxyCertInfo((ASN1Sequence) obj); throw new IllegalArgumentException("unknown object in factory"); }
/** * Convert the value of the passed in extension to an object * @param ext the extension to parse * @return the object the value string contains * @exception IllegalArgumentException if conversion is not possible */ public static ASN1Object convertValueToObject( X509Extension ext) throws IllegalArgumentException { try { return ASN1Object.fromByteArray(ext.getValue().getOctets()); } catch (IOException e) { throw new IllegalArgumentException("can't convert extension: " + e); } }
public static <T extends ASN1Object> T readAs(ASN1InputStream stream, Class<T> type) throws DecodingException { ASN1Object derObject; try { derObject = stream.readObject(); } catch(IOException e) { throw new DecodingException("kerberos.token.invalid", null, e); } return check(derObject, type); }
public static <T extends ASN1Object> T check(Object object, Class<T> type) throws DecodingException { if(!type.isInstance(object)) { Object[] args = new Object[]{type, object.getClass()}; throw new DecodingException("kerberos.object.cast", args, null); } return type.cast(object); }
ASN1Object[] getSequence(int arg) throws IOException { ASN1Object obj = is.readObject(); ASN1Sequence seq = DERSequence.getInstance(obj); ASN1Object[] dvs = new ASN1Object[seq.size()]; Enumeration<ASN1Object> e = ((DERSequence)seq).getObjects(); for (int i=0; e.hasMoreElements(); i++) { Object o = e.nextElement(); dvs[i] = (ASN1Object)o; } return dvs; }
public static byte[] sign(Trans trans, ASN1Object toSign, PrivateKey pk) throws IOException, InvalidKeyException, SignatureException, NoSuchAlgorithmException { TimeTaken tt = trans.start("Encode Security Object", Env.SUB); try { return sign(trans,toSign.getEncoded(),pk); } finally { tt.done(); } }
/** * Parses a transport extension from an attestation certificate and returns * a List of HardwareFeatures supported by the security key. The specification of * the HardwareFeatures in the certificate should match their internal definition in * device_auth.proto * * <p>The expected transport extension value is a BIT STRING containing the enabled * transports: * * <p>FIDOU2FTransports ::= BIT STRING { * bluetoothRadio(0), -- Bluetooth Classic * bluetoothLowEnergyRadio(1), * uSB(2), * nFC(3) * } * * <p>Note that the BIT STRING must be wrapped in an OCTET STRING. * An extension that encodes BT, BLE, and NFC then looks as follows: * * <p>SEQUENCE (2 elem) * OBJECT IDENTIFIER 1.3.6.1.4.1.45724.2.1.1 * OCTET STRING (1 elem) * BIT STRING (4 bits) 1101 * * @param cert the certificate to parse for extension * @return the supported transports as a List of HardwareFeatures or null if no extension * was found * @throws CertificateParsingException */ public static U2fAttestation Parse(X509Certificate cert) throws CertificateParsingException { ASN1OctetString extValue = X509ExtensionParsingUtil.extractExtensionValue(cert, TRANSPORT_EXTENSION_OID); if (extValue == null) { // No Transport extension was found return new U2fAttestation(null); } // Read out the BitString ASN1Object asn1Object = X509ExtensionParsingUtil.getAsn1Object(extValue.getOctets()); if (asn1Object == null || !(asn1Object instanceof DERBitString)) { throw new CertificateParsingException("No BitString found in transports extension"); } DERBitString bitString = (DERBitString) asn1Object; byte[] values = bitString.getBytes(); BitSet bitSet = BitSet.valueOf(values); // We might have more defined transports than used by the extension List<Transports> transports = new ArrayList<Transports>(); for (int i = 0; i < BITS_IN_A_BYTE; i++) { if (bitSet.get(BITS_IN_A_BYTE - i - 1)) { transports.add(Transports.values()[i]); } } return new U2fAttestation(transports); }
/** * Convert a byte array to a PKCS7 SignedData object * @param bytes byte array * @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); ASN1ObjectIdentifier typeId = ci.getContentType(); if( ! typeId.equals(PKCSObjectIdentifiers.signedData)) { throw new IllegalArgumentException("not a pkcs7 signature"); } return SignedData.getInstance(ci.getContent()); }
public static byte[] toByteArray(Object x) throws Exception { if(x instanceof APublicKey) { return toByteArray(((APublicKey)x).getKey()); } if(x instanceof APrivateKey) { return toByteArray(((APrivateKey)x).getKey()); } else if(x instanceof ASN1Object) { return ((ASN1Object)x).getEncoded(); } else if(x instanceof RSAPublicKeySpec) { return toByteArray((RSAPublicKeySpec)x); } else if(x instanceof RSAKeyParameters) { return toByteArray((RSAKeyParameters)x); } else { throw new Exception("don't know how to convert " + CKit.simpleName(x) + " to byte[]"); } }
public static BigInteger getCrlNumber(X509CRL crl) throws IOException { byte[] crlNumEnc = crl.getExtensionValue(X509Extension.cRLNumber.getId()); BigInteger crlNum = null; // XAdES 7.4.2: "The 'number' element is an optional hint ..." if (crlNumEnc != null) { ASN1Object derCrlNum = X509ExtensionUtil.fromExtensionValue(crlNumEnc); crlNum = CRLNumber.getInstance(derCrlNum).getCRLNumber(); } return crlNum; }
@Override public ASN1Object toASN1Object() throws SmartCardException { ASN1EncodableVector bodyVec = new ASN1EncodableVector(); bodyVec.add(getCMSVersion()); bodyVec.add(getDigestAlgorithms()); bodyVec.add(getContentInfo(content)); bodyVec.add(new DERTaggedObject(false, 0, getCertificates())); bodyVec.add(getSignerInfosEncodable()); DERSequence bodySeq = new DERSequence(bodyVec); return bodySeq; }
@Override public ASN1Object toASN1Object() throws SmartCardException { ASN1EncodableVector whole = new ASN1EncodableVector(); whole.add(contentType); whole.add(new DERTaggedObject(true, 0, signedData.toASN1Object())); final DERSequence whol = new DERSequence(whole); return whol; }
private ECNamedCurveParameterSpec readECParameters(String endMarker) throws IOException { DERObjectIdentifier oid = (DERObjectIdentifier)ASN1Object.fromByteArray(readBytes(endMarker)); return ECNamedCurveTable.getParameterSpec(oid.getId()); }
/** * 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. */ 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); } }