Java 类org.bouncycastle.crypto.util.PrivateKeyFactory 实例源码

项目:kafka-0.11.0.0-src-with-comment    文件:TestSslUtils.java   
public X509Certificate generate(String dn, KeyPair keyPair) throws CertificateException {
    try {
        Security.addProvider(new BouncyCastleProvider());
        AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(algorithm);
        AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
        AsymmetricKeyParameter privateKeyAsymKeyParam = PrivateKeyFactory.createKey(keyPair.getPrivate().getEncoded());
        SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
        ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(privateKeyAsymKeyParam);
        X500Name name = new X500Name(dn);
        Date from = new Date();
        Date to = new Date(from.getTime() + days * 86400000L);
        BigInteger sn = new BigInteger(64, new SecureRandom());
        X509v3CertificateBuilder v3CertGen = new X509v3CertificateBuilder(name, sn, from, to, name, subPubKeyInfo);

        if (subjectAltName != null)
            v3CertGen.addExtension(Extension.subjectAlternativeName, false, subjectAltName);
        X509CertificateHolder certificateHolder = v3CertGen.build(sigGen);
        return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certificateHolder);
    } catch (CertificateException ce) {
        throw ce;
    } catch (Exception e) {
        throw new CertificateException(e);
    }
}
项目:likafka-clients    文件:TestSslUtils.java   
/**
 * Create a self-signed X.509 Certificate.
 * From http://bfo.com/blog/2011/03/08/odds_and_ends_creating_a_new_x_509_certificate.html.
 *
 * @param dn        the X.509 Distinguished Name, eg "CN=Test, L=London, C=GB"
 * @param pair      the KeyPair
 * @param days      how many days from now the Certificate is valid for
 * @param algorithm the signing algorithm, eg "SHA1withRSA"
 * @return the self-signed certificate
 * @throws CertificateException thrown if a security error or an IO error occurred.
 */
public static X509Certificate generateCertificate(String dn, KeyPair pair,
                                                  int days, String algorithm)
    throws CertificateException {

  try {
    Security.addProvider(new BouncyCastleProvider());
    AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(algorithm);
    AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
    AsymmetricKeyParameter privateKeyAsymKeyParam = PrivateKeyFactory.createKey(pair.getPrivate().getEncoded());
    SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(pair.getPublic().getEncoded());
    ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(privateKeyAsymKeyParam);
    X500Name name = new X500Name(dn);
    Date from = new Date();
    Date to = new Date(from.getTime() + days * 86400000L);
    BigInteger sn = new BigInteger(64, new SecureRandom());

    X509v1CertificateBuilder v1CertGen = new X509v1CertificateBuilder(name, sn, from, to, name, subPubKeyInfo);
    X509CertificateHolder certificateHolder = v1CertGen.build(sigGen);
    return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certificateHolder);
  } catch (CertificateException ce) {
    throw ce;
  } catch (Exception e) {
    throw new CertificateException(e);
  }
}
项目:kafka    文件:TestSslUtils.java   
/**
 * Create a self-signed X.509 Certificate.
 * From http://bfo.com/blog/2011/03/08/odds_and_ends_creating_a_new_x_509_certificate.html.
 *
 * @param dn the X.509 Distinguished Name, eg "CN=Test, L=London, C=GB"
 * @param pair the KeyPair
 * @param days how many days from now the Certificate is valid for
 * @param algorithm the signing algorithm, eg "SHA1withRSA"
 * @return the self-signed certificate
 * @throws CertificateException thrown if a security error or an IO error occurred.
 */
public static X509Certificate generateCertificate(String dn, KeyPair pair,
                                                  int days, String algorithm)
    throws  CertificateException {

    try {
        Security.addProvider(new BouncyCastleProvider());
        AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(algorithm);
        AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
        AsymmetricKeyParameter privateKeyAsymKeyParam = PrivateKeyFactory.createKey(pair.getPrivate().getEncoded());
        SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(pair.getPublic().getEncoded());
        ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(privateKeyAsymKeyParam);
        X500Name name = new X500Name(dn);
        Date from = new Date();
        Date to = new Date(from.getTime() + days * 86400000L);
        BigInteger sn = new BigInteger(64, new SecureRandom());

        X509v1CertificateBuilder v1CertGen = new X509v1CertificateBuilder(name, sn, from, to, name, subPubKeyInfo);
        X509CertificateHolder certificateHolder = v1CertGen.build(sigGen);
        return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certificateHolder);
    } catch (CertificateException ce) {
        throw ce;
    } catch (Exception e) {
        throw new CertificateException(e);
    }
}
项目:li-apache-kafka-clients    文件:TestSslUtils.java   
/**
 * Create a self-signed X.509 Certificate.
 * From http://bfo.com/blog/2011/03/08/odds_and_ends_creating_a_new_x_509_certificate.html.
 *
 * @param dn        the X.509 Distinguished Name, eg "CN=Test, L=London, C=GB"
 * @param pair      the KeyPair
 * @param days      how many days from now the Certificate is valid for
 * @param algorithm the signing algorithm, eg "SHA1withRSA"
 * @return the self-signed certificate
 * @throws CertificateException thrown if a security error or an IO error occurred.
 */
