Search in sources :

Example 6 with BouncyCastleProvider

use of org.bouncycastle.jce.provider.BouncyCastleProvider in project OpenAttestation by OpenAttestation.

the class TASecureServer method main.

public static void main(String[] argv) {
    TASecureServer server;
    try {
        Security.addProvider(new BouncyCastleProvider());
        server = new TASecureServer(getSecurePort());
        server.waitForConnections();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        log.error("Error while starting TA", e);
    }
}
Also used : IOException(java.io.IOException) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Example 7 with BouncyCastleProvider

use of org.bouncycastle.jce.provider.BouncyCastleProvider in project robolectric by robolectric.

the class ParallelUniverse method setUpApplicationState.

@Override
public void setUpApplicationState(Method method, TestLifecycle testLifecycle, AndroidManifest appManifest, Config config, ResourceTable compileTimeResourceTable, ResourceTable appResourceTable, ResourceTable systemResourceTable) {
    ReflectionHelpers.setStaticField(RuntimeEnvironment.class, "apiLevel", sdkConfig.getApiLevel());
    RuntimeEnvironment.application = null;
    RuntimeEnvironment.setMasterScheduler(new Scheduler());
    RuntimeEnvironment.setMainThread(Thread.currentThread());
    DefaultPackageManager packageManager = new DefaultPackageManager();
    RuntimeEnvironment.setRobolectricPackageManager(packageManager);
    RuntimeEnvironment.setCompileTimeResourceTable(compileTimeResourceTable);
    RuntimeEnvironment.setAppResourceTable(appResourceTable);
    RuntimeEnvironment.setSystemResourceTable(systemResourceTable);
    initializeAppManifest(appManifest, appResourceTable, packageManager);
    packageManager.setDependencies(appManifest, appResourceTable);
    if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
        Security.insertProviderAt(new BouncyCastleProvider(), 1);
    }
    String qualifiers = Qualifiers.addPlatformVersion(config.qualifiers(), sdkConfig.getApiLevel());
    qualifiers = Qualifiers.addSmallestScreenWidth(qualifiers, 320);
    qualifiers = Qualifiers.addScreenWidth(qualifiers, 320);
    Resources systemResources = Resources.getSystem();
    Configuration configuration = systemResources.getConfiguration();
    configuration.smallestScreenWidthDp = Qualifiers.getSmallestScreenWidth(qualifiers);
    configuration.screenWidthDp = Qualifiers.getScreenWidth(qualifiers);
    systemResources.updateConfiguration(configuration, systemResources.getDisplayMetrics());
    RuntimeEnvironment.setQualifiers(qualifiers);
    Class<?> contextImplClass = ReflectionHelpers.loadClass(getClass().getClassLoader(), shadowsAdapter.getShadowContextImplClassName());
    Class<?> activityThreadClass = ReflectionHelpers.loadClass(getClass().getClassLoader(), shadowsAdapter.getShadowActivityThreadClassName());
    // Looper needs to be prepared before the activity thread is created
    if (Looper.myLooper() == null) {
        Looper.prepareMainLooper();
    }
    ShadowLooper.getShadowMainLooper().resetScheduler();
    Object activityThread = ReflectionHelpers.newInstance(activityThreadClass);
    RuntimeEnvironment.setActivityThread(activityThread);
    ReflectionHelpers.setField(activityThread, "mInstrumentation", new RoboInstrumentation());
    ReflectionHelpers.setField(activityThread, "mCompatConfiguration", configuration);
    Context systemContextImpl = ReflectionHelpers.callStaticMethod(contextImplClass, "createSystemContext", ClassParameter.from(activityThreadClass, activityThread));
    final Application application = (Application) testLifecycle.createApplication(method, appManifest, config);
    RuntimeEnvironment.application = application;
    if (application != null) {
        shadowsAdapter.bind(application, appManifest);
        ApplicationInfo applicationInfo;
        try {
            applicationInfo = packageManager.getApplicationInfo(appManifest.getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            throw new RuntimeException(e);
        }
        Class<?> compatibilityInfoClass = ReflectionHelpers.loadClass(getClass().getClassLoader(), "android.content.res.CompatibilityInfo");
        LoadedApk loadedApk = ReflectionHelpers.callInstanceMethod(activityThread, "getPackageInfo", ClassParameter.from(ApplicationInfo.class, applicationInfo), ClassParameter.from(compatibilityInfoClass, null), ClassParameter.from(int.class, Context.CONTEXT_INCLUDE_CODE));
        try {
            Context contextImpl = systemContextImpl.createPackageContext(applicationInfo.packageName, Context.CONTEXT_INCLUDE_CODE);
            ReflectionHelpers.setField(activityThreadClass, activityThread, "mInitialApplication", application);
            ApplicationTestUtil.attach(application, contextImpl);
        } catch (PackageManager.NameNotFoundException e) {
            throw new RuntimeException(e);
        }
        Resources appResources = application.getResources();
        ReflectionHelpers.setField(loadedApk, "mResources", appResources);
        ReflectionHelpers.setField(loadedApk, "mApplication", application);
        appResources.updateConfiguration(configuration, appResources.getDisplayMetrics());
        application.onCreate();
    }
}
Also used : Context(android.content.Context) Configuration(android.content.res.Configuration) LoadedApk(android.app.LoadedApk) Scheduler(org.robolectric.util.Scheduler) RoboInstrumentation(org.robolectric.android.fakes.RoboInstrumentation) DefaultPackageManager(org.robolectric.res.builder.DefaultPackageManager) ApplicationInfo(android.content.pm.ApplicationInfo) PackageManager(android.content.pm.PackageManager) DefaultPackageManager(org.robolectric.res.builder.DefaultPackageManager) Resources(android.content.res.Resources) Application(android.app.Application) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Example 8 with BouncyCastleProvider

