Example usage for org.bouncycastle.operator ContentSigner getOutputStream

List of usage examples for org.bouncycastle.operator ContentSigner getOutputStream

Introduction

In this page you can find the example usage for org.bouncycastle.operator ContentSigner getOutputStream.

Prototype

OutputStream getOutputStream();

Source Link

Document

Returns a stream that will accept data for the purpose of calculating a signature.

Usage

From source file:dorkbox.util.crypto.CryptoX509.java

License:Apache License

/**
 * Creates a NEW signature block that contains the pkcs7 (minus content, which is the .SF file)
 * signature of the .SF file./*from www .  ja va2  s . co m*/
 *
 * It contains the hash of the data, and the verification signature.
 */
public static byte[] createSignature(byte[] signatureSourceData, X509CertificateHolder x509CertificateHolder,
        AsymmetricKeyParameter privateKey) {

    try {
        CMSTypedData content = new CMSProcessableByteArray(signatureSourceData);

        ASN1ObjectIdentifier contentTypeOID = new ASN1ObjectIdentifier(content.getContentType().getId());
        ASN1EncodableVector digestAlgs = new ASN1EncodableVector();
        ASN1EncodableVector signerInfos = new ASN1EncodableVector();

        AlgorithmIdentifier sigAlgId = x509CertificateHolder.getSignatureAlgorithm();
        AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);

        // use the bouncy-castle lightweight API to generate a hash of the signature source data (usually the signature file bytes)
        BcContentSignerBuilder contentSignerBuilder;
        AlgorithmIdentifier digEncryptionAlgorithm;

        if (privateKey instanceof ECPrivateKeyParameters) {
            contentSignerBuilder = new BcECDSAContentSignerBuilder(sigAlgId, digAlgId);
            digEncryptionAlgorithm = new AlgorithmIdentifier(DSAUtil.dsaOids[0], null); // 1.2.840.10040.4.1  // DSA hashID
        } else if (privateKey instanceof DSAPrivateKeyParameters) {
            contentSignerBuilder = new BcDSAContentSignerBuilder(sigAlgId, digAlgId);
            digEncryptionAlgorithm = new AlgorithmIdentifier(DSAUtil.dsaOids[0], null); // 1.2.840.10040.4.1  // DSA hashID
        } else if (privateKey instanceof RSAPrivateCrtKeyParameters) {
            contentSignerBuilder = new BcRSAContentSignerBuilder(sigAlgId, digAlgId);
            digEncryptionAlgorithm = new AlgorithmIdentifier(RSAUtil.rsaOids[0], null); // 1.2.840.113549.1.1.1 // RSA hashID
        } else {
            throw new RuntimeException("Invalid signature type. Only ECDSA, DSA, RSA supported.");
        }

        ContentSigner hashSigner = contentSignerBuilder.build(privateKey);
        OutputStream outputStream = hashSigner.getOutputStream();
        outputStream.write(signatureSourceData, 0, signatureSourceData.length);
        outputStream.flush();
        byte[] sigBytes = hashSigner.getSignature();

        SignerIdentifier sigId = new SignerIdentifier(
                new IssuerAndSerialNumber(x509CertificateHolder.toASN1Structure()));

        SignerInfo inf = new SignerInfo(sigId, digAlgId, null, digEncryptionAlgorithm,
                new DEROctetString(sigBytes), (ASN1Set) null);

        digestAlgs.add(inf.getDigestAlgorithm());
        signerInfos.add(inf);

        ASN1EncodableVector certs = new ASN1EncodableVector();
        certs.add(x509CertificateHolder.toASN1Structure());

        ContentInfo encInfo = new ContentInfo(contentTypeOID, null);
        SignedData sd = new SignedData(new DERSet(digestAlgs), encInfo, new BERSet(certs), null,
                new DERSet(signerInfos));

        ContentInfo contentInfo = new ContentInfo(CMSObjectIdentifiers.signedData, sd);
        CMSSignedData cmsSignedData2 = new CMSSignedData(content, contentInfo);

        return cmsSignedData2.getEncoded();
    } catch (Throwable t) {
        logger.error("Error signing data.", t);
        throw new RuntimeException("Error trying to sign data. " + t.getMessage());
    }
}