public static X509Certificate generateCertificate(String dn, KeyPair pair,
                                                  int days, String algorithm)
    throws CertificateException {

  try {
    Security.addProvider(new BouncyCastleProvider());
    AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(algorithm);
    AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
    AsymmetricKeyParameter privateKeyAsymKeyParam = PrivateKeyFactory.createKey(pair.getPrivate().getEncoded());
    SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(pair.getPublic().getEncoded());
    ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(privateKeyAsymKeyParam);
    X500Name name = new X500Name(dn);
    Date from = new Date();
    Date to = new Date(from.getTime() + days * 86400000L);
    BigInteger sn = new BigInteger(64, new SecureRandom());

    X509v1CertificateBuilder v1CertGen = new X509v1CertificateBuilder(name, sn, from, to, name, subPubKeyInfo);
    X509CertificateHolder certificateHolder = v1CertGen.build(sigGen);
    return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certificateHolder);
  } catch (CertificateException ce) {
    throw ce;
  } catch (Exception e) {
    throw new CertificateException(e);
  }
}
项目:android-ssl    文件:KeyUtils.java   
public static PrivateKey readPrivateKey(Reader reader) throws IOException {
    try (PEMParser parser = new PEMParser(reader)) {
        Object object = parser.readObject();
        if (!(object instanceof PEMKeyPair))
            throw new IOException("File does not contain a key");

        PEMKeyPair pair = (PEMKeyPair) object;

        // TODO merge messy conversion logic with that below */
        AsymmetricKeyParameter privateKey = PrivateKeyFactory.createKey(pair.getPrivateKeyInfo());
        PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.createPrivateKeyInfo(privateKey);
        KeyFactory keyFactory = new DefaultJcaJceHelper().createKeyFactory("RSA"); // TODO should we really assume RSA?
        return keyFactory.generatePrivate(new PKCS8EncodedKeySpec(privateKeyInfo.getEncoded()));
    } catch (NoSuchAlgorithmException | InvalidKeySpecException ex) {
        throw new IOException(ex);
    }
}
项目:Oberien    文件:CustomTlsClient.java   
@Override
public TlsAuthentication getAuthentication() throws IOException {
    return new TlsAuthentication() {
        public void notifyServerCertificate(Certificate serverCertificate) throws IOException {
            System.out.println("notify server certificate");
            byte[] encoded = serverCertificate.getCertificateList()[0].getEncoded();
            if(!Arrays.equals(encoded, SERVER_CERT)) {
                throw new IllegalArgumentException("Server cert is not valid! Do you even MITM?");
            }
        }

        public TlsCredentials getClientCredentials(CertificateRequest certificateRequest) throws IOException {
            System.out.println("get client credentials");
            return new DefaultTlsSignerCredentials(context, clientCert, PrivateKeyFactory.createKey(clientKeyPair.getPrivate().getEncoded()), new SignatureAndHashAlgorithm(HashAlgorithm.sha256, SignatureAlgorithm.ecdsa)) {
                public DefaultTlsSignerCredentials fixThisFuckingRetardedLibrary() {
                    this.signer = new CustomECDSASigner();
                    this.signer.init(context);
                    return this;
                }
            }.fixThisFuckingRetardedLibrary();
        }
    };
}
项目:irma_future_id    文件:TlsTestUtils.java   
static AsymmetricKeyParameter loadPrivateKeyResource(String resource)
    throws IOException
{

    PemObject pem = loadPemResource(resource);
    if (pem.getType().endsWith("RSA PRIVATE KEY"))
    {
        RSAPrivateKey rsa = RSAPrivateKey.getInstance(pem.getContent());
        return new RSAPrivateCrtKeyParameters(rsa.getModulus(), rsa.getPublicExponent(),
            rsa.getPrivateExponent(), rsa.getPrime1(), rsa.getPrime2(), rsa.getExponent1(),
            rsa.getExponent2(), rsa.getCoefficient());
    }
    if (pem.getType().endsWith("PRIVATE KEY"))
    {
        return PrivateKeyFactory.createKey(pem.getContent());
    }
    throw new IllegalArgumentException("'resource' doesn't specify a valid private key");
}
项目:bc-java    文件:TlsTestUtils.java   
static AsymmetricKeyParameter loadPrivateKeyResource(String resource)
    throws IOException
{

    PemObject pem = loadPemResource(resource);
    if (pem.getType().endsWith("RSA PRIVATE KEY"))
    {
        RSAPrivateKey rsa = RSAPrivateKey.getInstance(pem.getContent());
        return new RSAPrivateCrtKeyParameters(rsa.getModulus(), rsa.getPublicExponent(),
            rsa.getPrivateExponent(), rsa.getPrime1(), rsa.getPrime2(), rsa.getExponent1(),
            rsa.getExponent2(), rsa.getCoefficient());
    }
    if (pem.getType().endsWith("PRIVATE KEY"))
    {
        return PrivateKeyFactory.createKey(pem.getContent());
    }
    throw new IllegalArgumentException("'resource' doesn't specify a valid private key");
}
项目:ambry    文件:TestSSLUtils.java   
/**
 * Create a self-signed X.509 Certificate.
 * From http://bfo.com/blog/2011/03/08/odds_and_ends_creating_a_new_x_509_certificate.html.
 *
 * @param dn the X.509 Distinguished Name, eg "CN(commonName)=Test, O(organizationName)=Org"
 * @param pair the KeyPair
 * @param days how many days from now the Certificate is valid for
 * @param algorithm the signing algorithm, eg "SHA1withRSA"
 * @return the self-signed certificate
 * @throws java.security.cert.CertificateException thrown if a security error or an IO error ocurred.
 */
public static X509Certificate generateCertificate(String dn, KeyPair pair, int days, String algorithm)
    throws CertificateException {
  try {
    Security.addProvider(new BouncyCastleProvider());
    AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(algorithm);
    AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
    AsymmetricKeyParameter privateKeyAsymKeyParam = PrivateKeyFactory.createKey(pair.getPrivate().getEncoded());
    SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(pair.getPublic().getEncoded());
    ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(privateKeyAsymKeyParam);
    X500Name name = new X500Name(dn);
    Date from = new Date();
    Date to = new Date(from.getTime() + days * 86400000L);
    BigInteger sn = new BigInteger(64, new SecureRandom());

    X509v1CertificateBuilder v1CertGen = new X509v1CertificateBuilder(name, sn, from, to, name, subPubKeyInfo);
    X509CertificateHolder certificateHolder = v1CertGen.build(sigGen);
    return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certificateHolder);
  } catch (CertificateException ce) {
    throw ce;
  } catch (Exception e) {
    throw new CertificateException(e);
  }
}
项目:rtcdcjava    文件:DTLSTransportFactory.java   
static DTLSTransport createServerTransport(final RTCCertificate rtcCertificate,
                                           final DatagramTransport transport) throws IOException {

    final DefaultTlsServer defaultTlsServer = new DefaultTlsServer() {

        private final AsymmetricKeyParameter privateKeyAsymKeyParam = PrivateKeyFactory.createKey(rtcCertificate.getKeyPair()
                                                                                                                .getPrivate()
                                                                                                                .getEncoded());
        private final Certificate cCert = new Certificate(new org.bouncycastle.asn1.x509.Certificate[]{rtcCertificate.getCertificate().toASN1Structure()});

        @Override
        protected ProtocolVersion getMaximumVersion() {
            return ProtocolVersion.DTLSv10;
        }

        @Override
        protected ProtocolVersion getMinimumVersion() {
            return ProtocolVersion.DTLSv10;
        }

        @Override
        protected TlsSignerCredentials getRSASignerCredentials() throws IOException {
            return new DefaultTlsSignerCredentials(this.context,
                                                   this.cCert,
                                                   this.privateKeyAsymKeyParam);
        }
    };

    return new DTLSServerProtocol(SECURE_RANDOM).accept(defaultTlsServer,
                                                        transport);
}
项目:dremio-oss    文件:ElasticsearchCluster.java   
private static ContentSigner newSigner(PrivateKey privateKey, String algo) {
    try {
        AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(algo);
        AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);

        return new BcRSAContentSignerBuilder(sigAlgId, digAlgId)
                .build(PrivateKeyFactory.createKey(privateKey.getEncoded()));
    } catch (OperatorCreationException | IOException e) {
        throw new RuntimeException(e);
    }
}
项目:fabric-java    文件:Crypto.java   
public BigInteger[] ecdsaSign(PrivateKey privateKey, ByteString message) {
    ECDSASigner signer = new ECDSASigner(new HMacDSAKCalculator(digest));
    ECPrivateKeyParameters ecdhPrivateKeyParameters;
    try {
        ecdhPrivateKeyParameters = (ECPrivateKeyParameters) (PrivateKeyFactory.createKey(privateKey.getEncoded()));
    } catch (IOException e) {
        logger.error("ECDSA sign load private key exception", e);
        throw new RuntimeException(e);
    }
    signer.init(true, ecdhPrivateKeyParameters);
    return signer.generateSignature(message.toByteArray());
}
项目:testarea-pdfbox2    文件:CreateSignature.java   
/**
 * <a href="http://stackoverflow.com/questions/41767351/create-pkcs7-signature-from-file-digest">
 * Create pkcs7 signature from file digest
 * </a>
 * <p>
 * The OP's <code>sign</code> method after fixing some errors. The
 * OP's original method is {@link #signBySnox(InputStream)}. The
 * errors were
 * </p>
 * <ul>
 * <li>multiple attempts at reading the {@link InputStream} parameter;
 * <li>convoluted creation of final CMS container.
 * </ul>
 * <p>
 * Additionally this method uses SHA256 instead of SHA-1.
 * </p>
 */