use of org.bouncycastle.jce.provider.BouncyCastleProvider in project otertool by wuntee.

the class AdbWorkshop method installCert.

public static void installCert(File certfile, String password) throws NotRootedException, Exception {
    if (!AdbWorkshop.canGetRoot()) {
        throw new NotRootedException();
    }
    Security.addProvider(new BouncyCastleProvider());
    // Pull the keystore, and load it into a Keystore object
    logger.debug("Pulling cacerts file");
    File cacerts = AdbWorkshop.pullFile(OterStatics.ANDROID_CERT_FILE);
    KeyStore ks = KeyStore.getInstance("BKS");
    FileInputStream fis = new java.io.FileInputStream(cacerts);
    ks.load(fis, password.toCharArray());
    // Read the certificate, and add it to the certfile
    logger.debug("Reading the cert, and adding it to a certfile: " + certfile.getName());
    FileInputStream is = new FileInputStream(certfile);
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    Certificate cert = cf.generateCertificate(is);
    ks.setCertificateEntry(certfile.getName(), cert);
    // Write cacert back out
    logger.debug("Writing temporary certfile to disk");
    File localFile = AdbWorkshop.getTemporaryFile();
    FileOutputStream fos = new java.io.FileOutputStream(localFile);
    ks.store(fos, password.toCharArray());
    // Mount FS as read/write
    logger.debug("Mounting remote filesystem rw");
    AdbWorkshop.mountFilesystemReadWrite();
    // Change file permissions of current cacert
    logger.debug("Changing permissions of certfile to 777");
    AdbWorkshop.changeFilePermissions(OterStatics.ANDROID_CERT_FILE, "777");
    // Push the new file back up
    logger.debug("Pushing the file on to the device");
    AdbWorkshop.pushFile(localFile, OterStatics.ANDROID_CERT_FILE);
    // Change file permissions back
    logger.debug("Changing permissions of certfile to 644");
    AdbWorkshop.changeFilePermissions(OterStatics.ANDROID_CERT_FILE, "644");
    // Deleting the temporary file
    logger.debug("Removing local temporary file: " + localFile);
    localFile.delete();
}
Also used : FileOutputStream(java.io.FileOutputStream) NotRootedException(com.wuntee.oter.exception.NotRootedException) File(java.io.File) KeyStore(java.security.KeyStore) CertificateFactory(java.security.cert.CertificateFactory) FileInputStream(java.io.FileInputStream) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) Certificate(java.security.cert.Certificate)

Example 9 with BouncyCastleProvider

use of org.bouncycastle.jce.provider.BouncyCastleProvider in project chassis by Kixeye.

the class WebSocketTransportTest method testWebSocketServiceWithJsonWithPskEncryption.

