Java Code Examples for org.bouncycastle.asn1.ASN1InputStream#readObject()

The following examples show how to use org.bouncycastle.asn1.ASN1InputStream#readObject() . 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: SoftKeymasterBlob.java    From keystore-decryptor with Apache License 2.0 6 votes vote down vote up
private void parseDsaKeyPair(byte[] blob) throws GeneralSecurityException,
        IOException {
    ASN1InputStream ain = new ASN1InputStream(new ByteArrayInputStream(
            blob));
    ASN1Sequence seq = (ASN1Sequence) ain.readObject();
    ain.close();

    ASN1Integer p = (ASN1Integer) seq.getObjectAt(1);
    ASN1Integer q = (ASN1Integer) seq.getObjectAt(2);
    ASN1Integer g = (ASN1Integer) seq.getObjectAt(3);
    ASN1Integer y = (ASN1Integer) seq.getObjectAt(4);
    ASN1Integer x = (ASN1Integer) seq.getObjectAt(5);
    DSAPrivateKeySpec privSpec = new DSAPrivateKeySpec(x.getValue(), p.getValue(),
            q.getValue(), g.getValue());
    DSAPublicKeySpec pubSpec = new DSAPublicKeySpec(y.getValue(), p.getValue(), q.getValue(),
            g.getValue());

    KeyFactory kf = KeyFactory.getInstance("DSA");
    privateKey = kf.generatePrivate(privSpec);
    publicKey = kf.generatePublic(pubSpec);
}
 
Example 2
Source File: ECDSASignatureProvider.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static byte[] asn1derToConcatenatedRS(final byte[] derEncodedSignatureValue, int signLength) throws IOException {
    int len = signLength / 2;

    ASN1InputStream asn1InputStream = new ASN1InputStream(derEncodedSignatureValue);
    ASN1Primitive asn1Primitive = asn1InputStream.readObject();
    asn1InputStream.close();

    ASN1Sequence asn1Sequence = (ASN1Sequence.getInstance(asn1Primitive));
    ASN1Integer rASN1 = (ASN1Integer) asn1Sequence.getObjectAt(0);
    ASN1Integer sASN1 = (ASN1Integer) asn1Sequence.getObjectAt(1);
    X9IntegerConverter x9IntegerConverter = new X9IntegerConverter();
    byte[] r = x9IntegerConverter.integerToBytes(rASN1.getValue(), len);
    byte[] s = x9IntegerConverter.integerToBytes(sASN1.getValue(), len);

    byte[] concatenatedSignatureValue = new byte[signLength];
    System.arraycopy(r, 0, concatenatedSignatureValue, 0, len);
    System.arraycopy(s, 0, concatenatedSignatureValue, len, len);

    return concatenatedSignatureValue;
}
 
Example 3
Source File: rsasign.java    From JrebelBrainsLicenseServerforJava with Apache License 2.0 6 votes vote down vote up
public static String Sign(byte[] content, String privateKey) {
try {
	byte[] keybyte = Base64.decode(privateKey.toString());
	ASN1InputStream in = new ASN1InputStream(keybyte);
	ASN1Primitive obj = in.readObject();
	RSAPrivateKeyStructure pStruct = RSAPrivateKeyStructure.getInstance(obj);
	RSAPrivateKeySpec spec = new RSAPrivateKeySpec(pStruct.getModulus(), pStruct.getPrivateExponent());
	KeyFactory keyFactory = KeyFactory.getInstance("RSA");
	PrivateKey priKey = keyFactory.generatePrivate(spec);
	java.security.Signature signature = java.security.Signature.getInstance("MD5WithRSA");
	signature.initSign(priKey);
	signature.update(content);
	byte[] signed = signature.sign();
	return Hex.bytesToHexString(signed);
       }
       catch (Exception e) {
           e.printStackTrace();
       }
       return null;
   }
 
Example 4
Source File: Asn1Utils.java    From android-testdpc with Apache License 2.0 6 votes vote down vote up
public static ASN1Sequence getAsn1SequenceFromStream(final ASN1InputStream asn1InputStream)
        throws IOException, CertificateParsingException {
    ASN1Primitive asn1Primitive = asn1InputStream.readObject();
    if (!(asn1Primitive instanceof ASN1OctetString)) {
        throw new CertificateParsingException(
                "Expected octet stream, found " + asn1Primitive.getClass().getName());
    }
    try (ASN1InputStream seqInputStream = new ASN1InputStream(
            ((ASN1OctetString) asn1Primitive).getOctets())) {
        asn1Primitive = seqInputStream.readObject();
        if (!(asn1Primitive instanceof ASN1Sequence)) {
            throw new CertificateParsingException(
                    "Expected sequence, found " + asn1Primitive.getClass().getName());
        }
        return (ASN1Sequence) asn1Primitive;
    }
}
 
