Example usage for org.bouncycastle.jce.provider BouncyCastleProvider BouncyCastleProvider

List of usage examples for org.bouncycastle.jce.provider BouncyCastleProvider BouncyCastleProvider

Introduction

In this page you can find the example usage for org.bouncycastle.jce.provider BouncyCastleProvider BouncyCastleProvider.

Prototype

public BouncyCastleProvider() 

Source Link

Document

Construct a new provider.

Usage

From source file:com.kixeye.chassis.transport.WebSocketTransportTest.java

License:Apache License

@Test
public void testWebSocketServiceWithJsonWithPskEncryption() throws Exception {
    // create AES shared key cipher
    Security.addProvider(new BouncyCastleProvider());
    KeyGenerator kgen = KeyGenerator.getInstance("AES", "BC");
    kgen.init(128);//from   www  .  j  a v  a 2  s .c  om
    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();
        }
    }
}

From source file:com.launchkey.example.cli.LaunchKeySdkDemoApp.java

License:Open Source License

public static void main(String[] args) {

    String privateKeyFile = null;
    try {//from   w  ww . j a  v a 2  s  .  c o m
        JSAP jsap = getJSAP();

        JSAPResult commandLine = jsap.parse(args);
        String rocketKey = commandLine.getString("rocket_key");
        String secretKey = commandLine.getString("secret_key");
        privateKeyFile = commandLine.getString("private_key_file");

        if (commandLine.getBoolean("help") || rocketKey == null || secretKey == null
                || privateKeyFile == null) {
            printHelp(jsap);
            return;
        }

        LaunchKeyClient client = LaunchKeyClient.factory(Long.parseLong(rocketKey), secretKey,
                readFile(privateKeyFile), new BouncyCastleProvider());

        String command = commandLine.getString("command");
        String[] commandOptions = commandLine.getStringArray("command-options");
        if (command.equalsIgnoreCase("login")) {
            if (commandOptions.length == 1) {
                handleLogin(commandOptions[0], client.auth());
            } else {
                System.out.println();
                System.out.println(
                        "The login command takes a single command option which is the username with which to perform a login");
                printHelp(jsap);
                System.out.println();
            }
        } else if (command.equalsIgnoreCase("authorized")) {
            if (commandOptions.length == 1) {
                Boolean authorized;
                try {
                    AuthResponse authResponse = client.auth().getAuthResponse(commandOptions[0]);
                    authorized = authResponse.isAuthorized();
                } catch (ExpiredAuthRequestException e) { // If the auth has an expired status, it has been logged out
                    authorized = false;
                }
                System.out.println();
                System.out.println("User is " + (authorized ? "still" : "not") + " authorized");
                System.out.println();
            } else {
                System.out.println();
                System.out.println(
                        "The authorized command takes a single command option which is the Auth Request value returned from a login command");
                printHelp(jsap);
                System.out.println();
            }
        } else if (command.equalsIgnoreCase("logout")) {
            if (commandOptions.length == 1) {
                client.auth().logout(commandOptions[0]);
                System.out.println();
                System.out.println("User is logged out.");
                System.out.println();
            } else {
                System.out.println();
                System.out.println(
                        "The authorized command takes a single command option which is the Auth Request value returned from a login command");
                printHelp(jsap);
                System.out.println();
            }
        } else if (command.equalsIgnoreCase("white-label-user-pair")) {
            if (commandOptions.length == 1) {
                handleWhiteLabelPairUser(commandOptions[0], client.whiteLabel());
            } else {
                System.out.println();
                System.out.println(
                        "white-label-user-pair command requires a single argument of the unique ID for your application");
                printHelp(jsap);
                System.out.println();
            }
        } else {
            System.out.println("Unknown command \"" + command + "\"");
            printHelp(jsap);
        }

    } catch (IOException ioe) {
        System.out.println();
        System.out.println("There was an error reading the private key file: " + privateKeyFile);
        System.out.println();
    } catch (LaunchKeyException e) {
        System.out.println();
        System.out.println("There was an error executing your command: " + e.getMessage());
        System.out.println();
    } catch (InterruptedException e) {
        System.out.println();
        System.out.println("The command was interrupted: " + e.getMessage());
        System.out.println();
    } catch (JSAPException e) {
        System.out.println();
        System.out.println("Unexpected parse exception: " + e.getMessage());
        System.out.println();
    }
}

From source file:com.launchkey.example.springmvc.AuthManager.java

License:Open Source License