public byte[] signWithSeparatedHashing(InputStream content) throws IOException
{
    try
    {
        // Digest generation step
        MessageDigest md = MessageDigest.getInstance("SHA256", "BC");
        byte[] digest = md.digest(IOUtils.toByteArray(content));

        // Separate signature container creation step
        List<Certificate> certList = Arrays.asList(chain);
        JcaCertStore certs = new JcaCertStore(certList);

        CMSSignedDataGenerator gen = new CMSSignedDataGenerator();

        Attribute attr = new Attribute(CMSAttributes.messageDigest,
                new DERSet(new DEROctetString(digest)));

        ASN1EncodableVector v = new ASN1EncodableVector();

        v.add(attr);

        SignerInfoGeneratorBuilder builder = new SignerInfoGeneratorBuilder(new BcDigestCalculatorProvider())
                .setSignedAttributeGenerator(new DefaultSignedAttributeTableGenerator(new AttributeTable(v)));

        AlgorithmIdentifier sha256withRSA = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA256withRSA");

        CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
        InputStream in = new ByteArrayInputStream(chain[0].getEncoded());
        X509Certificate cert = (X509Certificate) certFactory.generateCertificate(in);

        gen.addSignerInfoGenerator(builder.build(
                new BcRSAContentSignerBuilder(sha256withRSA,
                        new DefaultDigestAlgorithmIdentifierFinder().find(sha256withRSA))
                                .build(PrivateKeyFactory.createKey(pk.getEncoded())),
                new JcaX509CertificateHolder(cert)));

        gen.addCertificates(certs);

        CMSSignedData s = gen.generate(new CMSAbsentContent(), false);
        return s.getEncoded();
    }
    catch (Exception e)
    {
        e.printStackTrace();
        throw new IOException(e);
    }
}
项目:Proxy    文件:CryptoTest.java   
public static void main( String[] args ) throws InvalidKeySpecException, InvalidKeyException, IOException {
    ECPublicKey clientKey = (ECPublicKey) ECDH_KEY_FACTORY.generatePublic( new X509EncodedKeySpec( Base64.getDecoder().decode( "MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEDEKneqEvcqUqqFMM1HM1A4zWjJC+I8Y+aKzG5dl+6wNOHHQ4NmG2PEXRJYhujyodFH+wO0dEr4GM1WoaWog8xsYQ6mQJAC0eVpBM96spUB1eMN56+BwlJ4H3Qx4TAvAs" ) ) );
    ECPrivateKey privateKey = (ECPrivateKey) ECDH_KEY_FACTORY.generatePrivate( new PKCS8EncodedKeySpec( Base64.getDecoder().decode( "MB8CAQAwEAYHKoZIzj0CAQYFK4EEACIECDAGAgEBBAEB" ) ) );

    ECDHBasicAgreement agreement = new ECDHBasicAgreement();
    agreement.init( PrivateKeyFactory.createKey( privateKey.getEncoded() ) );
    byte[] secret = agreement.calculateAgreement( PublicKeyFactory.createKey( clientKey.getEncoded() ) ).toByteArray();

    System.out.println( Util.toHexString( secret ) );
    System.out.println( Util.toHexString( Base64.getDecoder().decode( "DEKneqEvcqUqqFMM1HM1A4zWjJC+I8Y+aKzG5dl+6wNOHHQ4NmG2PEXRJYhujyod" ) ) );
}
项目:cert-services    文件:CertificateService.java   
private ContentSigner generateContentSignerBuilder(PrivateKey issuerPrivateKey) throws OperatorCreationException, IOException {
    AsymmetricKeyParameter privateKeyParam = PrivateKeyFactory.createKey(issuerPrivateKey.getEncoded());

    AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(SIG_HASH_ALG);
    AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);

    return new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(privateKeyParam);
}
项目:vertx-config    文件:Certificates.java   
/**
 * See http://www.programcreek.com/java-api-examples/index.php?api=org.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder
 *
 * @param keyPair The RSA keypair with which to generate the certificate
 * @param issuer  The issuer (and subject) to use for the certificate
 * @return An X509 certificate
 * @throws IOException
 * @throws OperatorCreationException
 * @throws CertificateException
 * @throws NoSuchProviderException
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException
 * @throws SignatureException
 */