Example 5
Source File: Asn1Utils.java    From AttestationServer with MIT License 6 votes vote down vote up
public static ASN1Sequence getAsn1SequenceFromStream(final ASN1InputStream asn1InputStream)
        throws IOException, CertificateParsingException {
    ASN1Primitive asn1Primitive = asn1InputStream.readObject();
    if (!(asn1Primitive instanceof ASN1OctetString)) {
        throw new CertificateParsingException(
                "Expected octet stream, found " + asn1Primitive.getClass().getName());
    }
    try (ASN1InputStream seqInputStream = new ASN1InputStream(
            ((ASN1OctetString) asn1Primitive).getOctets())) {
        asn1Primitive = seqInputStream.readObject();
        if (!(asn1Primitive instanceof ASN1Sequence)) {
            throw new CertificateParsingException(
                    "Expected sequence, found " + asn1Primitive.getClass().getName());
        }
        return (ASN1Sequence) asn1Primitive;
    }
}
 
Example 6
Source File: CFDv3Debugger.java    From factura-electronica with Apache License 2.0 6 votes vote down vote up
private void dumpDigests() throws Exception {
    System.err.println(cfd.getCadenaOriginal());
    String certStr = cfd.document.getCertificado();
    Base64 b64 = new Base64();
    byte[] cbs = b64.decode(certStr);
    X509Certificate cert = (X509Certificate) KeyLoaderFactory.createInstance(
            KeyLoaderEnumeration.PUBLIC_KEY_LOADER,
            new ByteArrayInputStream(cbs)).getKey();
    cert.checkValidity();
    String sigStr = cfd.document.getSello();
    byte[] signature = b64.decode(sigStr);
    CFDv3.dump("Digestion firmada", signature, System.err);
    Cipher dec = Cipher.getInstance("RSA");
    dec.init(Cipher.DECRYPT_MODE, cert);
    byte[] result = dec.doFinal(signature);
    CFDv3.dump("Digestion decriptada", result, System.err);
    ASN1InputStream aIn = new ASN1InputStream(result);
    ASN1Sequence seq = (ASN1Sequence) aIn.readObject();
    ASN1OctetString sigHash = (ASN1OctetString) seq.getObjectAt(1);
    CFDv3.dump("Sello", sigHash.getOctets(), System.err);
}
 
Example 7
Source File: PdfPKCS7.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Added by Aiken Sam, 2006-11-15, modifed by Martin Brunecky 07/12/2007
 * to start with the timeStampToken (signedData 1.2.840.113549.1.7.2).
 * Token is the TSA response without response status, which is usually
 * handled by the (vendor supplied) TSA request/response interface).
 * @param timeStampToken byte[] - time stamp token, DER encoded signedData
 * @return ASN1EncodableVector
 * @throws IOException
 */
private ASN1EncodableVector buildUnauthenticatedAttributes(byte[] timeStampToken)  throws IOException {
    if (timeStampToken == null)
        return null;

    // @todo: move this together with the rest of the defintions
    String ID_TIME_STAMP_TOKEN = "1.2.840.113549.1.9.16.2.14"; // RFC 3161 id-aa-timeStampToken

    ASN1InputStream tempstream = new ASN1InputStream(new ByteArrayInputStream(timeStampToken));
    ASN1EncodableVector unauthAttributes = new ASN1EncodableVector();

    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(new ASN1ObjectIdentifier(ID_TIME_STAMP_TOKEN)); // id-aa-timeStampToken
    ASN1Sequence seq = (ASN1Sequence) tempstream.readObject();
    v.add(new DERSet(seq));

    unauthAttributes.add(new DERSequence(v));
    return unauthAttributes;
 }
 
