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:dam.asimetrico.SignTest.java

public static void main(String[] args) throws FileNotFoundException {

    String nombre = "albertoastudillo";
    try {//from w  w  w . j  a va 2  s  . c  o m
        // Anadir provider JCE (provider por defecto no soporta RSA)
        Security.addProvider(new BouncyCastleProvider()); // Cargar el provider BC
        //Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
        Cipher cifrador = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");

        // Crear KeyFactory (depende del provider) usado para las transformaciones de claves*/
        KeyFactory keyFactoryRSA = KeyFactory.getInstance("RSA", "BC"); // Hace uso del provider BC
        //*** 4 Recuperar clave PUBLICA del fichero */
        // 4.1 Leer datos binarios x809
        byte[] bufferPub = new byte[5000];
        FileInputStream in = new FileInputStream(nombre + ".publica");
        DataInputStream d = new DataInputStream(in);

        int charsPub = in.read(bufferPub, 0, 5000);
        in.close();

        byte[] bufferPub2 = new byte[charsPub];
        System.arraycopy(bufferPub, 0, bufferPub2, 0, charsPub);

        // 4.2 Recuperar clave publica desde datos codificados en formato X509
        X509EncodedKeySpec clavePublicaSpec = new X509EncodedKeySpec(bufferPub2);
        PublicKey clavePublica2 = keyFactoryRSA.generatePublic(clavePublicaSpec);

        // PASO 3b: Poner cifrador en modo DESCIFRADO
        // 2 Recuperar clave Privada del fichero */
        // 2.1 Leer datos binarios PKCS8
        byte[] bufferPriv = new byte[5000];
        in = new FileInputStream(nombre + ".privada");
        int chars = in.read(bufferPriv, 0, 5000);
        in.close();

        byte[] bufferPriv2 = new byte[chars];
        System.arraycopy(bufferPriv, 0, bufferPriv2, 0, chars);

        // 2.2 Recuperar clave privada desde datos codificados en formato PKCS8
        PKCS8EncodedKeySpec clavePrivadaSpec = new PKCS8EncodedKeySpec(bufferPriv2);

        PrivateKey clavePrivada2 = keyFactoryRSA.generatePrivate(clavePrivadaSpec);

        Signature sign = Signature.getInstance("SHA256WithRSA");
        sign.initSign(clavePrivada2);
        sign.update("hola".getBytes());
        byte[] firma = sign.sign();

        sign.initVerify(clavePublica2);
        sign.update("hola".getBytes());
        System.out.println(sign.verify(firma));

    } catch (Exception ex) {
        Logger.getLogger(CifrarRSAFicheros.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:dao.dslam.impl.gpon.huawei.HuaweiGponDslamVivo1IT.java

@BeforeClass
public static void setUpClass() {
    BouncyCastleProvider bouncyCastleProvider = new BouncyCastleProvider();
    Security.insertProviderAt(bouncyCastleProvider, 1);
    try {/* w  w w .j ava  2s .  com*/
        cust = (EfikaCustomer) new JacksonMapper(EfikaCustomer.class).deserialize("{"
                + "   \"designador\":\"SPO-8152TQTV1H-013\"," + "   \"instancia\":\"110008450928008\","
                + "   \"designadorAcesso\":\"SPO-30128377-069\"," + "   \"designadorTv\":null,"
                + "   \"rede\":{" + "      \"tipo\":\"GPON\"," + "      \"origem\":\"ONLINE\","
                + "      \"planta\":\"VIVO1\"," + "      \"ipDslam\":\"10.58.238.122\","
                + "      \"vendorDslam\":\"HUAWEI TECHNOLOGIES\"," + "      \"modeloDslam\":\"MA5600T\","
                + "      \"idOnt\":\"0004430124\"," + "      \"terminal\":\"1184509280\","
                + "      \"ipMulticast\":null," + "      \"nrc\":null," + "      \"slot\":6,"
                + "      \"porta\":5," + "      \"sequencial\":19," + "      \"logica\":19,"
                + "      \"rin\":63," + "      \"vlanVoip\":3004," + "      \"vlanVod\":3001,"
                + "      \"vlanMulticast\":3001," + "      \"cvlan\":2011," + "      \"bhs\":true" + "   },"
                + "   \"redeExterna\":{" + "      \"tipo\":null," + "      \"origem\":null,"
                + "      \"planta\":null," + "      \"splitter1n\":null," + "      \"splitter2n\":null,"
                + "      \"caboAlim\":null," + "      \"fibra1n\":null," + "      \"fibra2n\":null" + "   },"
                + "   \"servicos\":{" + "      \"origem\":null," + "      \"velDown\":204800,"
                + "      \"velUp\":102400," + "      \"tipoTv\":null," + "      \"tipoLinha\":\"SIP\"" + "   },"
                + "   \"linha\":{" + "      \"tipo\":null," + "      \"dn\":null," + "      \"central\":null"
                + "   }," + "   \"radius\":{" + "      \"status\":null," + "      \"armario\":null,"
                + "      \"rin\":null," + "      \"velocidade\":null," + "      \"ipFixo\":null,"
                + "      \"profile\":null," + "      \"porta\":null," + "      \"isIpFixo\":null" + "   },"
                + "   \"asserts\":[" + "      {" + "         \"asserts\":\"CIRCUITO_ATIVO\","
                + "         \"value\":true," + "         \"creationDate\":1545167857433" + "      },"
                + "      {" + "         \"asserts\":\"DIVERGENCIA_TBS_RADIUS\"," + "         \"value\":false,"
                + "         \"creationDate\":1545167857433" + "      }," + "      {"
                + "         \"asserts\":\"HAS_BLOQUEIO_RADIUS\"," + "         \"value\":false,"
                + "         \"creationDate\":1545167857433" + "      }" + "   ]," + "   \"eventos\":[" + ""
                + "   ]" + "}");
    } catch (Exception e) {
    }
    instance = new Huawei5800GponDlamVivo1(cust.getRede().getIpDslam());
    i = cust.getRede();
}

From source file:dao.dslam.impl.login.Login1023ComJump.java

@Override
public void conectar(Conector css) throws Exception {

    this.cs = (ConsultaDslamVivo1) css;

    try {//from www  .java2 s  . com
        BouncyCastleProvider bouncyCastleProvider = new BouncyCastleProvider();
        Security.insertProviderAt(bouncyCastleProvider, 2);
        jsch = new JSch();
        session = jsch.getSession("efika", "10.18.81.96", 22);
        session.setPassword("Vivo@2018");

        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);

        session.connect();
    } catch (Exception e) {
        e.printStackTrace();
        throw new FalhaJumpAccessEsception();
    }

    try {
        String telnet = "telnet " + cs.dslam.getIpDslam() + " 1023";

        cs.channel = session.openChannel("shell");

        cs.out = new PrintWriter(cs.channel.getOutputStream(), false);
        cs.in = new BufferedReader(new InputStreamReader(cs.channel.getInputStream()));

        cs.channel.connect();
        Thread.sleep(1000);

        cs.out.print(telnet + "\r");
        cs.out.flush();
        Thread.sleep(7000);
        cs.out.print("\r");
        cs.out.flush();
        Thread.sleep(3000);
        cs.out.print("Y\r");
        cs.out.flush();
        Thread.sleep(4000);
        cs.out.print(this.cs.dslam.getCredencial().getLogin() + "\r");
        cs.out.flush();
        Thread.sleep(1000);
        cs.out.print(this.cs.dslam.getCredencial().getPass() + "\r");
        cs.out.flush();
        Thread.sleep(4500);
    } catch (Exception e) {
        e.printStackTrace();
        throw new SemGerenciaException();
    }
}

From source file:dao.dslam.impl.login.LoginComJump.java

@Override
public void conectar(Conector css) throws Exception {

    this.cs = (ConsultaDslamVivo1) css;

    try {//w  ww.  j a  v  a  2 s.  co  m
        BouncyCastleProvider bouncyCastleProvider = new BouncyCastleProvider();
        Security.insertProviderAt(bouncyCastleProvider, 2);
        jsch = new JSch();
        session = jsch.getSession("efika", "10.18.81.96", 22);
        session.setPassword("Vivo@2018");

        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);

        session.connect();
    } catch (Exception e) {
        e.printStackTrace();
        throw new FalhaJumpAccessEsception();
    }

    try {
        String telnet = "telnet " + cs.dslam.getIpDslam();

        cs.channel = session.openChannel("shell");

        cs.out = new PrintWriter(cs.channel.getOutputStream(), false);
        cs.in = new BufferedReader(new InputStreamReader(cs.channel.getInputStream()));

        cs.channel.connect();
        Thread.sleep(1000);

        cs.out.print(telnet + "\r");
        cs.out.flush();
        Thread.sleep(5000);
        cs.out.print(this.cs.dslam.getCredencial().getLogin() + "\r");
        cs.out.flush();
        Thread.sleep(3500);
        cs.out.print(this.cs.dslam.getCredencial().getPass() + "\r");
        cs.out.flush();
        Thread.sleep(2000);
    } catch (Exception e) {
        e.printStackTrace();
        throw new SemGerenciaException();
    }
}

From source file:dao.dslam.impl.login.LoginComJumpMetalico.java

@Override
public void conectar(Conector css) throws Exception {

    this.cs = (ConsultaDslamVivo1) css;

    try {//from  w w w  .  j  a v a2s  .  com
        BouncyCastleProvider bouncyCastleProvider = new BouncyCastleProvider();
        Security.insertProviderAt(bouncyCastleProvider, 2);
        jsch = new JSch();
        session = jsch.getSession("efika", "10.18.81.96", 22);
        session.setPassword("Vivo@2018");

        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);

        session.connect();
    } catch (Exception e) {
        e.printStackTrace();
        throw new FalhaJumpAccessEsception();
    }

    try {
        String telnet = "telnet " + cs.dslam.getIpDslam();

        cs.channel = session.openChannel("shell");

        cs.out = new PrintWriter(cs.channel.getOutputStream(), false);
        cs.in = new BufferedReader(new InputStreamReader(cs.channel.getInputStream()));

        cs.channel.connect();
        Thread.sleep(1000);

        cs.out.print(telnet + "\r");
        cs.out.flush();
        Thread.sleep(3000);
        if (TratativaRetornoUtil.tratHuawei(cs.getRetorno(), "Connected")
                .contains("Parmetro no encontrado")) {
            Thread.sleep(5000);
            if (TratativaRetornoUtil.tratHuawei(cs.getRetorno(), "Connected")
                    .contains("Parmetro no encontrado")) {
                throw new SemGerenciaException();
            }
        }
        cs.out.print(this.cs.dslam.getCredencial().getLogin() + "\r");
        cs.out.flush();
        Thread.sleep(2500);
        cs.out.print(this.cs.dslam.getCredencial().getPass() + "\r");
        cs.out.flush();
        Thread.sleep(2000);

        if (!TratativaRetornoUtil.tratHuawei(cs.getRetorno(), "Username or password invalid").contains("enc")) {
            cs.out.print(Credencial.VIVO1.getLogin() + "\r");
            cs.out.flush();
            Thread.sleep(2500);
            cs.out.print(Credencial.VIVO1.getPass() + "\r");
            cs.out.flush();
            Thread.sleep(2000);
        }

    } catch (Exception e) {
        e.printStackTrace();
        throw new SemGerenciaException();
    }

}

