org.bouncycastle.asn1.DERBitString Java Examples

The following examples show how to use org.bouncycastle.asn1.DERBitString. 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: Asn1Dump.java    From keystore-explorer with GNU General Public License v3.0 6 votes vote down vote up
private String dumpBitString(DERBitString asn1BitString) throws IOException {
	StringBuilder sb = new StringBuilder();
	byte[] bytes = asn1BitString.getBytes();

	sb.append(indentSequence.toString(indentLevel));
	sb.append("BIT STRING");
	try {
		String dump = dump(bytes);
		sb.append(", encapsulates:");
		sb.append(NEWLINE);
		sb.append(dump);
	} catch (Exception e) {
		sb.append("=");

		// print short bit strings as string of bits and long ones as hex dump
		if (bytes.length < 8) {
			sb.append(new BigInteger(1, bytes).toString(2));
		} else {
			sb.append(NEWLINE);
			sb.append(dumpHexClear(bytes));
		}
	}
	sb.append(NEWLINE);

	return sb.toString();
}
 
Example #2
Source File: SECPrivateKey.java    From InflatableDonkey with MIT License 6 votes vote down vote up
@Override
public ASN1Primitive toASN1Primitive() {
    DERTaggedObject parametersEncodable = parameters()
            .map(DEROctetString::new)
            .map(e -> new DERTaggedObject(PARAMETERS, e))
            .orElseGet(null);

    DERTaggedObject publicKeyEncodable = publicKey()
            .map(DERBitString::new)
            .map(e -> new DERTaggedObject(PUBLIC_KEY, e))
            .orElseGet(null);

    ASN1EncodableVector vector = DER.vector(
            new ASN1Integer(version),
            new DEROctetString(privateKey),
            parametersEncodable,
            publicKeyEncodable);

    return new DERSequence(vector);
}
 
Example #3
Source File: SECPrivateKey.java    From InflatableDonkey with MIT License 6 votes vote down vote up
public SECPrivateKey(ASN1Primitive primitive) {
    DERIterator i = DER.asSequence(primitive);
    Map<Integer, ASN1Primitive> tagged = i.derTaggedObjects();

    version = DER.as(ASN1Integer.class, i)
            .getValue()
            .intValue();

    privateKey = DER.as(DEROctetString.class, i)
            .getOctets();

    parameters = Optional.ofNullable(tagged.get(PARAMETERS))
            .map(DER.as(DEROctetString.class))
            .map(ASN1OctetString::getOctets);

    publicKey = Optional.ofNullable(tagged.get(PUBLIC_KEY))
            .map(DER.as(DERBitString.class))
            .map(DERBitString::getBytes);
}
 
Example #4
Source File: X509Ext.java    From portecle with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Get Netscape Certificate Type (2.16.840.1.113730.1.1) extension value as a string.
 *
 * @param bValue The octet string value
 * @return Extension value as a string
 * @throws IOException If an I/O problem occurs
 */
private String getNetscapeCertificateTypeStringValue(byte[] bValue)
    throws IOException
{
	int val = new NetscapeCertType((DERBitString) ASN1Primitive.fromByteArray(bValue)).intValue();
	StringBuilder strBuff = new StringBuilder();
	for (int type : NETSCAPE_CERT_TYPES)
	{
		if ((val & type) == type)
		{
			if (strBuff.length() != 0)
			{
				strBuff.append("<br><br>");
			}
			strBuff.append(RB.getString("NetscapeCertificateType." + type));
		}
	}
	return strBuff.toString();
}
 
Example #5
Source File: KeyIdentifierGenerator.java    From keystore-explorer with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Generate 64 bit hash key identifier.
 *
 * @return Key identifier
 * @throws CryptoException
 *             If generation fails
 */