From source file:org.cesecore.util.CertTools.java

License:Open Source License

/**
 * Generates a PKCS10CertificationRequest
 * //from www .  jav a2 s .  co  m
 * Code Example:
 * -------------
 * An example of putting AltName and a password challenge in an 'attributes' set (taken from RequestMessageTest.test01Pkcs10RequestMessage() ):
 *       
 *      {@code
 *      // Create a P10 with extensions, in this case altNames with a DNS name
 *      ASN1EncodableVector altnameattr = new ASN1EncodableVector();
 *      altnameattr.add(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
 *      // AltNames
 *      GeneralNames san = CertTools.getGeneralNamesFromAltName("dNSName=foo1.bar.com");
 *      ExtensionsGenerator extgen = new ExtensionsGenerator();
 *      extgen.addExtension(Extension.subjectAlternativeName, false, san );
 *      Extensions exts = extgen.generate();
 *      altnameattr.add(new DERSet(exts));
 *    
 *      // Add a challenge password as well
 *      ASN1EncodableVector pwdattr = new ASN1EncodableVector();
 *      pwdattr.add(PKCSObjectIdentifiers.pkcs_9_at_challengePassword); 
 *      ASN1EncodableVector pwdvalues = new ASN1EncodableVector();
 *      pwdvalues.add(new DERUTF8String("foo123"));
 *      pwdattr.add(new DERSet(pwdvalues));
 *    
 *      // Complete the Attribute section of the request, the set (Attributes)
 *      // contains one sequence (Attribute)
 *      ASN1EncodableVector v = new ASN1EncodableVector();
 *      v.add(new DERSequence(altnameattr));
 *      v.add(new DERSequence(pwdattr));
 *      DERSet attributes = new DERSet(v);
 *      }
 * 
 * @param signatureAlgorithm
 * @param subject   The request's subjectDN
 * @param publickey the public key for the certificate requesting signing
 * @param attributes    A set of attributes, for example, extensions, challenge password, etc.
 * @param privateKey the private key used to generate the certificate
 * @param provider
 * @return a PKCS10CertificateRequest based on the input parameters.
 * 
 * @throws OperatorCreationException if an error occurred while creating the signing key
 */
public static PKCS10CertificationRequest genPKCS10CertificationRequest(String signatureAlgorithm,
        X500Name subject, PublicKey publickey, ASN1Set attributes, PrivateKey privateKey, String provider)
        throws OperatorCreationException {

    ContentSigner signer;
    CertificationRequestInfo reqInfo;
    try {
        ASN1Sequence seq = (ASN1Sequence) ASN1Primitive.fromByteArray(publickey.getEncoded());
        SubjectPublicKeyInfo pkinfo = new SubjectPublicKeyInfo(seq);
        reqInfo = new CertificationRequestInfo(subject, pkinfo, attributes);

        if (provider == null) {
            provider = BouncyCastleProvider.PROVIDER_NAME;
        }
        signer = new BufferingContentSigner(
                new JcaContentSignerBuilder(signatureAlgorithm).setProvider(provider).build(privateKey), 20480);
        signer.getOutputStream().write(reqInfo.getEncoded(ASN1Encoding.DER));
        signer.getOutputStream().flush();
    } catch (IOException e) {
        throw new IllegalStateException("Unexpected IOException was caught.", e);
    }
    byte[] sig = signer.getSignature();
    DERBitString sigBits = new DERBitString(sig);

    CertificationRequest req = new CertificationRequest(reqInfo, signer.getAlgorithmIdentifier(), sigBits);
    return new PKCS10CertificationRequest(req);
}

From source file:org.xipki.commons.security.DefaultConcurrentContentSigner.java

License:Open Source License

@Override
public boolean isHealthy() {
    ContentSigner signer = null;
    try {/*  ww w  . j  a va  2s  . co m*/
        signer = borrowContentSigner();
        OutputStream stream = signer.getOutputStream();
        stream.write(new byte[] { 1, 2, 3, 4 });
        byte[] signature = signer.getSignature();
        return signature != null && signature.length > 0;
    } catch (Exception ex) {
        LogUtil.error(LOG, ex);
        return false;
    } finally {
        if (signer != null) {
            returnContentSigner(signer);
        }
    }
}

