Search in sources :

Example 51 with ASN1Integer

use of org.webpki.asn1.ASN1Integer in project identity-credential by google.

the class Util method signatureCoseToDer.

private static byte[] signatureCoseToDer(byte[] signature) {
    // r and s are always positive and may use all bits so use the constructor which
    // parses them as unsigned.
    BigInteger r = new BigInteger(1, Arrays.copyOfRange(signature, 0, signature.length / 2));
    BigInteger s = new BigInteger(1, Arrays.copyOfRange(signature, signature.length / 2, signature.length));
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        DERSequenceGenerator seq = new DERSequenceGenerator(baos);
        seq.addObject(new ASN1Integer(r.toByteArray()));
        seq.addObject(new ASN1Integer(s.toByteArray()));
        seq.close();
    } catch (IOException e) {
        throw new IllegalStateException("Error generating DER signature", e);
    }
    return baos.toByteArray();
}
Also used : BigInteger(java.math.BigInteger) DERSequenceGenerator(org.bouncycastle.asn1.DERSequenceGenerator) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ASN1Integer(org.bouncycastle.asn1.ASN1Integer) IOException(java.io.IOException)

Example 52 with ASN1Integer

use of org.webpki.asn1.ASN1Integer in project SpringRemote by HaleyWang.

the class PKCS12KeyStore method extractPrivateKey.

/*
     * !!! TODO generalize handling and move to pkcs8 or pkcs1
     */
public static PrivateKey extractPrivateKey(byte[] berPrivateKeyInfo) throws UnrecoverableKeyException {
    ASN1DER ber = new ASN1DER();
    ByteArrayInputStream ba = new ByteArrayInputStream(berPrivateKeyInfo);
    PrivateKeyInfo pki = new PrivateKeyInfo();
    try {
        ber.decode(ba, pki);
        boolean isrsakey = true;
        try {
            String alg = pki.privateKeyAlgorithm.algorithmName().toLowerCase();
            if (alg.indexOf("dsa") >= 0)
                isrsakey = false;
        } catch (Throwable t) {
        }
        ba = new ByteArrayInputStream(pki.privateKey.getRaw());
        if (isrsakey) {
            com.mindbright.security.pkcs1.RSAPrivateKey rsa = new com.mindbright.security.pkcs1.RSAPrivateKey();
            ber.decode(ba, rsa);
            BigInteger n, e, d, p, q, pe, qe, u;
            n = rsa.modulus.getValue();
            e = rsa.publicExponent.getValue();
            d = rsa.privateExponent.getValue();
            p = rsa.prime1.getValue();
            q = rsa.prime2.getValue();
            pe = rsa.exponent1.getValue();
            qe = rsa.exponent2.getValue();
            u = rsa.coefficient.getValue();
            RSAPrivateCrtKeySpec prvSpec = new RSAPrivateCrtKeySpec(n, e, d, p, q, pe, qe, u);
            KeyFactory keyFact = KeyFactory.getInstance("RSA");
            return keyFact.generatePrivate(prvSpec);
        }
        BigInteger x = null;
        try {
            // Normally, we should have just one ASN.1 integer here...
            ASN1Integer dsax = new ASN1Integer();
            ber.decode(ba, dsax);
            x = dsax.getValue();
        } catch (Throwable t) {
        }
        if (x == null) {
            // ... but Mozilla returns SEQUENCE { y? INTEGER, x INTEGER }
            DSAyx dsayx = new DSAyx();
            ber.decode(new ByteArrayInputStream(pki.privateKey.getRaw()), dsayx);
            x = dsayx.x.getValue();
        }
        com.mindbright.security.pkcs1.DSAParams params = (com.mindbright.security.pkcs1.DSAParams) pki.privateKeyAlgorithm.parameters.getValue();
        DSAPrivateKeySpec prvSpec = new DSAPrivateKeySpec(x, params.p.getValue(), params.q.getValue(), params.g.getValue());
        KeyFactory keyFact = KeyFactory.getInstance("DSA");
        return keyFact.generatePrivate(prvSpec);
    } catch (Exception e) {
        throw new UnrecoverableKeyException(e.getMessage());
    }
}
Also used : RSAPrivateCrtKeySpec(java.security.spec.RSAPrivateCrtKeySpec) ASN1DER(com.mindbright.asn1.ASN1DER) ASN1OctetString(com.mindbright.asn1.ASN1OctetString) ASN1CharString(com.mindbright.asn1.ASN1CharString) ASN1Integer(com.mindbright.asn1.ASN1Integer) KeyStoreException(java.security.KeyStoreException) GeneralSecurityException(java.security.GeneralSecurityException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) DSAPrivateKeySpec(java.security.spec.DSAPrivateKeySpec) UnrecoverableKeyException(java.security.UnrecoverableKeyException) ByteArrayInputStream(java.io.ByteArrayInputStream) BigInteger(java.math.BigInteger) PrivateKeyInfo(com.mindbright.security.pkcs8.PrivateKeyInfo) EncryptedPrivateKeyInfo(com.mindbright.security.pkcs8.EncryptedPrivateKeyInfo) KeyFactory(java.security.KeyFactory)

