Search in sources :

Example 11 with RSAPrivateKey

use of org.bouncycastle.asn1.pkcs.RSAPrivateKey in project athenz by yahoo.

the class CryptoTest method testX509CSRrequest.

@Test(dataProvider = "x500Principal")
public void testX509CSRrequest(String x500Principal, boolean badRequest) {
    PublicKey publicKey = Crypto.loadPublicKey(rsaPublicKey);
    PrivateKey privateKey = Crypto.loadPrivateKey(rsaPrivateKey);
    String certRequest = null;
    GeneralName otherName1 = new GeneralName(GeneralName.otherName, new DERIA5String("role1"));
    GeneralName otherName2 = new GeneralName(GeneralName.otherName, new DERIA5String("role2"));
    GeneralName[] sanArray = new GeneralName[] { otherName1, otherName2 };
    try {
        certRequest = Crypto.generateX509CSR(privateKey, publicKey, x500Principal, sanArray);
    } catch (Exception e) {
        if (!badRequest) {
            fail("Should not have failed to create csr");
        }
    }
    if (!badRequest) {
        // Now validate the csr
        Crypto.getPKCS10CertRequest(certRequest);
    }
}
Also used : PrivateKey(java.security.PrivateKey) DERIA5String(org.bouncycastle.asn1.DERIA5String) PublicKey(java.security.PublicKey) DERIA5String(org.bouncycastle.asn1.DERIA5String) GeneralName(org.bouncycastle.asn1.x509.GeneralName) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Test(org.testng.annotations.Test)

Example 12 with RSAPrivateKey

use of org.bouncycastle.asn1.pkcs.RSAPrivateKey in project athenz by yahoo.

the class CryptoTest method testSignVerifyRSAKey.

@Test
public void testSignVerifyRSAKey() {
    PrivateKey privateKey = Crypto.loadPrivateKey(rsaPrivateKey);
    assertNotNull(privateKey);
    String signature = Crypto.sign(serviceToken, privateKey);
    assertEquals(signature, serviceRSASignature);
    PublicKey publicKey = Crypto.loadPublicKey(rsaPublicKey);
    assertNotNull(publicKey);
    assertTrue(Crypto.verify(serviceToken, publicKey, signature));
}
Also used : PrivateKey(java.security.PrivateKey) PublicKey(java.security.PublicKey) DERIA5String(org.bouncycastle.asn1.DERIA5String) Test(org.testng.annotations.Test)

Example 13 with RSAPrivateKey

use of org.bouncycastle.asn1.pkcs.RSAPrivateKey in project athenz by yahoo.

the class CryptoTest method testSignVerifyExtractedRSAKey.

@Test
public void testSignVerifyExtractedRSAKey() {
    PrivateKey privateKey = Crypto.loadPrivateKey(rsaPrivateKey);
    assertNotNull(privateKey);
    String signature = Crypto.sign(serviceToken, privateKey);
    assertEquals(signature, serviceRSASignature);
    PublicKey publicKey = Crypto.extractPublicKey(privateKey);
    assertNotNull(publicKey);
    assertTrue(Crypto.verify(serviceToken, publicKey, signature));
}
Also used : PrivateKey(java.security.PrivateKey) PublicKey(java.security.PublicKey) DERIA5String(org.bouncycastle.asn1.DERIA5String) Test(org.testng.annotations.Test)

Example 14 with RSAPrivateKey

use of org.bouncycastle.asn1.pkcs.RSAPrivateKey in project XobotOS by xamarin.

the class RSAPrivateKeyStructure method toASN1Object.

/**
     * This outputs the key in PKCS1v2 format.
     * <pre>
     *      RSAPrivateKey ::= SEQUENCE {
     *                          version Version,
     *                          modulus INTEGER, -- n
     *                          publicExponent INTEGER, -- e
     *                          privateExponent INTEGER, -- d
     *                          prime1 INTEGER, -- p
     *                          prime2 INTEGER, -- q
     *                          exponent1 INTEGER, -- d mod (p-1)
     *                          exponent2 INTEGER, -- d mod (q-1)
     *                          coefficient INTEGER, -- (inverse of q) mod p
     *                          otherPrimeInfos OtherPrimeInfos OPTIONAL
     *                      }
     *
     *      Version ::= INTEGER { two-prime(0), multi(1) }
     *        (CONSTRAINED BY {-- version must be multi if otherPrimeInfos present --})
     * </pre>
     * <p>
     * This routine is written to output PKCS1 version 2.1, private keys.
     */
