Java Code Examples for org.bouncycastle.asn1.DERBitString

The following examples show how to use org.bouncycastle.asn1.DERBitString. These examples are extracted from open source projects. 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 Project: portecle   Source File: X509Ext.java    License: 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 2
/**
 * 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 3
Source Project: keystore-explorer   Source File: Spkac.java    License: 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 4
Source Project: keystore-explorer   Source File: DKeyUsage.java    License: 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 5
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 6
Source Project: keystore-explorer   Source File: Asn1Dump.java    License: 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 7
Source Project: InflatableDonkey   Source File: SECPrivateKey.java    License: 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 8
Source Project: InflatableDonkey   Source File: SECPrivateKey.java    License: 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 9
Source Project: javasdk   Source File: CertUtil.java    License: 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 10
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 11
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 12
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 13
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 14
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 15
Source Project: gmhelper   Source File: SM2PrivateKey.java    License: 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 16
Source Project: ts3j   Source File: Identity.java    License: 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 17
Source Project: jcifs   Source File: NegTokenInit.java    License: 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 18
Source Project: jcifs-ng   Source File: NegTokenInit.java    License: 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 19
Source Project: keystore-explorer   Source File: X509Ext.java    License: 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 20
Source Project: keystore-explorer   Source File: X509Ext.java    License: 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 21
/**
 * 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 22
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 23
Source Project: keystore-explorer   Source File: Spkac.java    License: 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 24
Source Project: keystore-explorer   Source File: Spkac.java    License: 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 25
Source Project: keystore-explorer   Source File: Spkac.java    License: 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 26
Source Project: keystore-explorer   Source File: Asn1Dump.java    License: 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 27
Source Project: dss   Source File: DSSASN1Utils.java    License: 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 28
Source Project: syncope   Source File: BaseSyncopeWASAML2ClientTest.java    License: 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 29
Source Project: syncope   Source File: SAML2SPKeystoreTest.java    License: 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 30
/**
 *
 * @param ApplicationParam
 * @param ChallengeParam
 * @param kh
 * @param PublicKey
 * @return
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 * @throws InvalidKeySpecException
 */
private String objectTBS(String ApplicationParam, String ChallengeParam, String kh, String PublicKey)
        throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException, DecoderException {

    byte constant = (byte) 0x00;
    byte[] Challenge = Base64.decodeBase64(ChallengeParam);
    int ChanllengeL = Challenge.length;
    byte[] Application = Base64.decodeBase64(ApplicationParam);
    int ApplicationL = Application.length;
    byte[] keyHandle = Base64.decodeBase64(kh);
    int keyHandleL = keyHandle.length;
    byte[] publicKey = Base64.decodeBase64(PublicKey);
    int publicKeyL = publicKey.length;

    //  Convert back to publicKey
    KeyFactory kf = KeyFactory.getInstance("ECDSA", "BCFIPS");
    X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(publicKey);
    PublicKey pub = kf.generatePublic(pubKeySpec);

    ASN1InputStream bIn = new ASN1InputStream(new ByteArrayInputStream(pub.getEncoded()));
    ASN1Primitive obj = null;
    try {
        obj = bIn.readObject();
    } catch (IOException ex) {}
    Enumeration e = ((ASN1Sequence) obj).getObjects();

    byte[] q = null;
    while (e.hasMoreElements()) {
        ASN1Primitive o = (ASN1Primitive) e.nextElement();
        if (o instanceof DERBitString) {
            DERBitString bt = (DERBitString) o;
            q = bt.getBytes();
        }
    }

    int pukL = skfsConstants.P256_PUBLIC_KEY_SIZE; //ECDSA secp256r1 publickey length
    byte[] ob2Sign = new byte[1 + ChanllengeL + ApplicationL + keyHandleL + pukL];

    int tot = 1;
    ob2Sign[0] = constant;
    System.arraycopy(Application, 0, ob2Sign, tot, ApplicationL);
    tot += ApplicationL;
    System.arraycopy(Challenge, 0, ob2Sign, tot, ChanllengeL);
    tot += ChanllengeL;
    System.arraycopy(keyHandle, 0, ob2Sign, tot, keyHandleL);
    tot += keyHandleL;
    System.arraycopy(q, 0, ob2Sign, tot, pukL);
    tot += pukL;

    return Base64.encodeBase64String(ob2Sign);
}