Example 53 with ASN1Integer

use of org.webpki.asn1.ASN1Integer in project itext2 by albfernandez.

the class PdfPKCS7 method getEncodedPKCS7.

/**
 * Gets the bytes for the PKCS7SignedData object. Optionally the authenticatedAttributes
 * in the signerInfo can also be set, OR a time-stamp-authority client
 * may be provided.
 * @param secondDigest the digest in the authenticatedAttributes
 * @param signingTime the signing time in the authenticatedAttributes
 * @param tsaClient TSAClient - null or an optional time stamp authority client
 * @return byte[] the bytes for the PKCS7SignedData object
 * @since	2.1.6
 */
public byte[] getEncodedPKCS7(byte[] secondDigest, Calendar signingTime, TSAClient tsaClient, byte[] ocsp) {
    try {
        if (externalDigest != null) {
            digest = externalDigest;
            if (RSAdata != null)
                RSAdata = externalRSAdata;
        } else if (externalRSAdata != null && RSAdata != null) {
            RSAdata = externalRSAdata;
            sig.update(RSAdata);
            digest = sig.sign();
        } else {
            if (RSAdata != null) {
                RSAdata = messageDigest.digest();
                sig.update(RSAdata);
            }
            digest = sig.sign();
        }
        // Create the set of Hash algorithms
        ASN1EncodableVector digestAlgorithms = new ASN1EncodableVector();
        for (Iterator it = digestalgos.iterator(); it.hasNext(); ) {
            ASN1EncodableVector algos = new ASN1EncodableVector();
            algos.add(new ASN1ObjectIdentifier((String) it.next()));
            algos.add(DERNull.INSTANCE);
            digestAlgorithms.add(new DERSequence(algos));
        }
        // Create the contentInfo.
        ASN1EncodableVector v = new ASN1EncodableVector();
        v.add(new ASN1ObjectIdentifier(ID_PKCS7_DATA));
        if (RSAdata != null)
            v.add(new DERTaggedObject(0, new DEROctetString(RSAdata)));
        DERSequence contentinfo = new DERSequence(v);
        // Get all the certificates
        // 
        v = new ASN1EncodableVector();
        for (Iterator i = certs.iterator(); i.hasNext(); ) {
            ASN1InputStream tempstream = new ASN1InputStream(new ByteArrayInputStream(((X509Certificate) i.next()).getEncoded()));
            v.add(tempstream.readObject());
        }
        DERSet dercertificates = new DERSet(v);
        // Create signerinfo structure.
        // 
        ASN1EncodableVector signerinfo = new ASN1EncodableVector();
        // Add the signerInfo version
        // 
        signerinfo.add(new ASN1Integer(signerversion));
        v = new ASN1EncodableVector();
        v.add(getIssuer(signCert.getTBSCertificate()));
        v.add(new ASN1Integer(signCert.getSerialNumber()));
        signerinfo.add(new DERSequence(v));
        // Add the digestAlgorithm
        v = new ASN1EncodableVector();
        v.add(new ASN1ObjectIdentifier(digestAlgorithm));
        v.add(DERNull.INSTANCE);
        signerinfo.add(new DERSequence(v));
        // add the authenticated attribute if present
        if (secondDigest != null && signingTime != null) {
            signerinfo.add(new DERTaggedObject(false, 0, getAuthenticatedAttributeSet(secondDigest, signingTime, ocsp)));
        }
        // Add the digestEncryptionAlgorithm
        v = new ASN1EncodableVector();
        v.add(new ASN1ObjectIdentifier(digestEncryptionAlgorithm));
        v.add(DERNull.INSTANCE);
        signerinfo.add(new DERSequence(v));
        // Add the digest
        signerinfo.add(new DEROctetString(digest));
        // Sam found Adobe expects time-stamped SHA1-1 of the encrypted digest
        if (tsaClient != null) {
            byte[] tsImprint = MessageDigest.getInstance("SHA-1").digest(digest);
            byte[] tsToken = tsaClient.getTimeStampToken(this, tsImprint);
            if (tsToken != null) {
                ASN1EncodableVector unauthAttributes = buildUnauthenticatedAttributes(tsToken);
                if (unauthAttributes != null) {
                    signerinfo.add(new DERTaggedObject(false, 1, new DERSet(unauthAttributes)));
                }
            }
        }
        // Finally build the body out of all the components above
        ASN1EncodableVector body = new ASN1EncodableVector();
        body.add(new ASN1Integer(version));
        body.add(new DERSet(digestAlgorithms));
        body.add(contentinfo);
        body.add(new DERTaggedObject(false, 0, dercertificates));
        if (!crls.isEmpty()) {
            v = new ASN1EncodableVector();
            for (Iterator i = crls.iterator(); i.hasNext(); ) {
                ASN1InputStream t = new ASN1InputStream(new ByteArrayInputStream(((X509CRL) i.next()).getEncoded()));
                v.add(t.readObject());
            }
            DERSet dercrls = new DERSet(v);
            body.add(new DERTaggedObject(false, 1, dercrls));
        }
        // Only allow one signerInfo
        body.add(new DERSet(new DERSequence(signerinfo)));
        // Now we have the body, wrap it in it's PKCS7Signed shell
        // and return it
        // 
        ASN1EncodableVector whole = new ASN1EncodableVector();
        whole.add(new ASN1ObjectIdentifier(ID_PKCS7_SIGNED_DATA));
        whole.add(new DERTaggedObject(0, new DERSequence(body)));
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        ASN1OutputStream dout = ASN1OutputStream.create(bOut);
        dout.writeObject(new DERSequence(whole));
        dout.close();
        return bOut.toByteArray();
    } catch (Exception e) {
        throw new ExceptionConverter(e);
    }
}
Also used : ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) X509CRL(java.security.cert.X509CRL) DERTaggedObject(org.bouncycastle.asn1.DERTaggedObject) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DEROctetString(org.bouncycastle.asn1.DEROctetString) ASN1String(org.bouncycastle.asn1.ASN1String) ASN1Integer(org.bouncycastle.asn1.ASN1Integer) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ASN1OutputStream(org.bouncycastle.asn1.ASN1OutputStream) DERSet(org.bouncycastle.asn1.DERSet) DEROctetString(org.bouncycastle.asn1.DEROctetString) X509Certificate(java.security.cert.X509Certificate) SignatureException(java.security.SignatureException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) CertificateParsingException(java.security.cert.CertificateParsingException) IOException(java.io.IOException) NoSuchProviderException(java.security.NoSuchProviderException) ExceptionConverter(com.lowagie.text.ExceptionConverter) DERSequence(org.bouncycastle.asn1.DERSequence) ByteArrayInputStream(java.io.ByteArrayInputStream) Iterator(java.util.Iterator) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Example 54 with ASN1Integer