From source file:org.xipki.commons.security.DefaultConcurrentContentSigner.java

License:Open Source License

@Override
public byte[] sign(final byte[] data) throws NoIdleSignerException, IOException {
    ContentSigner contentSigner = borrowContentSigner();
    try {/*from   w w w .j  a  v a 2  s  .c  om*/
        OutputStream signatureStream = contentSigner.getOutputStream();
        signatureStream.write(data);
        return contentSigner.getSignature();
    } finally {
        returnContentSigner(contentSigner);
    }
}

From source file:org.xipki.security.DefaultConcurrentContentSigner.java

License:Open Source License

@Override
public boolean isHealthy() {
    ContentSigner signer = null;
    try {/*from w w w  .  j a v a 2s .c o  m*/
        signer = borrowContentSigner();
        OutputStream stream = signer.getOutputStream();
        stream.write(new byte[] { 1, 2, 3, 4 });
        byte[] signature = signer.getSignature();
        return signature != null && signature.length > 0;
    } catch (Exception e) {
        final String message = "isHealthy()";
        if (LOG.isErrorEnabled()) {
            LOG.error(LogUtil.buildExceptionLogFormat(message), e.getClass().getName(), e.getMessage());
        }
        LOG.debug(message, e);
        return false;
    } finally {
        if (signer != null) {
            returnContentSigner(signer);
        }
    }
}

From source file:org.xipki.security.SecurityFactoryImpl.java

License:Open Source License

private static void validateSigner(final ConcurrentContentSigner signer,
        final X509Certificate[] certificateChain, final String signerType, final String signerConf)
        throws SignerException {
    X509Certificate cert = signer.getCertificate();
    if (certificateChain == null) {
        return;/*from  ww  w.  jav a  2s.  c o m*/
    }

    String signatureAlgoName;
    try {
        signatureAlgoName = AlgorithmUtil.getSignatureAlgoName(signer.getAlgorithmIdentifier());
    } catch (NoSuchAlgorithmException e) {
        throw new SignerException(e.getMessage(), e);
    }

    ContentSigner csigner;
    try {
        csigner = signer.borrowContentSigner();
    } catch (NoIdleSignerException e) {
        throw new SignerException(e.getMessage(), e);
    }

    try {
        byte[] dummyContent = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        Signature verifier = Signature.getInstance(signatureAlgoName, "BC");

        OutputStream signatureStream = csigner.getOutputStream();
        signatureStream.write(dummyContent);
        byte[] signatureValue = csigner.getSignature();

        verifier.initVerify(cert.getPublicKey());
        verifier.update(dummyContent);
        boolean valid = verifier.verify(signatureValue);
        if (valid == false) {
            String subject = X509Util.getRFC4519Name(cert.getSubjectX500Principal());

            StringBuilder sb = new StringBuilder();
            sb.append("key and certificate not match. ");
            sb.append("key type='").append(signerType).append("'; ");

            CmpUtf8Pairs keyValues = new CmpUtf8Pairs(signerConf);
            String pwd = keyValues.getValue("password");
            if (pwd != null) {
                keyValues.putUtf8Pair("password", "****");
            }
            keyValues.putUtf8Pair("algo", signatureAlgoName);
            sb.append("conf='").append(keyValues.getEncoded()).append("', ");
            sb.append("certificate subject='").append(subject).append("'");

            throw new SignerException(sb.toString());
        }
    } catch (IOException | NoSuchAlgorithmException | InvalidKeyException | SignatureException
            | NoSuchProviderException e) {
        throw new SignerException(e.getMessage(), e);
    } finally {
        if (csigner != null) {
            signer.returnContentSigner(csigner);
        }
    }
}

From source file:org.xipki.security.test.Pkcs12_RSA_Test.java

License:Open Source License

protected byte[] sign(byte[] data) throws Exception {
    ConcurrentContentSigner signer = getSigner();
    ContentSigner cSigner = signer.borrowContentSigner();
    try {//from   w w  w  .j  a  va2s . c o  m
        OutputStream signatureStream = cSigner.getOutputStream();
        signatureStream.write(data);
        return cSigner.getSignature();
    } finally {
        signer.returnContentSigner(cSigner);
    }
}