private static X509Certificate generateCert(final KeyPair keyPair, final String issuer) throws IOException, OperatorCreationException,
  CertificateException, NoSuchProviderException, NoSuchAlgorithmException, InvalidKeyException,
  SignatureException {
  final String subject = issuer;
  final X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder(
    new X500Name(issuer),
    BigInteger.ONE,
    new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30),
    new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 30)),
    new X500Name(subject),
    SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded())
  );

  final GeneralNames subjectAltNames = new GeneralNames(new GeneralName(GeneralName.iPAddress, "127.0.0.1"));
  certificateBuilder.addExtension(org.bouncycastle.asn1.x509.Extension.subjectAlternativeName, false, subjectAltNames);

  final AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1WithRSAEncryption");
  final AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
  final BcContentSignerBuilder signerBuilder = new BcRSAContentSignerBuilder(sigAlgId, digAlgId);
  final AsymmetricKeyParameter keyp = PrivateKeyFactory.createKey(keyPair.getPrivate().getEncoded());
  final ContentSigner signer = signerBuilder.build(keyp);
  final X509CertificateHolder x509CertificateHolder = certificateBuilder.build(signer);

  final X509Certificate certificate = new JcaX509CertificateConverter()
    .getCertificate(x509CertificateHolder);
  certificate.checkValidity(new Date());
  certificate.verify(keyPair.getPublic());
  return certificate;
}
项目:mazebert-ladder    文件:ContentSigner.java   
private RSAKeyParameters parseKey(String key) {
    try (InputStreamReader reader = new InputStreamReader(a(inputStream().withString(key)))) {
        PEMParser parser = new PEMParser(reader);
        PEMKeyPair keyPair = (PEMKeyPair)parser.readObject();
        return (RSAKeyParameters) PrivateKeyFactory.createKey(keyPair.getPrivateKeyInfo());
    } catch (Throwable e) {
        throw new InternalServerError("Failed to parse private key for content signing.", e);
    }
}
项目:mycarenet    文件:CMSSignerTest.java   
public static X509Certificate generateCertificate(KeyPair keyPair, String distinguishedName) throws Exception {
    X500Name issuerX500Name = new X500Name(distinguishedName);
    X500Name subjectX500Name = new X500Name(distinguishedName);

    SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());

    SecureRandom secureRandom = new SecureRandom();
    byte[] serialValue = new byte[8];
    secureRandom.nextBytes(serialValue);
    BigInteger serial = new BigInteger(serialValue);

    DateTime notBefore = new DateTime();
    DateTime notAfter = notBefore.plusMonths(1);

    X509v3CertificateBuilder x509v3CertificateBuilder = new X509v3CertificateBuilder(issuerX500Name, serial,
            notBefore.toDate(), notAfter.toDate(), subjectX500Name, publicKeyInfo);

    AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1withRSA");
    AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
    AsymmetricKeyParameter asymmetricKeyParameter = PrivateKeyFactory.createKey(keyPair.getPrivate().getEncoded());
    ContentSigner contentSigner = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(asymmetricKeyParameter);
    X509CertificateHolder x509CertificateHolder = x509v3CertificateBuilder.build(contentSigner);

    byte[] encodedCertificate = x509CertificateHolder.getEncoded();

    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    X509Certificate certificate = (X509Certificate) certificateFactory
            .generateCertificate(new ByteArrayInputStream(encodedCertificate));
    return certificate;
}
项目:dssp    文件:TestUtils.java   
public static X509Certificate generateCertificate(KeyPair keyPair, String distinguishedName) throws Exception {
    X500Name issuerX500Name = new X500Name(distinguishedName);
    X500Name subjectX500Name = new X500Name(distinguishedName);

    SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());

    SecureRandom secureRandom = new SecureRandom();
    byte[] serialValue = new byte[8];
    secureRandom.nextBytes(serialValue);
    BigInteger serial = new BigInteger(serialValue);

    DateTime notBefore = new DateTime();
    DateTime notAfter = notBefore.plusMonths(1);

    X509v3CertificateBuilder x509v3CertificateBuilder = new X509v3CertificateBuilder(issuerX500Name, serial,
            notBefore.toDate(), notAfter.toDate(), subjectX500Name, publicKeyInfo);

    AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1withRSA");
    AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
    AsymmetricKeyParameter asymmetricKeyParameter = PrivateKeyFactory.createKey(keyPair.getPrivate().getEncoded());
    ContentSigner contentSigner = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(asymmetricKeyParameter);
    X509CertificateHolder x509CertificateHolder = x509v3CertificateBuilder.build(contentSigner);

    byte[] encodedCertificate = x509CertificateHolder.getEncoded();

    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    X509Certificate certificate = (X509Certificate) certificateFactory
            .generateCertificate(new ByteArrayInputStream(encodedCertificate));
    return certificate;
}
项目:airavata    文件:MyProxyLogon.java   
private PKCS10CertificationRequest generateCertificationRequest(String dn, KeyPair kp)
        throws Exception{
    X500Name subject=new X500Name(dn);
    PublicKey pubKey=kp.getPublic();
    PrivateKey privKey=kp.getPrivate();
    AsymmetricKeyParameter pubkeyParam = PublicKeyFactory.createKey(pubKey.getEncoded());
    SubjectPublicKeyInfo publicKeyInfo=SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(pubkeyParam);
    PKCS10CertificationRequestBuilder builder=new PKCS10CertificationRequestBuilder(subject, publicKeyInfo);
    AlgorithmIdentifier signatureAi = new AlgorithmIdentifier(OIWObjectIdentifiers.sha1WithRSA);
    BcRSAContentSignerBuilder signerBuilder=new BcRSAContentSignerBuilder(
            signatureAi, AlgorithmIdentifier.getInstance(OIWObjectIdentifiers.idSHA1));
    AsymmetricKeyParameter pkParam = PrivateKeyFactory.createKey(privKey.getEncoded());
    ContentSigner signer=signerBuilder.build(pkParam);
    return builder.build(signer);
}
项目:airavata    文件:MyProxyLogon.java   
private org.bouncycastle.pkcs.PKCS10CertificationRequest generateCertificationRequest(String dn, KeyPair kp)
        throws Exception{
    X500Name subject=new X500Name(dn);
    PublicKey pubKey=kp.getPublic();
    PrivateKey privKey=kp.getPrivate();
    AsymmetricKeyParameter pubkeyParam = PublicKeyFactory.createKey(pubKey.getEncoded());
    SubjectPublicKeyInfo publicKeyInfo=SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(pubkeyParam);
    PKCS10CertificationRequestBuilder builder=new PKCS10CertificationRequestBuilder(subject, publicKeyInfo);
    AlgorithmIdentifier signatureAi = new AlgorithmIdentifier(OIWObjectIdentifiers.sha1WithRSA);
    BcRSAContentSignerBuilder signerBuilder=new BcRSAContentSignerBuilder(
            signatureAi, AlgorithmIdentifier.getInstance(OIWObjectIdentifiers.idSHA1));
    AsymmetricKeyParameter pkParam = PrivateKeyFactory.createKey(privKey.getEncoded());
    ContentSigner signer=signerBuilder.build(pkParam);
    return builder.build(signer);
}
项目:cloudbreak    文件:PkiUtil.java   
private static X509Certificate selfsign(PKCS10CertificationRequest inputCSR, String publicAddress, KeyPair signKey)
        throws Exception {

    AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder()
            .find("SHA256withRSA");
    AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder()
            .find(sigAlgId);

    AsymmetricKeyParameter akp = PrivateKeyFactory.createKey(signKey.getPrivate()
            .getEncoded());

    Calendar cal = Calendar.getInstance();
    Date currentTime = cal.getTime();
    cal.add(Calendar.YEAR, CERT_VALIDITY_YEAR);
    Date expiryTime = cal.getTime();

    X509v3CertificateBuilder myCertificateGenerator = new X509v3CertificateBuilder(
            new X500Name(String.format("cn=%s", publicAddress)), new BigInteger("1"), currentTime, expiryTime, inputCSR.getSubject(),
            inputCSR.getSubjectPublicKeyInfo());

    ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId)
            .build(akp);

    X509CertificateHolder holder = myCertificateGenerator.build(sigGen);

    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    return (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(holder.toASN1Structure().getEncoded()));
}
项目:irma_future_id    文件:BcEnvelopedDataTest.java   
public void testKeyTrans128RC4()
    throws Exception
{
    byte[]          data     = "WallaWallaBouncyCastle".getBytes();

    CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator();

    edGen.addRecipientInfoGenerator(new BcRSAKeyTransRecipientInfoGenerator(new JcaX509CertificateHolder(_reciCert)));

    CMSEnvelopedData ed = edGen.generate(
                            new CMSProcessableByteArray(data),
                            new BcCMSContentEncryptorBuilder(new ASN1ObjectIdentifier("1.2.840.113549.3.4"), 128).build());

    RecipientInformationStore  recipients = ed.getRecipientInfos();

    assertEquals(ed.getEncryptionAlgOID(), "1.2.840.113549.3.4");

    Collection c = recipients.getRecipients();
    Iterator it = c.iterator();

    if (it.hasNext())
    {
        RecipientInformation   recipient = (RecipientInformation)it.next();

        byte[] recData = recipient.getContent(new BcRSAKeyTransEnvelopedRecipient(PrivateKeyFactory.createKey(PrivateKeyInfo.getInstance(_reciKP.getPrivate().getEncoded()))));

        assertEquals(true, Arrays.equals(data, recData));
    }
    else
    {
        fail("no recipient found");
    }
}
项目:irma_future_id    文件:BcEnvelopedDataTest.java   
public void testKeyTransLight128RC4()
    throws Exception
{
    byte[]          data     = "WallaWallaBouncyCastle".getBytes();

    CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator();

    edGen.addRecipientInfoGenerator(new BcRSAKeyTransRecipientInfoGenerator(new JcaX509CertificateHolder(_reciCert)));

    CMSEnvelopedData ed = edGen.generate(
                            new CMSProcessableByteArray(data),
                            new BcCMSContentEncryptorBuilder(new ASN1ObjectIdentifier("1.2.840.113549.3.4"), 128).build());

    RecipientInformationStore  recipients = ed.getRecipientInfos();

    assertEquals(ed.getEncryptionAlgOID(), "1.2.840.113549.3.4");

    Collection c = recipients.getRecipients();
    Iterator it = c.iterator();

    if (it.hasNext())
    {
        RecipientInformation   recipient = (RecipientInformation)it.next();

        byte[] recData = recipient.getContent(new BcRSAKeyTransEnvelopedRecipient(PrivateKeyFactory.createKey(PrivateKeyInfo.getInstance(_reciKP.getPrivate().getEncoded()))));

        assertEquals(true, Arrays.equals(data, recData));
    }
    else
    {
        fail("no recipient found");
    }
}
项目:irma_future_id    文件:BcEnvelopedDataTest.java   
public void testKeyTransODES()
    throws Exception
{
    byte[]          data     = "WallaWallaBouncyCastle".getBytes();

    CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator();

    edGen.addRecipientInfoGenerator(new BcRSAKeyTransRecipientInfoGenerator(new JcaX509CertificateHolder(_reciCert)));

    CMSEnvelopedData ed = edGen.generate(
        new CMSProcessableByteArray(data),
        new BcCMSContentEncryptorBuilder(new ASN1ObjectIdentifier("1.3.14.3.2.7")).build());

    RecipientInformationStore  recipients = ed.getRecipientInfos();

    assertEquals(ed.getEncryptionAlgOID(), "1.3.14.3.2.7");

    Collection c = recipients.getRecipients();
    Iterator it = c.iterator();

    if (it.hasNext())
    {
        RecipientInformation   recipient = (RecipientInformation)it.next();

        byte[] recData = recipient.getContent(new BcRSAKeyTransEnvelopedRecipient(PrivateKeyFactory.createKey(PrivateKeyInfo.getInstance(_reciKP.getPrivate().getEncoded()))));

        assertEquals(true, Arrays.equals(data, recData));
    }
    else
    {
        fail("no recipient found");
    }
}
项目:irma_future_id    文件:BcEnvelopedDataTest.java   
public void testKeyTransSmallAES()
    throws Exception
{
    byte[]          data     = new byte[] { 0, 1, 2, 3 };

    CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator();

    edGen.addRecipientInfoGenerator(new BcRSAKeyTransRecipientInfoGenerator(new JcaX509CertificateHolder(_reciCert)));

    CMSEnvelopedData ed = edGen.generate(
                          new CMSProcessableByteArray(data),
                          new BcCMSContentEncryptorBuilder(CMSAlgorithm.AES128_CBC).build());

    RecipientInformationStore  recipients = ed.getRecipientInfos();

    assertEquals(ed.getEncryptionAlgOID(),
                               CMSAlgorithm.AES128_CBC.getId());

    Collection c = recipients.getRecipients();
    Iterator it = c.iterator();

    if (it.hasNext())
    {
        RecipientInformation   recipient = (RecipientInformation)it.next();

        byte[] recData = recipient.getContent(new BcRSAKeyTransEnvelopedRecipient(PrivateKeyFactory.createKey(PrivateKeyInfo.getInstance(_reciKP.getPrivate().getEncoded()))));
        assertEquals(true, Arrays.equals(data, recData));
    }
    else
    {
        fail("no recipient found");
    }
}
项目:irma_future_id    文件:BcEnvelopedDataTest.java   
public void testRFC4134ex5_1()
    throws Exception
{
    byte[] data = Hex.decode("5468697320697320736f6d652073616d706c6520636f6e74656e742e");

    KeyFactory kFact = KeyFactory.getInstance("RSA", BC);
    Key key = kFact.generatePrivate(new PKCS8EncodedKeySpec(bobPrivRsaEncrypt));

    CMSEnvelopedData ed = new CMSEnvelopedData(rfc4134ex5_1);

    RecipientInformationStore  recipients = ed.getRecipientInfos();

    assertEquals("1.2.840.113549.3.7", ed.getEncryptionAlgOID());

    Collection c = recipients.getRecipients();
    Iterator it = c.iterator();

    if (it.hasNext())
    {
        RecipientInformation   recipient = (RecipientInformation)it.next();

        byte[] recData = recipient.getContent(new BcRSAKeyTransEnvelopedRecipient(PrivateKeyFactory.createKey(PrivateKeyInfo.getInstance(key.getEncoded()))));

        assertEquals(true, Arrays.equals(data, recData));
    }
    else
    {
        fail("no recipient found");
    }
}
项目:irma_future_id    文件:BcEnvelopedDataTest.java   
public void testRFC4134ex5_2()
    throws Exception
{
    byte[] data = Hex.decode("5468697320697320736f6d652073616d706c6520636f6e74656e742e");

    KeyFactory kFact = KeyFactory.getInstance("RSA", BC);
    PrivateKey key = kFact.generatePrivate(new PKCS8EncodedKeySpec(bobPrivRsaEncrypt));

    CMSEnvelopedData ed = new CMSEnvelopedData(rfc4134ex5_2);

    RecipientInformationStore  recipients = ed.getRecipientInfos();

    assertEquals("1.2.840.113549.3.2", ed.getEncryptionAlgOID());

    Collection c = recipients.getRecipients();
    Iterator it = c.iterator();

    if (it.hasNext())
    {
        while (it.hasNext())
        {
            RecipientInformation   recipient = (RecipientInformation)it.next();
            byte[] recData;

            if (recipient instanceof KeyTransRecipientInformation)
            {
                recData = recipient.getContent(new BcRSAKeyTransEnvelopedRecipient(PrivateKeyFactory.createKey(PrivateKeyInfo.getInstance(key.getEncoded()))));

                assertEquals(true, Arrays.equals(data, recData));
            }
        }
    }
    else
    {
        fail("no recipient found");
    }
}
项目:bc-java    文件:BcEnvelopedDataTest.java   
public void testKeyTrans128RC4()
    throws Exception
{
    byte[]          data     = "WallaWallaBouncyCastle".getBytes();

    CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator();

    edGen.addRecipientInfoGenerator(new BcRSAKeyTransRecipientInfoGenerator(new JcaX509CertificateHolder(_reciCert)));

    CMSEnvelopedData ed = edGen.generate(
                            new CMSProcessableByteArray(data),
                            new BcCMSContentEncryptorBuilder(new ASN1ObjectIdentifier("1.2.840.113549.3.4"), 128).build());

    RecipientInformationStore  recipients = ed.getRecipientInfos();

    assertEquals(ed.getEncryptionAlgOID(), "1.2.840.113549.3.4");

    Collection c = recipients.getRecipients();
    Iterator it = c.iterator();

    if (it.hasNext())
    {
        RecipientInformation   recipient = (RecipientInformation)it.next();

        byte[] recData = recipient.getContent(new BcRSAKeyTransEnvelopedRecipient(PrivateKeyFactory.createKey(PrivateKeyInfo.getInstance(_reciKP.getPrivate().getEncoded()))));

        assertEquals(true, Arrays.equals(data, recData));
    }
    else
    {
        fail("no recipient found");
    }
}
项目:bc-java    文件:BcEnvelopedDataTest.java   
public void testKeyTransLight128RC4()
    throws Exception
{
    byte[]          data     = "WallaWallaBouncyCastle".getBytes();

    CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator();

    edGen.addRecipientInfoGenerator(new BcRSAKeyTransRecipientInfoGenerator(new JcaX509CertificateHolder(_reciCert)));

    CMSEnvelopedData ed = edGen.generate(
                            new CMSProcessableByteArray(data),
                            new BcCMSContentEncryptorBuilder(new ASN1ObjectIdentifier("1.2.840.113549.3.4"), 128).build());

    RecipientInformationStore  recipients = ed.getRecipientInfos();

    assertEquals(ed.getEncryptionAlgOID(), "1.2.840.113549.3.4");

    Collection c = recipients.getRecipients();
    Iterator it = c.iterator();

    if (it.hasNext())
    {
        RecipientInformation   recipient = (RecipientInformation)it.next();

        byte[] recData = recipient.getContent(new BcRSAKeyTransEnvelopedRecipient(PrivateKeyFactory.createKey(PrivateKeyInfo.getInstance(_reciKP.getPrivate().getEncoded()))));

        assertEquals(true, Arrays.equals(data, recData));
    }
    else
    {
        fail("no recipient found");
    }
}
项目:bc-java    文件:BcEnvelopedDataTest.java   
public void testKeyTransODES()
    throws Exception
{
    byte[]          data     = "WallaWallaBouncyCastle".getBytes();

    CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator();

    edGen.addRecipientInfoGenerator(new BcRSAKeyTransRecipientInfoGenerator(new JcaX509CertificateHolder(_reciCert)));

    CMSEnvelopedData ed = edGen.generate(
        new CMSProcessableByteArray(data),
        new BcCMSContentEncryptorBuilder(new ASN1ObjectIdentifier("1.3.14.3.2.7")).build());

    RecipientInformationStore  recipients = ed.getRecipientInfos();

    assertEquals(ed.getEncryptionAlgOID(), "1.3.14.3.2.7");

    Collection c = recipients.getRecipients();
    Iterator it = c.iterator();

    if (it.hasNext())
    {
        RecipientInformation   recipient = (RecipientInformation)it.next();

        byte[] recData = recipient.getContent(new BcRSAKeyTransEnvelopedRecipient(PrivateKeyFactory.createKey(PrivateKeyInfo.getInstance(_reciKP.getPrivate().getEncoded()))));

        assertEquals(true, Arrays.equals(data, recData));
    }
    else
    {
        fail("no recipient found");
    }
}
项目:bc-java    文件:BcEnvelopedDataTest.java   
public void testKeyTransSmallAES()
    throws Exception
{
    byte[]          data     = new byte[] { 0, 1, 2, 3 };

    CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator();

    edGen.addRecipientInfoGenerator(new BcRSAKeyTransRecipientInfoGenerator(new JcaX509CertificateHolder(_reciCert)));

    CMSEnvelopedData ed = edGen.generate(
                          new CMSProcessableByteArray(data),
                          new BcCMSContentEncryptorBuilder(CMSAlgorithm.AES128_CBC).build());

    RecipientInformationStore  recipients = ed.getRecipientInfos();

    assertEquals(ed.getEncryptionAlgOID(),
                               CMSAlgorithm.AES128_CBC.getId());

    Collection c = recipients.getRecipients();
    Iterator it = c.iterator();

    if (it.hasNext())
    {
        RecipientInformation   recipient = (RecipientInformation)it.next();

        byte[] recData = recipient.getContent(new BcRSAKeyTransEnvelopedRecipient(PrivateKeyFactory.createKey(PrivateKeyInfo.getInstance(_reciKP.getPrivate().getEncoded()))));
        assertEquals(true, Arrays.equals(data, recData));
    }
    else
    {
        fail("no recipient found");
    }
}
项目:bc-java    文件:BcEnvelopedDataTest.java   
public void testRFC4134ex5_1()
    throws Exception
{
    byte[] data = Hex.decode("5468697320697320736f6d652073616d706c6520636f6e74656e742e");

    KeyFactory kFact = KeyFactory.getInstance("RSA", BC);
    Key key = kFact.generatePrivate(new PKCS8EncodedKeySpec(bobPrivRsaEncrypt));

    CMSEnvelopedData ed = new CMSEnvelopedData(rfc4134ex5_1);

    RecipientInformationStore  recipients = ed.getRecipientInfos();

    assertEquals("1.2.840.113549.3.7", ed.getEncryptionAlgOID());

    Collection c = recipients.getRecipients();
    Iterator it = c.iterator();

    if (it.hasNext())
    {
        RecipientInformation   recipient = (RecipientInformation)it.next();

        byte[] recData = recipient.getContent(new BcRSAKeyTransEnvelopedRecipient(PrivateKeyFactory.createKey(PrivateKeyInfo.getInstance(key.getEncoded()))));

        assertEquals(true, Arrays.equals(data, recData));
    }
    else
    {
        fail("no recipient found");
    }
}
项目:bc-java    文件:BcEnvelopedDataTest.java   
public void testRFC4134ex5_2()
    throws Exception
{
    byte[] data = Hex.decode("5468697320697320736f6d652073616d706c6520636f6e74656e742e");

    KeyFactory kFact = KeyFactory.getInstance("RSA", BC);
    PrivateKey key = kFact.generatePrivate(new PKCS8EncodedKeySpec(bobPrivRsaEncrypt));

    CMSEnvelopedData ed = new CMSEnvelopedData(rfc4134ex5_2);

    RecipientInformationStore  recipients = ed.getRecipientInfos();

    assertEquals("1.2.840.113549.3.2", ed.getEncryptionAlgOID());

    Collection c = recipients.getRecipients();
    Iterator it = c.iterator();

    if (it.hasNext())
    {
        while (it.hasNext())
        {
            RecipientInformation   recipient = (RecipientInformation)it.next();
            byte[] recData;

            if (recipient instanceof KeyTransRecipientInformation)
            {
                recData = recipient.getContent(new BcRSAKeyTransEnvelopedRecipient(PrivateKeyFactory.createKey(PrivateKeyInfo.getInstance(key.getEncoded()))));

                assertEquals(true, Arrays.equals(data, recData));
            }
        }
    }
    else
    {
        fail("no recipient found");
    }
}
项目:rtcdcjava    文件:RTCCertificate.java   
public static RTCCertificate generate(String commonName) {

        try {
            //generate certificate
            //TODO sign it by lets-encrypt
            KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA",
                                                                BouncyCastleProvider.PROVIDER_NAME);
            kpg.initialize(1024);

            KeyPair    keyPair      = kpg.genKeyPair();
            Date       startDate    = new Date(System.currentTimeMillis());// time from which certificate is valid
            Date       expiryDate   = new Date(System.currentTimeMillis() + 365L * 24L * 60L * 60L * 1000L);// time after which certificate is not valid
            BigInteger serialNumber = new BigInteger("1");// serial number for certificate
            X500Name   dnName       = new X500Name("CN=" + commonName);
            SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic()
                                                                                         .getEncoded());


            final X509v1CertificateBuilder x509v1CertificateBuilder = new X509v1CertificateBuilder(dnName,
                                                                                                   serialNumber,
                                                                                                   startDate,
                                                                                                   expiryDate,
                                                                                                   dnName,
                                                                                                   subPubKeyInfo);

            AsymmetricKeyParameter privateKeyAsymKeyParam = PrivateKeyFactory.createKey(keyPair.getPrivate()
                                                                                               .getEncoded());
            AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA256withRSA");
            AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
            ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId,
                                                                 digAlgId).build(privateKeyAsymKeyParam);

            final X509CertificateHolder x509CertificateHolder = x509v1CertificateBuilder.build(sigGen);

            return new RTCCertificate(fingerprint(x509CertificateHolder),
                                      keyPair,
                                      x509CertificateHolder);
        }
        catch (IOException | CertificateException | NoSuchAlgorithmException | NoSuchProviderException | OperatorCreationException e) {
            throw new RuntimeException(e);
        }
    }