public byte[] generate64BitHashId() throws CryptoException {
	/*
	 * RFC 3280: The keyIdentifier is composed of a four bit type field with
	 * the value 0100 followed by the least significant 60 bits of the SHA-1
	 * hash of the value of the BIT STRING subjectPublicKey (excluding the
	 * tag, length, and number of unused bit string bits)
	 */

	try {
		DERBitString publicKeyBitString = encodePublicKeyAsBitString(publicKey);
		byte[] hash = DigestUtil.getMessageDigest(publicKeyBitString.getBytes(), DigestType.SHA1);
		byte[] subHash = Arrays.copyOfRange(hash, 12, 20);
		subHash[0] &= 0x0F;
		subHash[0] |= 0x40;

		return subHash;
	} catch (IOException ex) {
		throw new CryptoException(res.getString("NoGenerateKeyIdentifier.exception.message"), ex);
	}
}
 
Example #6
Source File: Spkac.java    From keystore-explorer with GNU General Public License v3.0 6 votes vote down vote up
private PublicKey decodePublicKeyFromBitString(ASN1ObjectIdentifier publicKeyAlgorithmOid,
		ASN1Primitive algorithmParameters, DERBitString publicKey) throws SpkacException {
	if (publicKeyAlgorithmOid.getId().equals(RSA.oid())) {
		return decodeRsaPublicKeyFromBitString(publicKey); // Algorithm parameters are ASN1Null and unnecessary
	} else if (publicKeyAlgorithmOid.getId().equals(DSA.oid())) {
		ASN1Sequence dssParams = (ASN1Sequence) algorithmParameters;

		BigInteger p = ((ASN1Integer) dssParams.getObjectAt(0)).getValue();
		BigInteger q = ((ASN1Integer) dssParams.getObjectAt(1)).getValue();
		BigInteger g = ((ASN1Integer) dssParams.getObjectAt(2)).getValue();

		return decodeDsaPublicKeyFromBitString(publicKey, p, q, g);
	} else {
		throw new SpkacException(MessageFormat.format(
				res.getString("NoSupportPublicKeyAlgorithm.exception.message"), publicKeyAlgorithmOid.getId()));

	}
}
 
Example #7
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 #8
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 #9
Source File: Spkac.java    From keystore-explorer with GNU General Public License v3.0 5 votes vote down vote up
private DERBitString encodePublicKeyAsBitString(PublicKey publicKey) throws SpkacException {
	byte[] encodedPublicKey;

	if (publicKey instanceof RSAPublicKey) {
		encodedPublicKey = encodeRsaPublicKeyAsBitString((RSAPublicKey) publicKey);
	} else {
		encodedPublicKey = encodeDsaPublicKeyAsBitString((DSAPublicKey) publicKey);
	}

	return new DERBitString(encodedPublicKey);
}
 
Example #10
Source File: Spkac.java    From keystore-explorer with GNU General Public License v3.0 5 votes vote down vote up
private byte[] createPublicKeyAndChallengeForSigning() throws SpkacException {
	try {
		return new DERBitString(createPublicKeyAndChallenge().getEncoded(ASN1Encoding.DER)).getBytes();
	} catch (Exception ex) {
		throw new SpkacException(res.getString("NoGetPublicKeyAndChallengeForSignature.exception.message"), ex);
	}
}
 