Example 8
Source File: AbstractRequirementChecks.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
@BeforeEach
public void init() throws Exception {
	DSSDocument signedDocument = getSignedDocument();

	ASN1InputStream asn1sInput = new ASN1InputStream(signedDocument.openStream());
	ASN1Sequence asn1Seq = (ASN1Sequence) asn1sInput.readObject();
	assertEquals(2, asn1Seq.size());
	ASN1ObjectIdentifier oid = ASN1ObjectIdentifier.getInstance(asn1Seq.getObjectAt(0));
	assertEquals(PKCSObjectIdentifiers.signedData, oid);

	ASN1TaggedObject taggedObj = ASN1TaggedObject.getInstance(asn1Seq.getObjectAt(1));
	signedData = SignedData.getInstance(taggedObj.getObject());

	ASN1Set signerInfosAsn1 = signedData.getSignerInfos();
	assertEquals(1, signerInfosAsn1.size());

	signerInfo = SignerInfo.getInstance(ASN1Sequence.getInstance(signerInfosAsn1.getObjectAt(0)));

	Utils.closeQuietly(asn1sInput);
}
 
Example 9
Source File: CAdESTimeStampSigner.java    From signer with GNU Lesser General Public License v3.0 6 votes vote down vote up
private Timestamp checkTimeStamp(byte[] timeStamp, byte[] content,  byte[] hash){
	try {
		Security.addProvider(new BouncyCastleProvider());
		ais = new ASN1InputStream(new ByteArrayInputStream(timeStamp));
	    ASN1Sequence seq=(ASN1Sequence)ais.readObject();
        Attribute attributeTimeStamp = new Attribute((ASN1ObjectIdentifier)seq.getObjectAt(0), (ASN1Set)seq.getObjectAt(1));
        byte[] varTimeStamp = attributeTimeStamp.getAttrValues().getObjectAt(0).toASN1Primitive().getEncoded();
        TimeStampOperator timeStampOperator = new TimeStampOperator();
        if (content != null){
        	timeStampOperator.validate(content, varTimeStamp,null);
        }else{
        	timeStampOperator.validate(null, varTimeStamp,hash);
        }			
		TimeStampToken timeStampToken = new TimeStampToken(new CMSSignedData(varTimeStamp));
		Timestamp timeStampSigner = new Timestamp(timeStampToken);
		return timeStampSigner;
	} catch (CertificateCoreException | IOException | TSPException
			| CMSException e) {
		throw new SignerException(e);
	}

}
 
Example 10
Source File: BouncyCastleCrypto.java    From fabric-api-archive with Apache License 2.0 6 votes vote down vote up
@Override
public boolean verify(byte[] hash, byte[] signature, byte[] publicKey) {
    ASN1InputStream asn1 = new ASN1InputStream(signature);
    try {
        ECDSASigner signer = new ECDSASigner();
        signer.init(false, new ECPublicKeyParameters(curve.getCurve().decodePoint(publicKey), domain));

        DLSequence seq = (DLSequence) asn1.readObject();
        BigInteger r = ((ASN1Integer) seq.getObjectAt(0)).getPositiveValue();
        BigInteger s = ((ASN1Integer) seq.getObjectAt(1)).getPositiveValue();
        return signer.verifySignature(hash, r, s);
    } catch (Exception e) {
        return false;
    } finally {
        try {
            asn1.close();
        } catch (IOException ignored) {
        }
    }
}
 
Example 11
Source File: PdfPublicKeySecurityHandler.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
private ASN1Primitive createDERForRecipient(byte[] in, X509Certificate cert) 
    throws IOException,  
           GeneralSecurityException 
{
    
    String s = "1.2.840.113549.3.2";
    
    AlgorithmParameterGenerator algorithmparametergenerator = AlgorithmParameterGenerator.getInstance(s);
    AlgorithmParameters algorithmparameters = algorithmparametergenerator.generateParameters();
    ByteArrayInputStream bytearrayinputstream = new ByteArrayInputStream(algorithmparameters.getEncoded("ASN.1"));
    ASN1InputStream asn1inputstream = new ASN1InputStream(bytearrayinputstream);
    ASN1Primitive derobject = asn1inputstream.readObject();
    KeyGenerator keygenerator = KeyGenerator.getInstance(s);
    keygenerator.init(128);
    SecretKey secretkey = keygenerator.generateKey();
    Cipher cipher = Cipher.getInstance(s);
    cipher.init(1, secretkey, algorithmparameters);
    byte[] abyte1 = cipher.doFinal(in);
    DEROctetString deroctetstring = new DEROctetString(abyte1);
    KeyTransRecipientInfo keytransrecipientinfo = computeRecipientInfo(cert, secretkey.getEncoded());
    DERSet derset = new DERSet(new RecipientInfo(keytransrecipientinfo));
    AlgorithmIdentifier algorithmidentifier = new AlgorithmIdentifier(new ASN1ObjectIdentifier(s), derobject);
    EncryptedContentInfo encryptedcontentinfo = 
        new EncryptedContentInfo(PKCSObjectIdentifiers.data, algorithmidentifier, deroctetstring);
    EnvelopedData env = new EnvelopedData(null, derset, encryptedcontentinfo, (org.bouncycastle.asn1.ASN1Set) null);
    ContentInfo contentinfo = 
        new ContentInfo(PKCSObjectIdentifiers.envelopedData, env);
    return contentinfo.toASN1Primitive();        
}
 