public DERObject toASN1Object() {
    ASN1EncodableVector v = new ASN1EncodableVector();
    // version
    v.add(new DERInteger(version));
    v.add(new DERInteger(getModulus()));
    v.add(new DERInteger(getPublicExponent()));
    v.add(new DERInteger(getPrivateExponent()));
    v.add(new DERInteger(getPrime1()));
    v.add(new DERInteger(getPrime2()));
    v.add(new DERInteger(getExponent1()));
    v.add(new DERInteger(getExponent2()));
    v.add(new DERInteger(getCoefficient()));
    if (otherPrimeInfos != null) {
        v.add(otherPrimeInfos);
    }
    return new DERSequence(v);
}
Also used : DERSequence(org.bouncycastle.asn1.DERSequence) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) DERInteger(org.bouncycastle.asn1.DERInteger)

Example 15 with RSAPrivateKey

use of org.bouncycastle.asn1.pkcs.RSAPrivateKey in project candlepin by candlepin.

the class CrlFileUtil method updateCRLFile.

/**
 * Updates the specified CRL file by adding or removing entries. If both lists are either null
 * or empty, the CRL file will not be modified by this method. If the file does not exist or
 * appears to be empty, it will be initialized before processing the lists.
 *
 * @param file
 *  The CRL file to update
 *
 * @param revoke
 *  A collection of serials to revoke (add)
 *
 * @param unrevoke
 *  A collection of serials to unrevoke (remove)
 *
 * @throws IOException
 *  if an IO error occurs while updating the CRL file
 */