Example #11
Source File: Spkac.java    From keystore-explorer with GNU General Public License v3.0 5 votes vote down vote up
private void decodeSpkac(byte[] der) throws SpkacException {
	try {
		ASN1Sequence signedPublicKeyAndChallenge = ASN1Sequence.getInstance(der);

		ASN1Sequence publicKeyAndChallenge = (ASN1Sequence) signedPublicKeyAndChallenge.getObjectAt(0);
		ASN1Sequence signatureAlgorithm = (ASN1Sequence) signedPublicKeyAndChallenge.getObjectAt(1);
		DERBitString signature = (DERBitString) signedPublicKeyAndChallenge.getObjectAt(2);

		ASN1ObjectIdentifier signatureAlgorithmOid = (ASN1ObjectIdentifier) signatureAlgorithm.getObjectAt(0);

		ASN1Sequence spki = (ASN1Sequence) publicKeyAndChallenge.getObjectAt(0);
		DERIA5String challenge = (DERIA5String) publicKeyAndChallenge.getObjectAt(1);

		ASN1Sequence publicKeyAlgorithm = (ASN1Sequence) spki.getObjectAt(0);
		DERBitString publicKey = (DERBitString) spki.getObjectAt(1);

		ASN1ObjectIdentifier publicKeyAlgorithmOid = (ASN1ObjectIdentifier) publicKeyAlgorithm.getObjectAt(0);
		ASN1Primitive algorithmParameters = publicKeyAlgorithm.getObjectAt(1).toASN1Primitive();

		this.challenge = challenge.getString();
		this.publicKey = decodePublicKeyFromBitString(publicKeyAlgorithmOid, algorithmParameters, publicKey);
		this.signatureAlgorithm = getSignatureAlgorithm(signatureAlgorithmOid);
		this.signature = signature.getBytes();
	} catch (Exception ex) {
		throw new SpkacException(res.getString("NoDecodeSpkac.exception.message"), ex);
	}
}
 
Example #12
Source File: KeyIdentifierGenerator.java    From keystore-explorer with GNU General Public License v3.0 5 votes vote down vote up
private DERBitString encodePublicKeyAsBitString(PublicKey publicKey) throws IOException {
	byte[] encodedPublicKey;

	if (publicKey instanceof RSAPublicKey) {
		encodedPublicKey = encodeRsaPublicKeyAsBitString((RSAPublicKey) publicKey);
	} else if (publicKey instanceof ECPublicKey){
		encodedPublicKey = encodeEcPublicKeyAsBitString((ECPublicKey) publicKey);
	} else {
		encodedPublicKey = encodeDsaPublicKeyAsBitString((DSAPublicKey) publicKey);
	}

	return new DERBitString(encodedPublicKey);
}
 
Example #13
Source File: KeyIdentifierGenerator.java    From keystore-explorer with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Generate 160 bit hash key identifier.
 *
 * @return Key identifier
 * @throws CryptoException
 *             If generation fails
 */
public byte[] generate160BitHashId() throws CryptoException {
	/*
	 * RFC 3280: The keyIdentifier is composed of the 160-bit SHA-1 hash of
	 * the value of the BIT STRING subjectPublicKey (excluding the tag,
	 * length, and number of unused bits)
	 */

	try {
		DERBitString publicKeyBitString = encodePublicKeyAsBitString(publicKey);
		return DigestUtil.getMessageDigest(publicKeyBitString.getBytes(), DigestType.SHA1);
	} catch (IOException ex) {
		throw new CryptoException(res.getString("NoGenerateKeyIdentifier.exception.message"), ex);
	}
}
 
Example #14
Source File: X509Ext.java    From keystore-explorer with GNU General Public License v3.0 5 votes vote down vote up
private String getBitString(byte[] octets) throws IOException {

		if (octets == null) {
			return "";
		}

		DERBitString derBitString = DERBitString.getInstance(ASN1Primitive.fromByteArray(octets));
		byte[] bitStringBytes = derBitString.getBytes();

		return new BigInteger(1, bitStringBytes).toString(2);
	}
 
Example #15
Source File: DSSASN1Utils.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Computes SHA-1 hash of the given {@code publicKey}'s
 * @param publicKey {@link PublicKey} to compute digest for
 * @return byte array of public key's SHA-1 hash
 */
public static byte[] computeSkiFromCertPublicKey(final PublicKey publicKey) {
	try {
		DLSequence seq = (DLSequence) ASN1Primitive.fromByteArray(publicKey.getEncoded());
		DERBitString item = (DERBitString) seq.getObjectAt(1);
		return DSSUtils.digest(DigestAlgorithm.SHA1, item.getOctets());
	} catch (IOException e) {
		throw new DSSException(e);
	}
}
 