From source file:de.alpharogroup.crypto.key.KeyEncryptDecryptorTest.java

License:Open Source License

/**
 * Test encrypt and decrypt with {@link PublicKeyEncryptor#encrypt(byte[])} and
 * {@link PrivateKeyDecryptor#decrypt(byte[])} loaded from pem files.
 *
 * @throws Exception/*from   ww w .ja  va 2s.c  o m*/
 *             is thrown if any security exception occured.
 */
@Test
public void testEncryptDecryptPemFiles() throws Exception {
    final String test = "Lorem ipsum dolor sit amet, consetetur sadipscing elitr,;-)";
    final byte[] testBytes = test.getBytes("UTF-8");

    final File keyPemDir = new File(PathFinder.getSrcTestResourcesDir(), "pem");
    final File publickeyPemFile = new File(keyPemDir, "public.pem");
    final File privatekeyPemFile = new File(keyPemDir, "private.pem");

    Security.addProvider(new BouncyCastleProvider());
    final PrivateKey privateKey = PrivateKeyReader.readPemPrivateKey(privatekeyPemFile, SecurityProvider.BC);

    final PublicKey publicKey = PublicKeyReader.readPemPublicKey(publickeyPemFile, SecurityProvider.BC);

    final CryptModel<Cipher, PublicKey> encryptModel = CryptModel.<Cipher, PublicKey>builder().key(publicKey)
            .algorithm(KeyPairWithModeAndPaddingAlgorithm.RSA_ECB_OAEPWithSHA256AndMGF1Padding).build();

    final CryptModel<Cipher, PrivateKey> decryptModel = CryptModel.<Cipher, PrivateKey>builder().key(privateKey)
            .algorithm(KeyPairWithModeAndPaddingAlgorithm.RSA_ECB_OAEPWithSHA256AndMGF1Padding).build();

    final PublicKeyEncryptor encryptor = new PublicKeyEncryptor(encryptModel);
    final PrivateKeyDecryptor decryptor = new PrivateKeyDecryptor(decryptModel);

    byte[] encrypted = encryptor.encrypt(testBytes);

    byte[] decrypted = decryptor.decrypt(encrypted);

    String decryptedString = new String(decrypted, "UTF-8");
    logger.debug(decryptedString);
    AssertJUnit.assertTrue("String before encryption is not equal after decryption.",
            test.equals(decryptedString));
    for (int i = 0; i < 100; i++) {
        encrypted = encryptor.encrypt(testBytes);
        decrypted = decryptor.decrypt(encrypted);

        decryptedString = new String(decrypted, "UTF-8");
        AssertJUnit.assertTrue("String before encryption is not equal after decryption.",
                test.equals(decryptedString));
        logger.debug(decryptedString);
    }
}