Example 12
Source File: ECKey.java    From bushido-java-core with GNU General Public License v3.0 5 votes vote down vote up
public boolean verify(byte[] message, byte[] signature) throws Exception
{
    ASN1InputStream asn1 = new ASN1InputStream(signature);
    ECDSASigner signer = new ECDSASigner();
    //not for signing...
    signer.init(false, new ECPublicKeyParameters(curve.getCurve().decodePoint(pub), params));
    DLSequence seq = (DLSequence) asn1.readObject();
    BigInteger r = ((ASN1Integer) seq.getObjectAt(0)).getPositiveValue();
    BigInteger s = ((ASN1Integer) seq.getObjectAt(1)).getPositiveValue();
    return signer.verifySignature(message, r, s);
}
 
Example 13
Source File: Asn1.java    From UAF with Apache License 2.0 5 votes vote down vote up
/**
 * DER - From byte[] to Big Integer rs
 * UAF_ALG_SIGN_SECP256K1_ECDSA_SHA256_DER 0x06 DER [ITU-X690-2008] encoded
 * ECDSA signature [RFC5480] on the secp256k1 curve. I.e. a DER encoded
 * SEQUENCE { r INTEGER, s INTEGER }
 * 
 * @param signature
 * @return
 * @throws IOException
 */
public static BigInteger[] decodeToBigIntegerArray(byte[] signature)
		throws IOException {
	ASN1InputStream decoder = new ASN1InputStream(signature);
	DLSequence seq = (DLSequence) decoder.readObject();
	ASN1Integer r = (ASN1Integer) seq.getObjectAt(0);
	ASN1Integer s = (ASN1Integer) seq.getObjectAt(1);
	decoder.close();
	BigInteger[] ret = new BigInteger[2];
	ret[0] = r.getPositiveValue();
	ret[1] = s.getPositiveValue();
	return ret;
}
 
Example 14
Source File: CryptoPrimitives.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 * Decodes an ECDSA signature and returns a two element BigInteger array.
 *
 * @param signature ECDSA signature bytes.
 * @return BigInteger array for the signature's r and s values
 * @throws Exception
 */
private static BigInteger[] decodeECDSASignature(byte[] signature) throws Exception {

    try (ByteArrayInputStream inStream = new ByteArrayInputStream(signature)) {
        ASN1InputStream asnInputStream = new ASN1InputStream(inStream);
        ASN1Primitive asn1 = asnInputStream.readObject();

        BigInteger[] sigs = new BigInteger[2];
        int count = 0;
        if (asn1 instanceof ASN1Sequence) {
            ASN1Sequence asn1Sequence = (ASN1Sequence) asn1;
            ASN1Encodable[] asn1Encodables = asn1Sequence.toArray();
            for (ASN1Encodable asn1Encodable : asn1Encodables) {
                ASN1Primitive asn1Primitive = asn1Encodable.toASN1Primitive();
                if (asn1Primitive instanceof ASN1Integer) {
                    ASN1Integer asn1Integer = (ASN1Integer) asn1Primitive;
                    BigInteger integer = asn1Integer.getValue();
                    if (count < 2) {
                        sigs[count] = integer;
                    }
                    count++;
                }
            }
        }
        if (count != 2) {
            throw new CryptoException(format("Invalid ECDSA signature. Expected count of 2 but got: %d. Signature is: %s", count,
                    DatatypeConverter.printHexBinary(signature)));
        }
        return sigs;
    }

}
 
Example 15
Source File: PdfPKCS7.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Get the "subject" from the TBSCertificate bytes that are passed in
 * @param enc A TBSCertificate in a byte array
 * @return a DERObject
 */
private static ASN1Primitive getSubject(byte[] enc) {
    try {
        ASN1InputStream in = new ASN1InputStream(new ByteArrayInputStream(enc));
        ASN1Sequence seq = (ASN1Sequence)in.readObject();
        return (ASN1Primitive)seq.getObjectAt(seq.getObjectAt(0) instanceof ASN1TaggedObject ? 5 : 4);
    }
    catch (IOException e) {
        throw new ExceptionConverter(e);
    }
}
 