Example #16
Source File: Asn1Dump.java    From keystore-explorer with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Get dump of the supplied ASN.1 object.
 *
 * @param asn1Object
 *            ASN.1 object
 * @return Dump of object
 * @throws Asn1Exception
 *             A problem was encountered getting the ASN.1 dump
 * @throws IOException
 *             If an I/O problem occurred
 */
public String dump(ASN1Primitive asn1Object) throws Asn1Exception, IOException {
	// Get dump of the supplied ASN.1 object incrementing the indent level of the output
	try {
		indentLevel++;

		if (asn1Object instanceof DERBitString) { // special case of ASN1String
			return dumpBitString((DERBitString) asn1Object);
		} else if (asn1Object instanceof ASN1String) {
			return dumpString((ASN1String) asn1Object);
		} else if (asn1Object instanceof ASN1UTCTime) {
			return dumpUTCTime((ASN1UTCTime) asn1Object);
		} else if (asn1Object instanceof ASN1GeneralizedTime) {
			return dumpGeneralizedTime((ASN1GeneralizedTime) asn1Object);
		} else if (asn1Object instanceof ASN1Sequence ||
				asn1Object instanceof ASN1Set ) {
			return dumpSetOrSequence(asn1Object);
		} else if (asn1Object instanceof ASN1TaggedObject) {
			return dumpTaggedObject((ASN1TaggedObject) asn1Object);
		} else if (asn1Object instanceof ASN1Boolean) {
			return dumpBoolean((ASN1Boolean) asn1Object);
		} else if (asn1Object instanceof ASN1Enumerated) {
			return dumpEnumerated((ASN1Enumerated) asn1Object);
		} else if (asn1Object instanceof ASN1Integer) {
			return dumpInteger((ASN1Integer) asn1Object);
		} else if (asn1Object instanceof ASN1Null) {
			return dumpNull();
		} else if (asn1Object instanceof ASN1ObjectIdentifier) {
			return dumpObjectIdentifier((ASN1ObjectIdentifier) asn1Object);
		} else if (asn1Object instanceof ASN1OctetString) {
			return dumpOctetString((ASN1OctetString) asn1Object);
		} else {
			throw new Asn1Exception("Unknown ASN.1 object: " + asn1Object.toString());
		}
	} finally {
		indentLevel--;
	}
}
 
Example #17
Source File: BaseSyncopeWASAML2ClientTest.java    From syncope with Apache License 2.0 5 votes vote down vote up
protected static Certificate createSelfSignedCert(final KeyPair keyPair) throws Exception {
    final X500Name dn = new X500Name("cn=Unknown");
    final V3TBSCertificateGenerator certGen = new V3TBSCertificateGenerator();

    certGen.setSerialNumber(new ASN1Integer(BigInteger.valueOf(1)));
    certGen.setIssuer(dn);
    certGen.setSubject(dn);
    certGen.setStartDate(new Time(new Date(System.currentTimeMillis() - 1000L)));

    final Date expiration = new Date(System.currentTimeMillis() + 100000);
    certGen.setEndDate(new Time(expiration));

    final AlgorithmIdentifier sigAlgID = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption, DERNull.INSTANCE);
    certGen.setSignature(sigAlgID);
    certGen.setSubjectPublicKeyInfo(SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()));

    final Signature sig = Signature.getInstance("SHA1WithRSA");
    sig.initSign(keyPair.getPrivate());
    sig.update(certGen.generateTBSCertificate().getEncoded(ASN1Encoding.DER));

    final TBSCertificate tbsCert = certGen.generateTBSCertificate();
    final ASN1EncodableVector v = new ASN1EncodableVector();

    v.add(tbsCert);
    v.add(sigAlgID);
    v.add(new DERBitString(sig.sign()));

    final Certificate cert = CertificateFactory.getInstance("X.509")
        .generateCertificate(new ByteArrayInputStream(new DERSequence(v).getEncoded(ASN1Encoding.DER)));
    cert.verify(keyPair.getPublic());
    return cert;
}
 