From source file:de.alpharogroup.crypto.key.KeyHexEncryptDecryptorTest.java

License:Open Source License

/**
 * Sets up method will be invoked before every unit test method in this class.
 *
 * @throws Exception//ww w .  j ava2 s.c  om
 *             the exception
 */
@BeforeMethod
protected void setUp() throws Exception {
    Security.addProvider(new BouncyCastleProvider());
}

From source file:de.alpharogroup.crypto.key.PrivateKeyExtensionsTest.java

License:Open Source License

/**
 * Test method for {@link PrivateKeyExtensions#generatePublicKey(PrivateKey)}
 *
 * @throws Exception/* w w w.j  av  a2s.  co  m*/
 *             is thrown if an security error occurs
 */
@Test
public void testGeneratePublicKey() throws Exception {

    final File keyPemDir = new File(PathFinder.getSrcTestResourcesDir(), "pem");
    final File publickeyPemFile = new File(keyPemDir, "public.pem");
    final File privatekeyPemFile = new File(keyPemDir, "private.pem");

    Security.addProvider(new BouncyCastleProvider());
    final PrivateKey privateKey = PrivateKeyReader.readPemPrivateKey(privatekeyPemFile, SecurityProvider.BC);

    final PublicKey expected = PublicKeyReader.readPemPublicKey(publickeyPemFile, SecurityProvider.BC);

    final PublicKey actual = PrivateKeyExtensions.generatePublicKey(privateKey);
    AssertJUnit.assertEquals(expected, actual);
}

