Search in sources :

Example 81 with KeyPair

use of java.security.KeyPair in project XobotOS by xamarin.

the class MiscPEMGenerator method createPemObject.

private PemObject createPemObject(Object o) throws IOException {
    String type;
    byte[] encoding;
    if (o instanceof PemObject) {
        return (PemObject) o;
    }
    if (o instanceof PemObjectGenerator) {
        return ((PemObjectGenerator) o).generate();
    }
    if (o instanceof X509Certificate) {
        type = "CERTIFICATE";
        try {
            encoding = ((X509Certificate) o).getEncoded();
        } catch (CertificateEncodingException e) {
            throw new PemGenerationException("Cannot encode object: " + e.toString());
        }
    } else if (o instanceof X509CRL) {
        type = "X509 CRL";
        try {
            encoding = ((X509CRL) o).getEncoded();
        } catch (CRLException e) {
            throw new PemGenerationException("Cannot encode object: " + e.toString());
        }
    } else if (o instanceof KeyPair) {
        return createPemObject(((KeyPair) o).getPrivate());
    } else if (o instanceof PrivateKey) {
        PrivateKeyInfo info = new PrivateKeyInfo((ASN1Sequence) ASN1Object.fromByteArray(((Key) o).getEncoded()));
        if (o instanceof RSAPrivateKey) {
            type = "RSA PRIVATE KEY";
            encoding = info.getPrivateKey().getEncoded();
        } else if (o instanceof DSAPrivateKey) {
            type = "DSA PRIVATE KEY";
            DSAParameter p = DSAParameter.getInstance(info.getAlgorithmId().getParameters());
            ASN1EncodableVector v = new ASN1EncodableVector();
            v.add(new DERInteger(0));
            v.add(new DERInteger(p.getP()));
            v.add(new DERInteger(p.getQ()));
            v.add(new DERInteger(p.getG()));
            BigInteger x = ((DSAPrivateKey) o).getX();
            BigInteger y = p.getG().modPow(x, p.getP());
            v.add(new DERInteger(y));
            v.add(new DERInteger(x));
            encoding = new DERSequence(v).getEncoded();
        } else if (((PrivateKey) o).getAlgorithm().equals("ECDSA")) {
            type = "EC PRIVATE KEY";
            encoding = info.getPrivateKey().getEncoded();
        } else {
            throw new IOException("Cannot identify private key");
        }
    } else if (o instanceof PublicKey) {
        type = "PUBLIC KEY";
        encoding = ((PublicKey) o).getEncoded();
    } else if (o instanceof X509AttributeCertificate) {
        type = "ATTRIBUTE CERTIFICATE";
        encoding = ((X509V2AttributeCertificate) o).getEncoded();
    } else if (o instanceof PKCS10CertificationRequest) {
        type = "CERTIFICATE REQUEST";
        encoding = ((PKCS10CertificationRequest) o).getEncoded();
    } else if (o instanceof ContentInfo) {
        type = "PKCS7";
        encoding = ((ContentInfo) o).getEncoded();
    } else {
        throw new PemGenerationException("unknown object passed - can't encode.");
    }
    return new PemObject(type, encoding);
}
Also used : X509CRL(java.security.cert.X509CRL) DSAPrivateKey(java.security.interfaces.DSAPrivateKey) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) PrivateKey(java.security.PrivateKey) X509AttributeCertificate(org.bouncycastle.x509.X509AttributeCertificate) DERInteger(org.bouncycastle.asn1.DERInteger) PemObjectGenerator(org.bouncycastle.util.io.pem.PemObjectGenerator) DERSequence(org.bouncycastle.asn1.DERSequence) ContentInfo(org.bouncycastle.asn1.cms.ContentInfo) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) DSAParameter(org.bouncycastle.asn1.x509.DSAParameter) CRLException(java.security.cert.CRLException) PKCS10CertificationRequest(org.bouncycastle.jce.PKCS10CertificationRequest) KeyPair(java.security.KeyPair) PemGenerationException(org.bouncycastle.util.io.pem.PemGenerationException) PublicKey(java.security.PublicKey) CertificateEncodingException(java.security.cert.CertificateEncodingException) IOException(java.io.IOException) X509V2AttributeCertificate(org.bouncycastle.x509.X509V2AttributeCertificate) X509Certificate(java.security.cert.X509Certificate) PemObject(org.bouncycastle.util.io.pem.PemObject) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) DSAPrivateKey(java.security.interfaces.DSAPrivateKey) BigInteger(java.math.BigInteger) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo) DSAPrivateKey(java.security.interfaces.DSAPrivateKey) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) PublicKey(java.security.PublicKey) Key(java.security.Key) PrivateKey(java.security.PrivateKey) RSAPrivateCrtKey(java.security.interfaces.RSAPrivateCrtKey)