Example #18
Source File: X509Ext.java    From keystore-explorer with GNU General Public License v3.0 5 votes vote down vote up
private String getEntrustVersionInformationStringValue(byte[] value) throws IOException {
	// @formatter:off

	/*
	 * EntrustVersInfoSyntax ::= OCTET STRING
	 *
	 * entrustVersInfo EXTENSION ::= { SYNTAX EntrustVersInfoSyntax,
	 * IDENTIFIED BY {id-entrust 0} }
	 *
	 * EntrustVersInfoSyntax ::= ASN1Sequence { entrustVers GeneralString,
	 * entrustInfoFlags EntrustInfoFlags }
	 *
	 * EntrustInfoFlags ::= BIT STRING { keyUpdateAllowed newExtensions (1),
	 * pKIXCertificate (2) }
	 */

	// @formatter:on

	StringBuilder sb = new StringBuilder();

	ASN1Sequence entrustVersInfo = (ASN1Sequence) ASN1Primitive.fromByteArray(value);

	DERGeneralString entrustVers = (DERGeneralString) entrustVersInfo.getObjectAt(0);
	DERBitString entrustInfoFlags = (DERBitString) entrustVersInfo.getObjectAt(1);

	sb.append(MessageFormat.format(res.getString("EntrustVersion"), entrustVers.getString()));
	sb.append(NEWLINE);
	sb.append(MessageFormat.format(res.getString("EntrustInformationFlags"), entrustInfoFlags.getString()));
	sb.append(NEWLINE);

	return sb.toString();
}
 
Example #19
Source File: NegTokenInit.java    From jcifs-ng with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public byte[] toByteArray () {
    try {
        ASN1EncodableVector fields = new ASN1EncodableVector();
        ASN1ObjectIdentifier[] mechs = getMechanisms();
        if ( mechs != null ) {
            ASN1EncodableVector vector = new ASN1EncodableVector();
            for ( int i = 0; i < mechs.length; i++ ) {
                vector.add(mechs[ i ]);
            }
            fields.add(new DERTaggedObject(true, 0, new DERSequence(vector)));
        }
        int ctxFlags = getContextFlags();
        if ( ctxFlags != 0 ) {
            fields.add(new DERTaggedObject(true, 1, new DERBitString(ctxFlags)));
        }
        byte[] mechanismToken = getMechanismToken();
        if ( mechanismToken != null ) {
            fields.add(new DERTaggedObject(true, 2, new DEROctetString(mechanismToken)));
        }
        byte[] mechanismListMIC = getMechanismListMIC();
        if ( mechanismListMIC != null ) {
            fields.add(new DERTaggedObject(true, 3, new DEROctetString(mechanismListMIC)));
        }

        ASN1EncodableVector ev = new ASN1EncodableVector();
        ev.add(SPNEGO_OID);
        ev.add(new DERTaggedObject(true, 0, new DERSequence(fields)));
        ByteArrayOutputStream collector = new ByteArrayOutputStream();
        DEROutputStream der = new DEROutputStream(collector);
        DERApplicationSpecific derApplicationSpecific = new DERApplicationSpecific(0, ev);
        der.writeObject(derApplicationSpecific);
        return collector.toByteArray();
    }
    catch ( IOException ex ) {
        throw new IllegalStateException(ex.getMessage());
    }
}
 