Example 16
Source File: SoftKeymasterBlob.java    From keystore-decryptor with Apache License 2.0 5 votes vote down vote up
public void parseRsaKeyPair(byte[] b) throws GeneralSecurityException, IOException {
    ASN1InputStream ain = new ASN1InputStream(new ByteArrayInputStream(b));
    ASN1Sequence seq = (ASN1Sequence) ain.readObject();
    ain.close();

    org.bouncycastle.asn1.pkcs.RSAPrivateKey pk = org.bouncycastle.asn1.pkcs.RSAPrivateKey
            .getInstance(seq);
    privateKey = toJcaPrivateKey(pk);
    publicKey = toJcaPublicKey(pk);
}
 
Example 17
Source File: SoftKeymasterBlob.java    From keystore-decryptor with Apache License 2.0 5 votes vote down vote up
public static RSAPrivateKey parseRsaKey(byte[] b) throws GeneralSecurityException, IOException {
    ASN1InputStream ain = new ASN1InputStream(new ByteArrayInputStream(b));
    ASN1Sequence seq = (ASN1Sequence) ain.readObject();
    ain.close();
    for (int i = 0; i < seq.size(); i++) {
        ASN1Integer p = (ASN1Integer) seq.getObjectAt(i);
        System.out.printf("%d::%s\n", i, p.toString());
    }

    org.bouncycastle.asn1.pkcs.RSAPrivateKey pk = org.bouncycastle.asn1.pkcs.RSAPrivateKey
            .getInstance(seq);
    return toJcaPrivateKey(pk);
}
 
Example 18
Source File: UserIdentityExtractor.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public Object extractUserIdentity(X509Certificate[] certs) {
    if (certs == null || certs.length == 0) {
        throw new IllegalArgumentException();
    }

    try {
        Collection<List<?>> subjectAlternativeNames = certs[0].getSubjectAlternativeNames();

        if (subjectAlternativeNames == null) {
            return null;
        }

        Iterator<List<?>> iterator = subjectAlternativeNames.iterator();

        boolean foundUpn = false;
        String tempOtherName = null;
        String tempOid = null;

        while (iterator.hasNext() && !foundUpn) {
            List<?> next = iterator.next();

            if (Integer.class.cast(next.get(0)) == generalName) {

                // We will try to find UPN_OID among the subjectAltNames of type 'otherName' . Just if not found, we will fallback to the other type
                for (int i = 1 ; i<next.size() ; i++) {
                    Object obj = next.get(i);

                    // We have Subject Alternative Name of other type than 'otherName' . Just return it directly
                    if (generalName != 0) {
                        logger.tracef("Extracted identity '%s' from Subject Alternative Name of type '%d'", obj, generalName);
                        return obj;
                    }

                    byte[] otherNameBytes = (byte[]) obj;

                    try {
                        ASN1InputStream asn1Stream = new ASN1InputStream(new ByteArrayInputStream(otherNameBytes));
                        ASN1Encodable asn1otherName = asn1Stream.readObject();
                        asn1otherName = unwrap(asn1otherName);

                        ASN1Sequence asn1Sequence = ASN1Sequence.getInstance(asn1otherName);

                        if (asn1Sequence != null) {
                            ASN1Encodable encodedOid = asn1Sequence.getObjectAt(0);
                            ASN1ObjectIdentifier oid = ASN1ObjectIdentifier.getInstance(unwrap(encodedOid));
                            tempOid = oid.getId();

                            ASN1Encodable principalNameEncoded = asn1Sequence.getObjectAt(1);
                            DERUTF8String principalName = DERUTF8String.getInstance(unwrap(principalNameEncoded));

                            tempOtherName = principalName.getString();

                            // We found UPN among the 'otherName' principal. We don't need to look other
                            if (UPN_OID.equals(tempOid)) {
                                foundUpn = true;
                                break;
                            }
                        }

                    } catch (Exception e) {
                        logger.error("Failed to parse subjectAltName", e);
                    }
                }

            }
        }

        logger.tracef("Parsed otherName from subjectAltName. OID: '%s', Principal: '%s'", tempOid, tempOtherName);

        return tempOtherName;

    } catch (CertificateParsingException cause) {
        logger.errorf(cause, "Failed to obtain identity from subjectAltName extension");
    }

    return null;
}
 