@Test
public void testWebSocketServiceWithJsonWithPskEncryption() throws Exception {
    // create AES shared key cipher
    Security.addProvider(new BouncyCastleProvider());
    KeyGenerator kgen = KeyGenerator.getInstance("AES", "BC");
    kgen.init(128);
    SecretKey key = kgen.generateKey();
    byte[] aesKey = key.getEncoded();
    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put("websocket.enabled", "true");
    properties.put("websocket.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("websocket.hostname", "localhost");
    properties.put("http.enabled", "false");
    properties.put("http.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("http.hostname", "localhost");
    properties.put("websocket.crypto.enabled", "true");
    properties.put("websocket.crypto.cipherProvider", "BC");
    properties.put("websocket.crypto.cipherTransformation", "AES/ECB/PKCS7Padding");
    properties.put("websocket.crypto.secretKeyAlgorithm", "AES");
    properties.put("websocket.crypto.secretKeyData", BaseEncoding.base16().encode(aesKey));
    AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
    StandardEnvironment environment = new StandardEnvironment();
    environment.getPropertySources().addFirst(new MapPropertySource("default", properties));
    context.setEnvironment(environment);
    context.register(PropertySourcesPlaceholderConfigurer.class);
    context.register(TransportConfiguration.class);
    context.register(TestWebSocketService.class);
    WebSocketClient wsClient = new WebSocketClient();
    try {
        context.refresh();
        final MessageSerDe serDe = context.getBean(JsonJacksonMessageSerDe.class);
        final WebSocketMessageRegistry messageRegistry = context.getBean(WebSocketMessageRegistry.class);
        messageRegistry.registerType("stuff", TestObject.class);
        wsClient.start();
        QueuingWebSocketListener webSocket = new QueuingWebSocketListener(serDe, messageRegistry, context.getBean(WebSocketPskFrameProcessor.class));
        Session session = wsClient.connect(webSocket, new URI("ws://localhost:" + properties.get("websocket.port") + "/" + serDe.getMessageFormatName())).get(5000, TimeUnit.MILLISECONDS);
        Envelope envelope = new Envelope("getStuff", null, null, Lists.newArrayList(new Header("testheadername", Lists.newArrayList("testheaderval"))), null);
        byte[] rawEnvelope = serDe.serialize(envelope);
        rawEnvelope = SymmetricKeyCryptoUtils.encrypt(rawEnvelope, 0, rawEnvelope.length, key, "AES/ECB/PKCS7Padding", "BC");
        session.getRemote().sendBytes(ByteBuffer.wrap(rawEnvelope));
        TestObject response = webSocket.getResponse(5, TimeUnit.SECONDS);
        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);
        byte[] rawStuff = serDe.serialize(new TestObject("more stuff"));
        envelope = new Envelope("setStuff", "stuff", null, ByteBuffer.wrap(rawStuff));
        rawEnvelope = serDe.serialize(envelope);
        rawEnvelope = SymmetricKeyCryptoUtils.encrypt(rawEnvelope, 0, rawEnvelope.length, key, "AES/ECB/PKCS7Padding", "BC");
        session.getRemote().sendBytes(ByteBuffer.wrap(rawEnvelope));
        response = webSocket.getResponse(5, TimeUnit.SECONDS);
        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);
        envelope = new Envelope("getStuff", null, null, null);
        rawEnvelope = serDe.serialize(envelope);
        rawEnvelope = SymmetricKeyCryptoUtils.encrypt(rawEnvelope, 0, rawEnvelope.length, key, "AES/ECB/PKCS7Padding", "BC");
        session.getRemote().sendBytes(ByteBuffer.wrap(rawEnvelope));
        response = webSocket.getResponse(5, TimeUnit.SECONDS);
        Assert.assertNotNull(response);
        Assert.assertEquals("more stuff", response.value);
        rawStuff = serDe.serialize(new TestObject(RandomStringUtils.randomAlphanumeric(100)));
        envelope = new Envelope("setStuff", "stuff", null, ByteBuffer.wrap(rawStuff));
        rawEnvelope = serDe.serialize(envelope);
        rawEnvelope = SymmetricKeyCryptoUtils.encrypt(rawEnvelope, 0, rawEnvelope.length, key, "AES/ECB/PKCS7Padding", "BC");
        session.getRemote().sendBytes(ByteBuffer.wrap(rawEnvelope));
        ServiceError error = webSocket.getResponse(5, TimeUnit.SECONDS);
        Assert.assertNotNull(error);
        Assert.assertEquals(ExceptionServiceErrorMapper.VALIDATION_ERROR_CODE, error.code);
        envelope = new Envelope("expectedError", null, null, null);
        rawEnvelope = serDe.serialize(envelope);
        rawEnvelope = SymmetricKeyCryptoUtils.encrypt(rawEnvelope, 0, rawEnvelope.length, key, "AES/ECB/PKCS7Padding", "BC");
        session.getRemote().sendBytes(ByteBuffer.wrap(rawEnvelope));
        error = webSocket.getResponse(5, TimeUnit.SECONDS);
        Assert.assertNotNull(error);
        Assert.assertEquals(TestWebSocketService.EXPECTED_EXCEPTION.code, error.code);
        Assert.assertEquals(TestWebSocketService.EXPECTED_EXCEPTION.description, error.description);
        envelope = new Envelope("unexpectedError", null, null, null);
        rawEnvelope = serDe.serialize(envelope);
        rawEnvelope = SymmetricKeyCryptoUtils.encrypt(rawEnvelope, 0, rawEnvelope.length, key, "AES/ECB/PKCS7Padding", "BC");
        session.getRemote().sendBytes(ByteBuffer.wrap(rawEnvelope));
        error = webSocket.getResponse(5, TimeUnit.SECONDS);
        Assert.assertNotNull(error);
        Assert.assertEquals(ExceptionServiceErrorMapper.UNKNOWN_ERROR_CODE, error.code);
    } finally {
        try {
            wsClient.stop();
        } finally {
            context.close();
        }
    }
}
Also used : ServiceError(com.kixeye.chassis.transport.dto.ServiceError) HashMap(java.util.HashMap) WebSocketMessageRegistry(com.kixeye.chassis.transport.websocket.WebSocketMessageRegistry) JsonJacksonMessageSerDe(com.kixeye.chassis.transport.serde.converter.JsonJacksonMessageSerDe) ProtobufMessageSerDe(com.kixeye.chassis.transport.serde.converter.ProtobufMessageSerDe) YamlJacksonMessageSerDe(com.kixeye.chassis.transport.serde.converter.YamlJacksonMessageSerDe) XmlMessageSerDe(com.kixeye.chassis.transport.serde.converter.XmlMessageSerDe) MessageSerDe(com.kixeye.chassis.transport.serde.MessageSerDe) WebSocketClient(org.eclipse.jetty.websocket.client.WebSocketClient) Envelope(com.kixeye.chassis.transport.dto.Envelope) AnnotationConfigWebApplicationContext(org.springframework.web.context.support.AnnotationConfigWebApplicationContext) URI(java.net.URI) SecretKey(javax.crypto.SecretKey) Header(com.kixeye.chassis.transport.dto.Header) MapPropertySource(org.springframework.core.env.MapPropertySource) QueuingWebSocketListener(com.kixeye.chassis.transport.websocket.QueuingWebSocketListener) KeyGenerator(javax.crypto.KeyGenerator) WebSocketPskFrameProcessor(com.kixeye.chassis.transport.websocket.WebSocketPskFrameProcessor) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) StandardEnvironment(org.springframework.core.env.StandardEnvironment) Session(org.eclipse.jetty.websocket.api.Session) WebSocketSession(org.eclipse.jetty.websocket.common.WebSocketSession) Test(org.junit.Test)