项目:fabric-java    文件:Crypto.java   
public ByteString eciesDecrypt(PrivateKey recipientPrivateKey, ByteString cipherText) {
    BCECPrivateKey bcecPrivateKey = (BCECPrivateKey) recipientPrivateKey;
    ECNamedCurveSpec ecNamedCurveSpec = (ECNamedCurveSpec) bcecPrivateKey.getParams();
    int level = SecurityLevel.from(ecNamedCurveSpec.getName()).size();

    //cipherText = ephemeralPubKeyBytes + encryptedTokBytes + macBytes
    //ephemeralPubKeyBytes = first ((384+7)/8)*2 + 1 bytes = first 97 bytes
    //hmac is sha3_384 = 48 bytes or sha3_256 = 32 bytes
    int ephemeralPubKeyLength = ((level + 7) / 8) * 2 + 1;
    int hmacLength = level >> 3;
    int cipherTextLength = cipherText.size();

    if (cipherTextLength <= ephemeralPubKeyLength + hmacLength)
        throw new RuntimeException(String.format("Illegal cipherText length: %d must be > %d", cipherTextLength, ephemeralPubKeyLength + hmacLength));

    ByteString ephemeralPubKey = cipherText.substring(0, ephemeralPubKeyLength);
    ByteString encryptedContent = cipherText.substring(ephemeralPubKeyLength, cipherTextLength - hmacLength);
    ByteString hmac = cipherText.substring(cipherTextLength - hmacLength);

    ECPrivateKeyParameters ecdhPrivateKeyParameters;
    try {
        ecdhPrivateKeyParameters = (ECPrivateKeyParameters) (PrivateKeyFactory.createKey(bcecPrivateKey.getEncoded()));
    } catch (IOException e) {
        logger.error("ECIES decrypt load private key exception", e);
        throw new RuntimeException(e);
    }
    ECDomainParameters ecDomainParameters = ecdhPrivateKeyParameters.getParameters();
    ECCurve ecCurve = ecDomainParameters.getCurve();
    ECPublicKeyParameters ecPublicKeyParameters = new ECPublicKeyParameters(ecCurve.decodePoint(ephemeralPubKey.toByteArray()), ecDomainParameters);
    BasicAgreement agree = new ECDHBasicAgreement();
    agree.init(ecdhPrivateKeyParameters);
    byte[] keyAgreement = agree.calculateAgreement(ecPublicKeyParameters).toByteArray();

    HKDFParameters hkdfParameters = new HKDFParameters(keyAgreement, null, null);
    HKDFBytesGenerator hkdfBytesGenerator = new HKDFBytesGenerator(digest);
    hkdfBytesGenerator.init(hkdfParameters);
    byte[] hkdfOutputBytes = new byte[AESKEY_LENGTH + HMACKEY_LENGTH];
    hkdfBytesGenerator.generateBytes(hkdfOutputBytes, 0, AESKEY_LENGTH + HMACKEY_LENGTH);
    ByteString hkdfOutput = ByteString.copyFrom(hkdfOutputBytes);
    ByteString aesKey = hkdfOutput.substring(0, AESKEY_LENGTH);
    ByteString hmacKey = hkdfOutput.substring(AESKEY_LENGTH, AESKEY_LENGTH + HMACKEY_LENGTH);
    HMac hMac = new HMac(digest);
    hMac.init(new KeyParameter(hmacKey.toByteArray()));
    hMac.update(encryptedContent.toByteArray(), 0, encryptedContent.size());
    byte[] recoveredHmac = new byte[hMac.getMacSize()];
    hMac.doFinal(recoveredHmac, 0);
    if (!MessageDigest.isEqual(hmac.toByteArray(), recoveredHmac)) {
        throw new RuntimeException("HMAC verify failed");
    }

    CFBBlockCipher aesCipher = new CFBBlockCipher(
            new AESEngine(), BLOCK_BIT_SIZE);
    ByteString iv = encryptedContent.substring(0, IV_LENGTH);
    CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(aesKey.toByteArray()), iv.toByteArray());
    aesCipher.init(false, ivAndKey);
    byte[] decryptedBytes = new byte[500];
    aesCipher.decryptBlock(encryptedContent.substring(IV_LENGTH).toByteArray(), 0, decryptedBytes, 0);
    return ByteString.copyFrom(decryptedBytes);
}
项目:testarea-pdfbox2    文件:CreateSignature.java   
/**
 * <a href="http://stackoverflow.com/questions/41767351/create-pkcs7-signature-from-file-digest">
 * Create pkcs7 signature from file digest
 * </a>
 * <p>
 * The OP's own <code>sign</code> method which has some errors. These
 * errors are fixed in {@link #signWithSeparatedHashing(InputStream)}.
 * </p>
 */