Example #20
Source File: SAML2SPKeystoreTest.java    From syncope with Apache License 2.0 5 votes vote down vote up
private static Certificate createSelfSignedCert(final KeyPair keyPair) throws Exception {
    final X500Name dn = new X500Name("cn=Unknown");
    final V3TBSCertificateGenerator certGen = new V3TBSCertificateGenerator();

    certGen.setSerialNumber(new ASN1Integer(BigInteger.valueOf(1)));
    certGen.setIssuer(dn);
    certGen.setSubject(dn);
    certGen.setStartDate(new Time(new Date(System.currentTimeMillis() - 1000L)));

    final Date expiration = new Date(System.currentTimeMillis() + 100000);
    certGen.setEndDate(new Time(expiration));

    final AlgorithmIdentifier sigAlgID = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption, DERNull.INSTANCE);
    certGen.setSignature(sigAlgID);
    certGen.setSubjectPublicKeyInfo(SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()));

    final Signature sig = Signature.getInstance("SHA1WithRSA");
    sig.initSign(keyPair.getPrivate());
    sig.update(certGen.generateTBSCertificate().getEncoded(ASN1Encoding.DER));

    final TBSCertificate tbsCert = certGen.generateTBSCertificate();
    final ASN1EncodableVector v = new ASN1EncodableVector();

    v.add(tbsCert);
    v.add(sigAlgID);
    v.add(new DERBitString(sig.sign()));

    final Certificate cert = CertificateFactory.getInstance("X.509")
        .generateCertificate(new ByteArrayInputStream(new DERSequence(v).getEncoded(ASN1Encoding.DER)));
    cert.verify(keyPair.getPublic());
    return cert;
}
 
Example #21
Source File: NegTokenInit.java    From jcifs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public byte[] toByteArray () {
    try {
        ASN1EncodableVector fields = new ASN1EncodableVector();
        ASN1ObjectIdentifier[] mechs = getMechanisms();
        if ( mechs != null ) {
            ASN1EncodableVector vector = new ASN1EncodableVector();
            for ( int i = 0; i < mechs.length; i++ ) {
                vector.add(mechs[ i ]);
            }
            fields.add(new DERTaggedObject(true, 0, new DERSequence(vector)));
        }
        int ctxFlags = getContextFlags();
        if ( ctxFlags != 0 ) {
            fields.add(new DERTaggedObject(true, 1, new DERBitString(ctxFlags)));
        }
        byte[] mechanismToken = getMechanismToken();
        if ( mechanismToken != null ) {
            fields.add(new DERTaggedObject(true, 2, new DEROctetString(mechanismToken)));
        }
        byte[] mechanismListMIC = getMechanismListMIC();
        if ( mechanismListMIC != null ) {
            fields.add(new DERTaggedObject(true, 3, new DEROctetString(mechanismListMIC)));
        }

        ASN1EncodableVector ev = new ASN1EncodableVector();
        ev.add(SPNEGO_OID);
        ev.add(new DERTaggedObject(true, 0, new DERSequence(fields)));
        ByteArrayOutputStream collector = new ByteArrayOutputStream();
        DEROutputStream der = new DEROutputStream(collector);
        DERApplicationSpecific derApplicationSpecific = new DERApplicationSpecific(0, ev);
        der.writeObject(derApplicationSpecific);
        return collector.toByteArray();
    }
    catch ( IOException ex ) {
        throw new IllegalStateException(ex.getMessage());
    }
}
 
Example #22
Source File: Identity.java    From ts3j with Apache License 2.0 5 votes vote down vote up
public byte[] toASN() throws IOException {
    return new DERSequence(
            new ASN1Encodable[] {
                    new DERBitString(0),
                    new ASN1Integer(32),
                    new ASN1Integer(getPublicKey().getXCoord().toBigInteger()),
                    new ASN1Integer(getPublicKey().getYCoord().toBigInteger())
            }
    ).getEncoded();
}
 
Example #23
Source File: SM2PrivateKey.java    From gmhelper with Apache License 2.0 5 votes vote down vote up
private DERBitString getSM2PublicKeyDetails(SM2PublicKey pub) {
    try {
        SubjectPublicKeyInfo info = SubjectPublicKeyInfo.getInstance(ASN1Primitive.fromByteArray(pub.getEncoded()));

        return info.getPublicKeyData();
    } catch (IOException e) {   // should never happen
        return null;
    }
}
 