use of org.webpki.asn1.ASN1Integer in project Elastos.DID.Java.SDK by elastos.

the class ECKey method extractKeyFromASN1.

private static ECKey extractKeyFromASN1(byte[] asn1privkey) {
    // 
    try {
        ASN1InputStream decoder = new ASN1InputStream(asn1privkey);
        DLSequence seq = (DLSequence) decoder.readObject();
        checkArgument(decoder.readObject() == null, "Input contains extra bytes");
        decoder.close();
        checkArgument(seq.size() == 4, "Input does not appear to be an ASN.1 OpenSSL EC private key");
        checkArgument(((ASN1Integer) seq.getObjectAt(0)).getValue().equals(BigInteger.ONE), "Input is of wrong version");
        byte[] privbits = ((ASN1OctetString) seq.getObjectAt(1)).getOctets();
        BigInteger privkey = new BigInteger(1, privbits);
        ASN1TaggedObject pubkey = (ASN1TaggedObject) seq.getObjectAt(3);
        checkArgument(pubkey.getTagNo() == 1, "Input has 'publicKey' with bad tag number");
        byte[] pubbits = ((DERBitString) pubkey.getObject()).getBytes();
        checkArgument(pubbits.length == 33 || pubbits.length == 65, "Input has 'publicKey' with invalid length");
        int encoding = pubbits[0] & 0xFF;
        // Only allow compressed(2,3) and uncompressed(4), not infinity(0) or hybrid(6,7)
        checkArgument(encoding >= 2 && encoding <= 4, "Input has 'publicKey' with invalid encoding");
        // Now sanity check to ensure the pubkey bytes match the privkey.
        boolean compressed = isPubKeyCompressed(pubbits);
        ECKey key = new ECKey(privkey, (byte[]) null, compressed);
        if (!Arrays.equals(key.getPubKey(), pubbits))
            throw new IllegalArgumentException("Public key in ASN.1 structure does not match private key.");
        return key;
    } catch (IOException e) {
        // Cannot happen, reading from memory stream.
        throw new RuntimeException(e);
    }
}
Also used : ASN1OctetString(org.spongycastle.asn1.ASN1OctetString) ASN1InputStream(org.spongycastle.asn1.ASN1InputStream) ASN1TaggedObject(org.spongycastle.asn1.ASN1TaggedObject) DERBitString(org.spongycastle.asn1.DERBitString) ASN1Integer(org.spongycastle.asn1.ASN1Integer) IOException(java.io.IOException) ECPoint(org.spongycastle.math.ec.ECPoint) LazyECPoint(org.bitcoinj.crypto.LazyECPoint) DLSequence(org.spongycastle.asn1.DLSequence) BigInteger(java.math.BigInteger)