Example 10 with BouncyCastleProvider

use of org.bouncycastle.jce.provider.BouncyCastleProvider in project cloudstack by apache.

the class SAMLUtils method getKeyFactory.

public static KeyFactory getKeyFactory() {
    KeyFactory keyFactory = null;
    try {
        Security.addProvider(new BouncyCastleProvider());
        keyFactory = KeyFactory.getInstance("RSA", "BC");
    } catch (NoSuchAlgorithmException | NoSuchProviderException e) {
        s_logger.error("Unable to create KeyFactory:" + e.getMessage());
    }
    return keyFactory;
}
Also used : NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) NoSuchProviderException(java.security.NoSuchProviderException) KeyFactory(java.security.KeyFactory) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Aggregations

BouncyCastleProvider (org.bouncycastle.jce.provider.BouncyCastleProvider)34 IOException (java.io.IOException)12 KeyPair (java.security.KeyPair)9 X509Certificate (java.security.cert.X509Certificate)9 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)8 KeyPairGenerator (java.security.KeyPairGenerator)6 KeyStore (java.security.KeyStore)6 SecureRandom (java.security.SecureRandom)5 Date (java.util.Date)5 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)5 File (java.io.File)4 FileOutputStream (java.io.FileOutputStream)4 SecretKey (javax.crypto.SecretKey)4 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)4 Before (org.junit.Before)4 KeyStoreException (java.security.KeyStoreException)3 NoSuchProviderException (java.security.NoSuchProviderException)3 CertificateException (java.security.cert.CertificateException)3 X500Name (org.bouncycastle.asn1.x500.X500Name)3 Test (org.junit.Test)3