public byte[] signBySnox(InputStream content) throws IOException {
    // testSHA1WithRSAAndAttributeTable
    try {
        MessageDigest md = MessageDigest.getInstance("SHA1", "BC");
        List<Certificate> certList = new ArrayList<Certificate>();
        CMSTypedData msg = new CMSProcessableByteArray(IOUtils.toByteArray(content));

        certList.addAll(Arrays.asList(chain));

        Store certs = new JcaCertStore(certList);

        CMSSignedDataGenerator gen = new CMSSignedDataGenerator();

        Attribute attr = new Attribute(CMSAttributes.messageDigest,
                new DERSet(new DEROctetString(md.digest(IOUtils.toByteArray(content)))));

        ASN1EncodableVector v = new ASN1EncodableVector();

        v.add(attr);

        SignerInfoGeneratorBuilder builder = new SignerInfoGeneratorBuilder(new BcDigestCalculatorProvider())
                .setSignedAttributeGenerator(new DefaultSignedAttributeTableGenerator(new AttributeTable(v)));

        AlgorithmIdentifier sha1withRSA = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1withRSA");

        CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
        InputStream in = new ByteArrayInputStream(chain[0].getEncoded());
        X509Certificate cert = (X509Certificate) certFactory.generateCertificate(in);

        gen.addSignerInfoGenerator(builder.build(
                new BcRSAContentSignerBuilder(sha1withRSA,
                        new DefaultDigestAlgorithmIdentifierFinder().find(sha1withRSA))
                                .build(PrivateKeyFactory.createKey(pk.getEncoded())),
                new JcaX509CertificateHolder(cert)));

        gen.addCertificates(certs);

        CMSSignedData s = gen.generate(new CMSAbsentContent(), false);
        return new CMSSignedData(msg, s.getEncoded()).getEncoded();

    } catch (Exception e) {
        e.printStackTrace();
        throw new IOException(e);
    }
}
项目:ca    文件:CertificateManager.java   
/**
 * Given a Keystore containing a private key and certificate and a Reader
 * containing a PEM-encoded Certificiate Signing Request (CSR), sign the CSR
 * with that private key and return the signed certificate as a PEM-encoded
 * PKCS#7 signedData object. The returned value can be written to a file and
 * imported into a Java KeyStore with "keytool -import -trustcacerts -alias
 * subjectalias -file file.pem"
 *
 * @param pemcsr
 *            a Reader from which will be read a PEM-encoded CSR (begins
 *            "-----BEGIN NEW CERTIFICATE REQUEST-----")
 * @param validity
 *            the number of days to sign the Certificate for
 *
 * @return a String containing the PEM-encoded signed Certificate (begins
 *         "-----BEGIN PKCS #7 SIGNED DATA-----")
 */