@Autowired
public AuthManager(LaunchKeyConfig config) throws ConfigurationException, IOException {
    final Long rocketKey = config.getRocketKey();
    final String secretKey = config.getSecretKey();
    final String privateKeyLocation = config.getPrivateKeyLocation();

    boolean halt = false;
    if (rocketKey == null) {
        log.error("launchkey.rocket-key property not provided");
        halt = true;/* w ww .  j a v  a2  s  .c  o  m*/
    }
    if (secretKey == null) {
        log.error("launchkey.secret-key property not provided");
        halt = true;
    }
    if (privateKeyLocation == null) {
        log.error("launchkey.private-key-location property not provided");
        halt = true;
    }
    if (halt)
        throw new ConfigurationException("Missing required LaunchKey configuration");

    BufferedReader br = new BufferedReader(new FileReader(privateKeyLocation));
    StringBuilder sb = new StringBuilder();
    try {
        String line = br.readLine();

        while (line != null) {
            sb.append(line);
            sb.append("\n");
            line = br.readLine();
        }
    } finally {
        br.close();
    }
    String privateKey = sb.toString();
    LaunchKeyClient launchKeyClient = LaunchKeyClient.factory(rocketKey, secretKey, privateKey,
            new BouncyCastleProvider());
    this.authService = launchKeyClient.auth();
    this.sessionAuthenticationMap = Collections.synchronizedMap(new HashMap<String, Boolean>());
    this.sessionAuthRequestMap = new ConcurrentHashMap<String, String>();
    this.userHashSessionMap = new ConcurrentHashMap<String, List<String>>();
}

From source file:com.launchkey.sdk.LaunchKeyClientTest.java

License:Open Source License

@Before
public void setUp() throws Exception {
    provider = new BouncyCastleProvider();
    auth = mock(AuthService.class);
    whiteLabel = mock(WhiteLabelService.class);
    client = new LaunchKeyClient(auth, whiteLabel);
}

From source file:com.leahscape.passwordmaker.Hasher.java

License:Open Source License

public Hasher() {
    Security.addProvider(new BouncyCastleProvider());
    bc = Security.getProvider("BC");
    algorithms.put("MD4", "MD4");
    algorithms.put("HMAC-MD4", "HMAC-MD4");
    algorithms.put("MD5", "MD5");
    algorithms.put("MD5 Version 0.6", "MD5");
    algorithms.put("HMAC-MD5", "HMAC-MD5");
    algorithms.put("HMAC-MD5 Version 0.6", "HMAC-MD5");
    algorithms.put("SHA1", "SHA1");
    algorithms.put("HMAC-SHA1", "HMAC-SHA1");
    algorithms.put("SHA-256", "SHA-256");
    algorithms.put("HMAC-SHA-256", "HMAC-SHA256");
    algorithms.put("RIPEMD-160", "RIPEMD160");
    algorithms.put("HMAC-RIPEMD-160", "HMAC-RIPEMD160");
}

From source file:com.liferay.amazontools.AMIBuilder.java

License:Open Source License

public AMIBuilder(String baseDirName, String imageName, boolean output, String propertiesFileName)
        throws Exception {

    super(propertiesFileName);

    _baseDirName = baseDirName;//from   w  ww.j  a  v a  2s  . c o m
    _imageName = imageName;
    _output = output;

    Security.addProvider(new BouncyCastleProvider());

    _provisioners = getProvisioners(properties);
}

From source file:com.lightszentip.module.security.password.PasswordModuleImpl.java

License:Apache License

/**
 * Constructor Set attribute for password encoding and cryption, for
 * generate and check - you need the same attributes
 * /*from   w  w w  .  j a  v a  2  s  . com*/
 * @param secretId
 * @param secretSaltPw
 * @param secureSaltKey
 * @param typeEncrypt
 * @param typeEncod
 * @param randomPasswordLength
 */
public PasswordModuleImpl(String secretId, String secretSaltPw, String secureSaltKey,
        EncryptionType typeEncrypt, AlgorithmType typeEncod, int randomPasswordLength) {
    this.secretId = secretId;
    this.secretSaltPw = secretSaltPw;
    this.typeEncod = typeEncod;
    this.typeEncrypt = typeEncrypt;
    this.randomPasswordLength = randomPasswordLength;
    this.key = secureSaltKey + this.secretId;
    if (this.key.length() % 4 != 0) {
        throw new IllegalArgumentException("The length for secureSaltKey and secretId is false");
    }
    Security.addProvider(new BouncyCastleProvider());
}

From source file:com.linecorp.armeria.internal.crypto.BouncyCastleKeyFactoryProviderTest.java

License:Apache License

/**
 * Tests if everything works even if Bouncy Castle is loaded already.
 *///from   w  w w . j  a  va  2 s.  c om
@Test
public void bouncyCastlePreInstalled() {
    Assume.assumeTrue(Arrays.stream(Security.getProviders())
            .noneMatch(p -> BouncyCastleProvider.PROVIDER_NAME.equals(p.getName())));

    Security.addProvider(new BouncyCastleProvider());
    try {
        BouncyCastleKeyFactoryProvider.call(this::loadPkcs5);
        BouncyCastleKeyFactoryProvider.call(this::loadPkcs8);
    } finally {
        Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME);
    }
}

From source file:com.linkedin.kafka.clients.utils.tests.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//from   ww  w  . java  2s . c o  m
 * @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);
    }
}

From source file:com.maiereni.host.web.util.impl.BouncyCastleEncryptorImpl.java

License:Apache License

BouncyCastleEncryptorImpl(@Nonnull final X509Certificate certificate, @Nonnull final PrivateKey key) {
    this.certificate = certificate;
    this.key = key;
    this.base64 = new Base64();
    Security.addProvider(new BouncyCastleProvider());
}