Example #24
Source File: NewCertificateContract.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
private int getKeySize(SubjectPublicKeyInfo subjectPKInfo) {
   try {
      X509EncodedKeySpec xspec = new X509EncodedKeySpec((new DERBitString(subjectPKInfo.getEncoded())).getBytes());
      AlgorithmIdentifier keyAlg = subjectPKInfo.getAlgorithm();
      PublicKey publicKey = KeyFactory.getInstance(keyAlg.getAlgorithm().getId()).generatePublic(xspec);
      String algorithm = publicKey.getAlgorithm();
      KeyFactory keyFact = KeyFactory.getInstance(algorithm);
      RSAPublicKeySpec keySpec = (RSAPublicKeySpec)keyFact.getKeySpec(publicKey, RSAPublicKeySpec.class);
      BigInteger modulus = keySpec.getModulus();
      return modulus.toString(2).length();
   } catch (Exception var9) {
      throw new IllegalArgumentException(var9);
   }
}
 
Example #25
Source File: NewCertificateContract.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
private static int getKeySize(SubjectPublicKeyInfo subjectPKInfo) {
   try {
      X509EncodedKeySpec xspec = new X509EncodedKeySpec((new DERBitString(subjectPKInfo.getEncoded())).getBytes());
      AlgorithmIdentifier keyAlg = subjectPKInfo.getAlgorithm();
      PublicKey publicKey = KeyFactory.getInstance(keyAlg.getAlgorithm().getId()).generatePublic(xspec);
      String algorithm = publicKey.getAlgorithm();
      KeyFactory keyFact = KeyFactory.getInstance(algorithm);
      RSAPublicKeySpec keySpec = (RSAPublicKeySpec)keyFact.getKeySpec(publicKey, RSAPublicKeySpec.class);
      BigInteger modulus = keySpec.getModulus();
      return modulus.toString(2).length();
   } catch (Exception var8) {
      throw new IllegalArgumentException(var8);
   }
}
 
Example #26
Source File: NewCertificateContract.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
private static int getKeySize(SubjectPublicKeyInfo subjectPKInfo) {
   try {
      X509EncodedKeySpec xspec = new X509EncodedKeySpec((new DERBitString(subjectPKInfo.getEncoded())).getBytes());
      AlgorithmIdentifier keyAlg = subjectPKInfo.getAlgorithm();
      PublicKey publicKey = KeyFactory.getInstance(keyAlg.getAlgorithm().getId()).generatePublic(xspec);
      String algorithm = publicKey.getAlgorithm();
      KeyFactory keyFact = KeyFactory.getInstance(algorithm);
      RSAPublicKeySpec keySpec = (RSAPublicKeySpec)keyFact.getKeySpec(publicKey, RSAPublicKeySpec.class);
      BigInteger modulus = keySpec.getModulus();
      return modulus.toString(2).length();
   } catch (Exception var8) {
      throw new IllegalArgumentException(var8);
   }
}
 
Example #27
Source File: NewCertificateContract.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
private int getKeySize(SubjectPublicKeyInfo subjectPKInfo) {
   try {
      X509EncodedKeySpec xspec = new X509EncodedKeySpec((new DERBitString(subjectPKInfo.getEncoded())).getBytes());
      AlgorithmIdentifier keyAlg = subjectPKInfo.getAlgorithm();
      PublicKey publicKey = KeyFactory.getInstance(keyAlg.getAlgorithm().getId()).generatePublic(xspec);
      String algorithm = publicKey.getAlgorithm();
      KeyFactory keyFact = KeyFactory.getInstance(algorithm);
      RSAPublicKeySpec keySpec = (RSAPublicKeySpec)keyFact.getKeySpec(publicKey, RSAPublicKeySpec.class);
      BigInteger modulus = keySpec.getModulus();
      return modulus.toString(2).length();
   } catch (Exception var9) {
      throw new IllegalArgumentException(var9);
   }
}
 