public String signCSR(Reader pemcsr, int validity)
        throws Exception {
    PEMParser reader = new PEMParser(pemcsr);
    PKCS10CertificationRequest csr = new PKCS10CertificationRequest((CertificationRequest) reader.readObject());
    reader.close();

    AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1withRSA");
    AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
    X500Name issuer = caname;
    BigInteger serial = new BigInteger(32, new SecureRandom());
    Date from = new Date();
    Date to = new Date(System.currentTimeMillis() + (validity * 86400000L));

    X509v3CertificateBuilder certgen = new X509v3CertificateBuilder(issuer, serial, from, to, csr.getSubject(),
            csr.getSubjectPublicKeyInfo());
    certgen.addExtension(Extension.basicConstraints, false, new BasicConstraints(false));
    certgen.addExtension(Extension.subjectKeyIdentifier, false,
            new SubjectKeyIdentifier(csr.getSubjectPublicKeyInfo().getEncoded()));
    certgen.addExtension(Extension.authorityKeyIdentifier, false,
            new AuthorityKeyIdentifier(
                    new GeneralNames(new GeneralName(new X500Name(cacert.getSubjectX500Principal().getName()))),
                    cacert.getSerialNumber()));

    ContentSigner signer = new BcRSAContentSignerBuilder(sigAlgId, digAlgId)
            .build(PrivateKeyFactory.createKey(cakey.getEncoded()));
    X509CertificateHolder holder = certgen.build(signer);
    byte[] certencoded = holder.toASN1Structure().getEncoded();

    CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
    signer = new JcaContentSignerBuilder("SHA1withRSA").build(cakey);
    generator.addSignerInfoGenerator(
            new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().build()).build(signer,
                    cacert));
    generator.addCertificate(new X509CertificateHolder(certencoded));
    generator.addCertificate(new X509CertificateHolder(cacert.getEncoded()));
    CMSTypedData content = new CMSProcessableByteArray(certencoded);
    CMSSignedData signeddata = generator.generate(content, true);

    StringBuilder builder = new StringBuilder();
    builder.append("-----BEGIN PKCS #7 SIGNED DATA-----\n");
    builder.append(Base64.getEncoder().encodeToString(signeddata.getEncoded()));
    builder.append("\n-----END PKCS #7 SIGNED DATA-----\n");
    return builder.toString();
}
项目:occupy-pub    文件:CertificationAuthority.java   
protected AsymmetricKeyParameter readKey(Path keyPath) throws IOException {
    try (PemReader reader = new PemReader(Files.newBufferedReader(keyPath))) {
        PemObject pem = reader.readPemObject();
        return PrivateKeyFactory.createKey(pem.getContent());
    }
}
项目:mycarenet    文件:SealTest.java   
@Test
public void testSeal() throws Exception {
    InputStream sealInputStream = SealTest.class
            .getResourceAsStream("/seal-fcorneli.der");
    assertNotNull(sealInputStream);
    byte[] cmsData = IOUtils.toByteArray(sealInputStream);

    // check outer signature
    byte[] data = getVerifiedContent(cmsData);

    // decrypt content

    CMSEnvelopedDataParser cmsEnvelopedDataParser = new CMSEnvelopedDataParser(
            data);
    LOG.debug("content encryption algo: "
            + cmsEnvelopedDataParser.getContentEncryptionAlgorithm()
                    .getAlgorithm().getId());

    RecipientInformationStore recipientInformationStore = cmsEnvelopedDataParser
            .getRecipientInfos();
    Collection<RecipientInformation> recipients = recipientInformationStore
            .getRecipients();
    RecipientInformation recipientInformation = recipients.iterator()
            .next();
    LOG.debug("recipient info type: "
            + recipientInformation.getClass().getName());
    KeyTransRecipientInformation keyTransRecipientInformation = (KeyTransRecipientInformation) recipientInformation;

    // load eHealth encryption certificate
    KeyStore eHealthKeyStore = KeyStore.getInstance("PKCS12");
    FileInputStream fileInputStream = new FileInputStream(
            this.config.getEHealthPKCS12Path());
    eHealthKeyStore.load(fileInputStream, this.config
            .getEHealthPKCS12Password().toCharArray());
    Enumeration<String> aliasesEnum = eHealthKeyStore.aliases();
    aliasesEnum.nextElement(); // skip authentication certificate.
    String alias = aliasesEnum.nextElement();
    X509Certificate eHealthCertificate = (X509Certificate) eHealthKeyStore
            .getCertificate(alias);
    PrivateKey eHealthPrivateKey = (PrivateKey) eHealthKeyStore.getKey(
            alias, this.config.getEHealthPKCS12Password().toCharArray());

    AsymmetricKeyParameter privKeyParams = PrivateKeyFactory
            .createKey(eHealthPrivateKey.getEncoded());
    BcRSAKeyTransEnvelopedRecipient recipient = new BcRSAKeyTransEnvelopedRecipient(
            privKeyParams);
    byte[] decryptedContent = recipientInformation.getContent(recipient);
    assertNotNull(decryptedContent);
    LOG.debug("decrypted content size: " + decryptedContent.length);

    byte[] result = getVerifiedContent(decryptedContent);
    LOG.debug("result: " + new String(result));
}