public void updateCRLFile(File file, final Collection<BigInteger> revoke, final Collection<BigInteger> unrevoke) throws IOException {
    if (!file.exists() || file.length() == 0) {
        this.initializeCRLFile(file, revoke);
        return;
    }
    File strippedFile = stripCRLFile(file);
    InputStream input = null;
    InputStream reaper = null;
    BufferedOutputStream output = null;
    OutputStream filter = null;
    OutputStream encoder = null;
    try {
        // Impl note:
        // Due to the way the X509CRLStreamWriter works (and the DER format in general), we have
        // to make two passes through the file.
        input = new Base64InputStream(new FileInputStream(strippedFile));
        reaper = new Base64InputStream(new FileInputStream(strippedFile));
        // Note: This will break if we ever stop using RSA keys
        PrivateKey key = this.certificateReader.getCaKey();
        X509CRLStreamWriter writer = new X509CRLStreamWriter(input, (RSAPrivateKey) key, this.certificateReader.getCACert());
        // Add new entries
        if (revoke != null) {
            Date now = new Date();
            for (BigInteger serial : revoke) {
                writer.add(serial, now, CRLReason.privilegeWithdrawn);
            }
        }
        // or we could miss cases where we have entries to remove, but nothing to add.
        if (unrevoke != null && !unrevoke.isEmpty()) {
            writer.preScan(reaper, new CRLEntryValidator() {

                public boolean shouldDelete(CRLEntry entry) {
                    BigInteger certSerial = entry.getUserCertificate().getValue();
                    return unrevoke.contains(certSerial);
                }
            });
        } else {
            writer.preScan(reaper);
        }
        writer.setSigningAlgorithm(PKIUtility.SIGNATURE_ALGO);
        // Verify we actually have work to do now
        if (writer.hasChangesQueued()) {
            output = new BufferedOutputStream(new FileOutputStream(file));
            filter = new FilterOutputStream(output) {

                private boolean needsLineBreak = true;

                public void write(int b) throws IOException {
                    this.needsLineBreak = (b != (byte) '\n');
                    super.write(b);
                }

                public void write(byte[] buffer) throws IOException {
                    this.needsLineBreak = (buffer[buffer.length - 1] != (byte) '\n');
                    super.write(buffer);
                }

                public void write(byte[] buffer, int off, int len) throws IOException {
                    this.needsLineBreak = (buffer[off + len - 1] != (byte) '\n');
                    super.write(buffer, off, len);
                }

                public void close() throws IOException {
                    if (this.needsLineBreak) {
                        super.write((int) '\n');
                        this.needsLineBreak = false;
                    }
                // Impl note:
                // We're intentionally not propagating the call here.
                }
            };
            encoder = new Base64OutputStream(filter, true, 76, new byte[] { (byte) '\n' });
            output.write("-----BEGIN X509 CRL-----\n".getBytes());
            writer.lock();
            writer.write(encoder);
            encoder.close();
            filter.close();
            output.write("-----END X509 CRL-----\n".getBytes());
            output.close();
        }
    } catch (GeneralSecurityException e) {
        // This should never actually happen
        log.error("Unexpected security error occurred while retrieving CA key", e);
    } catch (CryptoException e) {
        // Something went horribly wrong with the stream writer
        log.error("Unexpected error occurred while writing new CRL file", e);
    } finally {
        for (Closeable stream : Arrays.asList(encoder, output, reaper, input)) {
            if (stream != null) {
                try {
                    stream.close();
                } catch (IOException e) {
                    log.error("Unexpected exception occurred while closing stream: {}", stream, e);
                }
            }
        }
        if (!strippedFile.delete()) {
            log.error("Unable to delete temporary CRL file: {}", strippedFile);
        }
    }
}
Also used : RSAPrivateKey(java.security.interfaces.RSAPrivateKey) PrivateKey(java.security.PrivateKey) FileInputStream(java.io.FileInputStream) Base64InputStream(org.apache.commons.codec.binary.Base64InputStream) InputStream(java.io.InputStream) BufferedOutputStream(java.io.BufferedOutputStream) Base64OutputStream(org.apache.commons.codec.binary.Base64OutputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) FilterOutputStream(java.io.FilterOutputStream) GeneralSecurityException(java.security.GeneralSecurityException) Closeable(java.io.Closeable) CRLEntry(org.bouncycastle.asn1.x509.TBSCertList.CRLEntry) IOException(java.io.IOException) Base64OutputStream(org.apache.commons.codec.binary.Base64OutputStream) FileInputStream(java.io.FileInputStream) Date(java.util.Date) FileOutputStream(java.io.FileOutputStream) BigInteger(java.math.BigInteger) Base64InputStream(org.apache.commons.codec.binary.Base64InputStream) FilterOutputStream(java.io.FilterOutputStream) CryptoException(org.bouncycastle.crypto.CryptoException) File(java.io.File) BufferedOutputStream(java.io.BufferedOutputStream)

Aggregations

BigInteger (java.math.BigInteger)11 PrivateKey (java.security.PrivateKey)10 BufferedOutputStream (java.io.BufferedOutputStream)8 File (java.io.File)8 FileOutputStream (java.io.FileOutputStream)8 OutputStream (java.io.OutputStream)8 X509CRL (java.security.cert.X509CRL)8 DERIA5String (org.bouncycastle.asn1.DERIA5String)8 Test (org.testng.annotations.Test)8 ASN1Integer (org.bouncycastle.asn1.ASN1Integer)7 Test (org.junit.Test)7 PublicKey (java.security.PublicKey)6 X509CRLEntry (java.security.cert.X509CRLEntry)6 Date (java.util.Date)6 HashSet (java.util.HashSet)6 ASN1EncodableVector (org.bouncycastle.asn1.ASN1EncodableVector)5 DERSequence (org.bouncycastle.asn1.DERSequence)5 X509CRLHolder (org.bouncycastle.cert.X509CRLHolder)5 DSAPrivateKey (java.security.interfaces.DSAPrivateKey)4 RSAPrivateKey (java.security.interfaces.RSAPrivateKey)4