Example 19
Source File: Common.java    From fido2 with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Function to create the packed FIDO U2F data-structure to sign when
 * registering a new public-key with a FIDO U2F server. See the U2F Raw
 * Messages specification for details:
 *
 * https://fidoalliance.org/specs/fido-u2f-v1.0-nfc-bt-amendment-20150514/fido-u2f-raw-message-formats.html
 *
 * @param ApplicationParam String The application parameter is the SHA-256
 * hash of the application identity of the application requesting the
 * registration; it is 32-bytes in length
 * @param ChallengeParam String The challenge parameter is the SHA-256 hash
 * of the Client Data, a string JSON data structure the FIDO Client
 * prepares. Among other things, the Client Data contains the challenge from
 * the relying party (hence the name of the parameter)
 * @param kh String Base64-encoded, encrypted JSON data-structure of the
 * private-key, origin and the message-digest of the private-key
 * @param PublicKey String Base64-encoded public-key of the ECDSA key-pair
 * @return String Base64-encoded data-structure of the object being signed
 * as per the FIDO U2F protocol for a new-key registration
 *
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 * @throws InvalidKeySpecException
 * @throws java.io.IOException
 */
public static String createRegistrationObjectToSign(String ApplicationParam,
        String ChallengeParam,
        String kh,
        String PublicKey)
        throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException, IOException {
    // U2F Signed Registration constant
    final byte[] constant = {(byte) 0x00};
    int constantL = constant.length;

    // 32-byte challenge parameter
    byte[] Challenge = Base64.getUrlDecoder().decode(ChallengeParam);
    int ChanllengeL = Challenge.length;

    // 32-byte application parameter
    byte[] Application = Base64.getUrlDecoder().decode(ApplicationParam);
    int ApplicationL = Application.length;

    // Variable length encrypted key-handle JSON data-structure
    byte[] keyHandle = Base64.getUrlDecoder().decode(kh);
    int keyHandleL = keyHandle.length;

    // Fixed-length ECDSA public key
    byte[] publicKey = Base64.getUrlDecoder().decode(PublicKey);
    int pbkL = Constants.ECDSA_P256_PUBLICKEY_LENGTH;

    // Test the public key for sanity
    KeyFactory kf = KeyFactory.getInstance("ECDSA", "BCFIPS");
    X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(publicKey);
    PublicKey pub = kf.generatePublic(pubKeySpec);
    ECPublicKey ecpub = (ECPublicKey) pub;

    ASN1InputStream bIn = new ASN1InputStream(new ByteArrayInputStream(pub.getEncoded()));
    ASN1Primitive obj = bIn.readObject();
    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();
        }
    }

    // Create byte[] for to-be-signed (TBS) object
    // Could have also used  ByteBuffer for this
    int currpos = 0;
    byte[] tbs = new byte[constantL + ChanllengeL + ApplicationL + keyHandleL + pbkL];

    // Copy the Signed Registration constant to TBS
    System.arraycopy(constant, 0, tbs, currpos, constantL);
    currpos += constantL;

    // Copy ApplicationParameters to TBS
    System.arraycopy(Application, 0, tbs, currpos, ApplicationL);
    currpos += ApplicationL;

    // Copy ChallengeParameters to TBS
    System.arraycopy(Challenge, 0, tbs, currpos, ChanllengeL);
    currpos += ChanllengeL;

    // Copy encrypted KeyHandle JSON to TBS
    System.arraycopy(keyHandle, 0, tbs, currpos, keyHandleL);
    currpos += keyHandleL;

    // Copy public-key to TBS
    System.arraycopy(q, 0, tbs, currpos, pbkL);

    // Return Base64-encoded TBS
    return Base64.getUrlEncoder().encodeToString(tbs);
}
 
Example 20
Source File: CipherSuiteUtil.java    From DeepViolet with Apache License 2.0 3 votes vote down vote up
/**
 * Convert <code>der</code> encoded data to <code>ASN1Primitive</code>.
 * For more information, 
 * (<a href="http://stackoverflow.com/questions/2409618/how-do-i-decode-a-der-encoded-string-in-java">StackOverflow: How do I decode a DER encoded string in Java?</a>) 
 * @param data byte[] of <code>der</code> encoded data
 * @return <code>ASN1Primitive</code> representation of <code>der</code> encoded data
 * @throws IOException
 */
static final ASN1Primitive toDERObject(byte[] data) throws IOException {
	   
	ByteArrayInputStream inStream = new ByteArrayInputStream(data);
	
	ASN1InputStream asnInputStream = new ASN1InputStream(inStream);
    
    ASN1Primitive p = asnInputStream.readObject();

    asnInputStream.close();
    
    return p;
}