Example 82 with KeyPair

use of java.security.KeyPair in project XobotOS by xamarin.

the class MiscPEMGenerator method createPemObject.

private PemObject createPemObject(Object obj, String algorithm, char[] password, SecureRandom random) throws IOException {
    if (obj instanceof KeyPair) {
        return createPemObject(((KeyPair) obj).getPrivate(), algorithm, password, random);
    }
    String type = null;
    byte[] keyData = null;
    if (obj instanceof RSAPrivateCrtKey) {
        type = "RSA PRIVATE KEY";
        RSAPrivateCrtKey k = (RSAPrivateCrtKey) obj;
        RSAPrivateKeyStructure keyStruct = new RSAPrivateKeyStructure(k.getModulus(), k.getPublicExponent(), k.getPrivateExponent(), k.getPrimeP(), k.getPrimeQ(), k.getPrimeExponentP(), k.getPrimeExponentQ(), k.getCrtCoefficient());
        // convert to bytearray
        keyData = keyStruct.getEncoded();
    } else if (obj instanceof DSAPrivateKey) {
        type = "DSA PRIVATE KEY";
        DSAPrivateKey k = (DSAPrivateKey) obj;
        DSAParams p = k.getParams();
        ASN1EncodableVector v = new ASN1EncodableVector();
        v.add(new DERInteger(0));
        v.add(new DERInteger(p.getP()));
        v.add(new DERInteger(p.getQ()));
        v.add(new DERInteger(p.getG()));
        BigInteger x = k.getX();
        BigInteger y = p.getG().modPow(x, p.getP());
        v.add(new DERInteger(y));
        v.add(new DERInteger(x));
        keyData = new DERSequence(v).getEncoded();
    } else if (obj instanceof PrivateKey && "ECDSA".equals(((PrivateKey) obj).getAlgorithm())) {
        type = "EC PRIVATE KEY";
        PrivateKeyInfo privInfo = PrivateKeyInfo.getInstance(ASN1Object.fromByteArray(((PrivateKey) obj).getEncoded()));
        keyData = privInfo.getPrivateKey().getEncoded();
    }
    if (type == null || keyData == null) {
        // TODO Support other types?
        throw new IllegalArgumentException("Object type not supported: " + obj.getClass().getName());
    }
    String dekAlgName = Strings.toUpperCase(algorithm);
    // Note: For backward compatibility
    if (dekAlgName.equals("DESEDE")) {
        dekAlgName = "DES-EDE3-CBC";
    }
    int ivLength = dekAlgName.startsWith("AES-") ? 16 : 8;
    byte[] iv = new byte[ivLength];
    random.nextBytes(iv);
    byte[] encData = PEMUtilities.crypt(true, provider, keyData, password, dekAlgName, iv);
    List headers = new ArrayList(2);
    headers.add(new PemHeader("Proc-Type", "4,ENCRYPTED"));
    headers.add(new PemHeader("DEK-Info", dekAlgName + "," + getHexEncoded(iv)));
    return new PemObject(type, headers, encData);
}
Also used : KeyPair(java.security.KeyPair) RSAPrivateCrtKey(java.security.interfaces.RSAPrivateCrtKey) DSAPrivateKey(java.security.interfaces.DSAPrivateKey) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) PrivateKey(java.security.PrivateKey) ArrayList(java.util.ArrayList) DSAParams(java.security.interfaces.DSAParams) DERInteger(org.bouncycastle.asn1.DERInteger) PemObject(org.bouncycastle.util.io.pem.PemObject) DERSequence(org.bouncycastle.asn1.DERSequence) RSAPrivateKeyStructure(org.bouncycastle.asn1.pkcs.RSAPrivateKeyStructure) DSAPrivateKey(java.security.interfaces.DSAPrivateKey) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) BigInteger(java.math.BigInteger) ArrayList(java.util.ArrayList) List(java.util.List) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo) PemHeader(org.bouncycastle.util.io.pem.PemHeader)

Example 83 with KeyPair

use of java.security.KeyPair in project nhin-d by DirectProject.

the class CRLRevocationManager_getCrlFromUriTest method testGetCrlFromUri_notInCache_loadFromCacheFile_assertCRLFound.