Example #28
Source File: NewCertificateContract.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
private int getKeySize(SubjectPublicKeyInfo subjectPKInfo) {
   try {
      X509EncodedKeySpec xspec = new X509EncodedKeySpec((new DERBitString(subjectPKInfo.getEncoded())).getBytes());
      AlgorithmIdentifier keyAlg = subjectPKInfo.getAlgorithm();
      PublicKey publicKey = KeyFactory.getInstance(keyAlg.getAlgorithm().getId()).generatePublic(xspec);
      String algorithm = publicKey.getAlgorithm();
      KeyFactory keyFact = KeyFactory.getInstance(algorithm);
      RSAPublicKeySpec keySpec = (RSAPublicKeySpec)keyFact.getKeySpec(publicKey, RSAPublicKeySpec.class);
      BigInteger modulus = keySpec.getModulus();
      return modulus.toString(2).length();
   } catch (Exception var9) {
      throw new IllegalArgumentException(var9);
   }
}
 
Example #29
Source File: CertUtil.java    From javasdk with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * read pem and convert to address.
 * @param s pem file context
 * @return address
 * @throws Exception -
 */
public static String pemToAddr(String s) throws Exception {
    PemReader pemReader = new PemReader(new StringReader(s));
    PemObject pemObject = pemReader.readPemObject();
    X509CertificateHolder cert = new X509CertificateHolder(pemObject.getContent());
    SubjectPublicKeyInfo pkInfo = cert.getSubjectPublicKeyInfo();
    DERBitString pk = pkInfo.getPublicKeyData();
    byte[] pk64 = ByteUtils.subArray(pk.getBytes(),1);
    return ByteUtils.toHexString(HashUtil.sha3omit12(pk64));
}
 
Example #30
Source File: X509Ext.java    From keystore-explorer with GNU General Public License v3.0 4 votes vote down vote up
private String[] getReasonFlagsStrings(ReasonFlags reasonFlags) throws IOException {
	// @formatter:off

	/*
	 * ReasonFlags ::= BIT STRING { unused(0), keyCompromise(1),
	 * cACompromise(2), affiliationChanged(3), superseded(4),
	 * cessationOfOperation(5), certificateHold(6), privilegeWithdrawn(7),
	 * aACompromise(8)}
	 */

	// @formatter:on

	List<String> reasonFlagsList = new ArrayList<>();

	DERBitString reasonFlagsBitString = (DERBitString) reasonFlags.toASN1Primitive();

	int reasonFlagsInt = reasonFlagsBitString.intValue();

	// Go through bit string adding reason flags found to be true
	if (hasReasonFlag(reasonFlagsInt, ReasonFlags.unused)) {
		reasonFlagsList.add(res.getString("UnusedReasonFlag"));
	}
	if (hasReasonFlag(reasonFlagsInt, ReasonFlags.keyCompromise)) {
		reasonFlagsList.add(res.getString("KeyCompromiseReasonFlag"));
	}
	if (hasReasonFlag(reasonFlagsInt, ReasonFlags.cACompromise)) {
		reasonFlagsList.add(res.getString("CaCompromiseReasonFlag"));
	}
	if (hasReasonFlag(reasonFlagsInt, ReasonFlags.affiliationChanged)) {
		reasonFlagsList.add(res.getString("AffiliationChangedReasonFlag"));
	}
	if (hasReasonFlag(reasonFlagsInt, ReasonFlags.superseded)) {
		reasonFlagsList.add(res.getString("SupersededReasonFlag"));
	}
	if (hasReasonFlag(reasonFlagsInt, ReasonFlags.cessationOfOperation)) {
		reasonFlagsList.add(res.getString("CessationOfOperationReasonFlag"));
	}
	if (hasReasonFlag(reasonFlagsInt, ReasonFlags.certificateHold)) {
		reasonFlagsList.add(res.getString("CertificateHoldReasonFlag"));
	}
	if (hasReasonFlag(reasonFlagsInt, ReasonFlags.privilegeWithdrawn)) {
		reasonFlagsList.add(res.getString("PrivilegeWithdrawnReasonFlag"));
	}
	if (hasReasonFlag(reasonFlagsInt, ReasonFlags.aACompromise)) {
		reasonFlagsList.add(res.getString("AaCompromiseReasonFlag"));
	}

	return reasonFlagsList.toArray(new String[reasonFlagsList.size()]);
}