From source file:de.alpharogroup.crypto.key.PublicKeyExtensionsTest.java

License:Open Source License

/**
 * Test method for {@link PublicKeyExtensions#toBase64(PublicKey)}
 *
 * @throws Exception//from  ww w  . java2 s.  c  om
 *             is thrown if an security error occurs
 */
@Test
public void testToBase64() throws Exception {
    final File keyPemDir = new File(PathFinder.getSrcTestResourcesDir(), "pem");
    final File publickeyPemFile = new File(keyPemDir, "public.pem");

    Security.addProvider(new BouncyCastleProvider());

    final PublicKey publicKey = PublicKeyReader.readPemPublicKey(publickeyPemFile, SecurityProvider.BC);

    final String base64 = PublicKeyExtensions.toBase64(publicKey);
    AssertJUnit.assertEquals(PUBLIC_KEY_BASE64_ENCODED, base64);
}

From source file:de.alpharogroup.mystic.crypt.actions.OpenPrivateKeyAction.java

License:Open Source License

private PrivateKey getPrivateKey(final File file) {
    PrivateKey privateKey = null;
    try {/*from   ww  w .j  av a  2  s  .com*/
        privateKey = PrivateKeyReader.readPrivateKey(file);

    } catch (NoSuchAlgorithmException | InvalidKeySpecException | NoSuchProviderException | IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    if (privateKey == null) {
        try {
            Security.addProvider(new BouncyCastleProvider());
            privateKey = PrivateKeyReader.readPemPrivateKey(file);
        } catch (final Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    return privateKey;
}