public void testGetCrlFromUri_notInCache_loadFromCacheFile_assertCRLFound() throws Exception {
    CRLRevocationManager.initCRLCacheLocation();
    String uri = "http://localhost:8080/certs.crl";
    X509CRL crl = (X509CRL) TestUtils.loadCRL("certs.crl");
    KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA", "BC");
    KeyPair pair = kpGen.generateKeyPair();
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.YEAR, cal.get(Calendar.YEAR) + 10);
    X509V2CRLGenerator crlGen = new X509V2CRLGenerator();
    crlGen.setIssuerDN(new X500Principal("CN=Test CRL"));
    crlGen.setNextUpdate(cal.getTime());
    crlGen.setSignatureAlgorithm("SHA256withRSAEncryption");
    crlGen.setThisUpdate(Calendar.getInstance().getTime());
    crlGen.addCRL(crl);
    crl = crlGen.generate(pair.getPrivate(), "BC");
    CRLRevocationManager.INSTANCE.writeCRLCacheFile(uri, crl);
    X509CRL retCrl = CRLRevocationManager.getInstance().getCrlFromUri(uri);
    assertNotNull(retCrl);
    assertEquals(crl, retCrl);
}
Also used : KeyPair(java.security.KeyPair) X509CRL(java.security.cert.X509CRL) Calendar(java.util.Calendar) X500Principal(javax.security.auth.x500.X500Principal) KeyPairGenerator(java.security.KeyPairGenerator) X509V2CRLGenerator(org.bouncycastle.x509.X509V2CRLGenerator)

Example 84 with KeyPair

use of java.security.KeyPair in project android_frameworks_base by DirtyUnicorns.

the class AndroidKeyStoreTest method generateCertificate.

@SuppressWarnings("deprecation")
private static X509Certificate generateCertificate(android.security.KeyStore keyStore, String alias, BigInteger serialNumber, X500Principal subjectDN, Date notBefore, Date notAfter) throws Exception {
    final String privateKeyAlias = Credentials.USER_PRIVATE_KEY + alias;
    KeyPair keyPair = AndroidKeyStoreProvider.loadAndroidKeyStoreKeyPairFromKeystore(keyStore, privateKeyAlias, KeyStore.UID_SELF);
    final X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    certGen.setPublicKey(keyPair.getPublic());
    certGen.setSerialNumber(serialNumber);
    certGen.setSubjectDN(subjectDN);
    certGen.setIssuerDN(subjectDN);
    certGen.setNotBefore(notBefore);
    certGen.setNotAfter(notAfter);
    certGen.setSignatureAlgorithm("sha1WithRSA");
    final X509Certificate cert = certGen.generate(keyPair.getPrivate());
    return cert;
}
Also used : KeyPair(java.security.KeyPair) X509V3CertificateGenerator(com.android.org.bouncycastle.x509.X509V3CertificateGenerator) X509Certificate(java.security.cert.X509Certificate)

Example 85 with KeyPair

use of java.security.KeyPair in project android_frameworks_base by DirtyUnicorns.

the class AndroidKeyPairGeneratorTest method testKeyPairGenerator_GenerateKeyPair_EC_Unencrypted_Success.

public void testKeyPairGenerator_GenerateKeyPair_EC_Unencrypted_Success() throws Exception {
    KeyPairGenerator generator = KeyPairGenerator.getInstance("EC", "AndroidKeyStore");
    generator.initialize(new KeyGenParameterSpec.Builder(TEST_ALIAS_1, KeyProperties.PURPOSE_SIGN | KeyProperties.PURPOSE_VERIFY).setCertificateSubject(TEST_DN_1).setCertificateSerialNumber(TEST_SERIAL_1).setCertificateNotBefore(NOW).setCertificateNotAfter(NOW_PLUS_10_YEARS).setDigests(KeyProperties.DIGEST_SHA256).build());
    final KeyPair pair = generator.generateKeyPair();
    assertNotNull("The KeyPair returned should not be null", pair);
    assertKeyPairCorrect(pair, TEST_ALIAS_1, "EC", 256, null, TEST_DN_1, TEST_SERIAL_1, NOW, NOW_PLUS_10_YEARS);
}
Also used : KeyPair(java.security.KeyPair) RSAKeyGenParameterSpec(java.security.spec.RSAKeyGenParameterSpec) KeyPairGenerator(java.security.KeyPairGenerator)

Aggregations

KeyPair (java.security.KeyPair)313 KeyPairGenerator (java.security.KeyPairGenerator)146 X509Certificate (java.security.cert.X509Certificate)61 PrivateKey (java.security.PrivateKey)60 PublicKey (java.security.PublicKey)59 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)36 IOException (java.io.IOException)34 SecureRandom (java.security.SecureRandom)31 Test (org.junit.Test)26 KeyFactory (java.security.KeyFactory)23 KeyStore (java.security.KeyStore)23 Date (java.util.Date)22 BigInteger (java.math.BigInteger)21 Signature (java.security.Signature)19 File (java.io.File)17 Cipher (javax.crypto.Cipher)17 KeyPairGeneratorSpec (android.security.KeyPairGeneratorSpec)16 RSAPrivateKey (java.security.interfaces.RSAPrivateKey)16 RSAPublicKey (java.security.interfaces.RSAPublicKey)16 HashMap (java.util.HashMap)16