Example 55 with ASN1Integer

use of org.webpki.asn1.ASN1Integer in project attestation by TokenScript.

the class HelperTest method makeMaximalAtt.

public static IdentifierAttestation makeMaximalAtt(AsymmetricKeyParameter key) throws IOException {
    IdentifierAttestation att = new IdentifierAttestation("205521676", "https://www.deviantart.com/some_user", key);
    att.setSerialNumber(42);
    att.setSigningAlgorithm(IdentifierAttestation.DEFAULT_SIGNING_ALGORITHM);
    att.setIssuer("CN=ALX");
    att.setSmartcontracts(Arrays.asList(42L, 1337L));
    ASN1EncodableVector dataObject = new ASN1EncodableVector();
    dataObject.add(new DEROctetString("hello world".getBytes()));
    dataObject.add(new ASN1Integer(42));
    att.setDataObject(new DERSequence(dataObject));
    assertTrue(att.checkValidity());
    return att;
}
Also used : DERSequence(org.bouncycastle.asn1.DERSequence) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) ASN1Integer(org.bouncycastle.asn1.ASN1Integer) DEROctetString(org.bouncycastle.asn1.DEROctetString)

Aggregations

ASN1Integer (org.bouncycastle.asn1.ASN1Integer)213 ASN1Integer (com.unboundid.asn1.ASN1Integer)96 ASN1Sequence (com.unboundid.asn1.ASN1Sequence)94 ASN1EncodableVector (org.bouncycastle.asn1.ASN1EncodableVector)91 IOException (java.io.IOException)89 DERSequence (org.bouncycastle.asn1.DERSequence)89 ASN1Integer (com.github.zhenwei.core.asn1.ASN1Integer)86 BigInteger (java.math.BigInteger)86 ASN1OctetString (com.unboundid.asn1.ASN1OctetString)80 ASN1Element (com.unboundid.asn1.ASN1Element)69 Test (org.testng.annotations.Test)63 ArrayList (java.util.ArrayList)50 ASN1EncodableVector (com.github.zhenwei.core.asn1.ASN1EncodableVector)49 DERSequence (com.github.zhenwei.core.asn1.DERSequence)47 ASN1Sequence (org.bouncycastle.asn1.ASN1Sequence)47 DEROctetString (org.bouncycastle.asn1.DEROctetString)38 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)35 ASN1InputStream (org.bouncycastle.asn1.ASN1InputStream)28 ASN1Encodable (org.bouncycastle.asn1.ASN1Encodable)27 AlgorithmIdentifier (org.bouncycastle.asn1.x509.AlgorithmIdentifier)27