Example usage for java.security Security addProvider

List of usage examples for java.security Security addProvider

Introduction

In this page you can find the example usage for java.security Security addProvider.

Prototype

public static int addProvider(Provider provider) 

Source Link

Document

Adds a provider to the next position available.

Usage

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    Security.addProvider(new BouncyCastleProvider());
    SecureRandom random = new SecureRandom();
    IvParameterSpec ivSpec = createCtrIvForAES(1, random);
    Key key = createKeyForAES(256, random);
    Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding", "BC");
    String input = "www.java2s.com";
    Mac mac = Mac.getInstance("DES", "BC");
    byte[] macKeyBytes = "12345678".getBytes();
    Key macKey = new SecretKeySpec(macKeyBytes, "DES");
    System.out.println("input : " + input);

    // encryption step
    cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
    byte[] cipherText = new byte[cipher.getOutputSize(input.length() + mac.getMacLength())];
    int ctLength = cipher.update(input.getBytes(), 0, input.length(), cipherText, 0);
    mac.init(macKey);//  w  ww  .j a v a 2 s .  co m
    mac.update(input.getBytes());
    ctLength += cipher.doFinal(mac.doFinal(), 0, mac.getMacLength(), cipherText, ctLength);
    System.out.println("cipherText : " + new String(cipherText));

    // decryption step
    cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);
    byte[] plainText = cipher.doFinal(cipherText, 0, ctLength);
    int messageLength = plainText.length - mac.getMacLength();

    mac.init(macKey);
    mac.update(plainText, 0, messageLength);

    byte[] messageHash = new byte[mac.getMacLength()];
    System.arraycopy(plainText, messageLength, messageHash, 0, messageHash.length);

    System.out.println("plain : " + new String(plainText) + " verified: "
            + MessageDigest.isEqual(mac.doFinal(), messageHash));
}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    KeyPair pair = generateRSAKeyPair();
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    bOut.write(generateV1Certificate(pair).getEncoded());
    bOut.close();//w  w w.j av  a 2  s . c  o  m
    InputStream in = new ByteArrayInputStream(bOut.toByteArray());
    CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC");
    X509Certificate x509Cert = (X509Certificate) fact.generateCertificate(in);
    System.out.println("issuer: " + x509Cert.getIssuerX500Principal());
}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    KeyPair pair = generateRSAKeyPair();

    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    bOut.write(generateV1Certificate(pair).getEncoded());
    bOut.close();//  w w  w  . j av  a2  s .  c o m

    InputStream in = new ByteArrayInputStream(bOut.toByteArray());

    CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC");

    X509Certificate x509Cert;
    Collection collection = new ArrayList();

    while ((x509Cert = (X509Certificate) fact.generateCertificate(in)) != null) {
        collection.add(x509Cert);
    }

    Iterator it = collection.iterator();
    while (it.hasNext()) {
        System.out.println("version: " + ((X509Certificate) it.next()).getVersion());
    }
}

From source file:net.maritimecloud.identityregistry.McIdregApplication.java

public static void main(String[] args) {
    // Set awt to be headless to avoid issues when scaling images (logos)
    System.setProperty("java.awt.headless", "true");
    // Set Bouncy Castle as Provider, used for Certificates.
    Security.addProvider(new BouncyCastleProvider());
    SpringApplication.run(McIdregApplication.class, args);
}

From source file:hd3gtv.embddb.MainClass.java

public static void main(String[] args) throws Exception {
    Security.addProvider(new BouncyCastleProvider());

    PoolManager poolmanager = new PoolManager("test");
    poolmanager.startLocalServers();//www .ja v a 2 s . co m

    // TODO manage white/black range addr list for autodiscover

    Thread.sleep(50);

    Properties conf = new Properties();
    conf.load(FileUtils.openInputStream(new File("conf.properties")));

    poolmanager.setBootstrapPotentialNodes(
            importConf(poolmanager, conf, poolmanager.getProtocol().getDefaultTCPPort()));
    poolmanager.connectToBootstrapPotentialNodes("Startup");

    Thread.sleep(50);

    poolmanager.startConsole();
}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA", "BC");
    kpGen.initialize(1024, new SecureRandom());

    KeyPair pair = kpGen.generateKeyPair();

    PKCS10CertificationRequest request = generateRequest(pair);

    PEMWriter pemWrt = new PEMWriter(new OutputStreamWriter(System.out));
    pemWrt.writeObject(request);//from  w  w  w .j  a  va2s. c  o  m
    pemWrt.close();
}

From source file:MainClass.java

public static void main(String args[]) {
    MessageDigest algorithm = null;
    Security.addProvider(new MyProvider());
    try {/*from ww  w . j  a  v a 2 s  . co  m*/
        algorithm = MessageDigest.getInstance("CRC32");
    } catch (NoSuchAlgorithmException e) {
        System.err.println("Invalid algorithm");
        System.exit(-1);
    }
    int argsLength = args.length;
    for (int i = 0; i < argsLength; i++) {
        String digest = computeDigest(algorithm, args[i]);
        System.out.println(args[i] + " : " + digest);

    }
}

From source file:no.digipost.api.client.eksempelkode.FallbackTilPrintEksempel.java

public static void main(final String[] args) {

    // 1. For  kunne kryptere brevet som skal sendes trenger vi
    // BouncyCastle
    Security.addProvider(new BouncyCastleProvider());

    // 2. Vi leser inn sertifikatet du har knyttet til din Digipost-konto (i
    // .p12-formatet)
    InputStream sertifikatInputStream = lesInnSertifikat();

    // 3. Vi oppretter en DigipostClient
    DigipostClient client = new DigipostClient(ApiFlavor.STEPWISE_REST, "https://api.digipost.no",
            AVSENDERS_KONTOID, sertifikatInputStream, SERTIFIKAT_PASSORD);

    // 4. Vi oppretter et fdselsnummerobjekt som skal brukes til 
    // identifisere mottaker i Digipost
    PersonalIdentificationNumber pin = new PersonalIdentificationNumber("26079833787");

    // 5. Vi oppretter en forsendelse for sending av brevet i Digipost og med adresseinformasjon som vil
    // benyttes dersom mottaker ikke er Digipostbruker
    Document primaryDocument = new Document(UUID.randomUUID().toString(), "Dokumentets emne", PDF, null,
            new SmsNotification(), null, PASSWORD, NORMAL);

    PrintDetails printDetails = new PrintDetails(
            new PrintRecipient("Mottakers navn", new NorwegianAddress("postnummer", "Mottakers poststed")),
            new PrintRecipient("Avsenders navn", new NorwegianAddress("postnummer", "Avsenders poststed")), B,
            MONOCHROME, RETURN_TO_SENDER);
    String dinForsendelseId = UUID.randomUUID().toString();
    Message message = newMessage(dinForsendelseId, primaryDocument)
            .recipient(new MessageRecipient(pin, printDetails)).build();

    // 7. Forelpig sttter Digipost kun  sende krypterte brev til print. 
    // spesifisere PreEncrypt gjr at klientbiblioteket krypterer filen for
    // deg fr den oversendes Digipost.
    primaryDocument.setPreEncrypt();//ww w  . j  ava  2  s  . c  o m

    // 8. Vi oppretter forsendelsen, legger til innhold og alternativt
    // innhold for print, og til slutt sender forsendelsen. Alt hndteres
    // av klientbiblioteket.
    client.createMessage(message).addContent(primaryDocument, getMessageContent(), getPrintContent()).send();

}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    KeyPair pair = generateRSAKeyPair();
    X509Certificate cert = generateV3Certificate(pair);
    cert.checkValidity(new Date());
    cert.verify(cert.getPublicKey());//  w w w .j  av  a  2s.co  m
}

From source file:org.wildfly.security.tool.ElytronTool.java

/**
 * Main method to call from scripts./*w  w  w .  j a va 2 s . c  om*/
 *
 * @param args parameters to pass farther. The first parameter is name or alias of the command.
 */
public static void main(String[] args) {

    Security.addProvider(new WildFlyElytronProvider());

    ElytronTool tool = new ElytronTool();
    if (args != null && args.length > 0) {
        if (args[0].startsWith("{")) {
            tool.scriptName = args[0].substring(1, args[0].indexOf('}'));
            args[0] = args[0].substring(args[0].indexOf('}') + 1);
        }
        Command command = tool.findCommand(args[0]);
        if (command != null && tool.scriptName != null) {
            command.setToolCommand(tool.scriptName);
        }
        String[] newArgs = new String[args.length - 1];
        System.arraycopy(args, 1, newArgs, 0, args.length - 1);
        if (command != null && newArgs.length > 0) {
            try {
                command.execute(newArgs);
                System.exit(command.getStatus());
            } catch (Exception e) {
                if (e instanceof AlreadySelectedException) {
                    Option option = ((AlreadySelectedException) e).getOption();
                    System.err.println(ElytronToolMessages.msg.longOptionDescription(option.getOpt(),
                            option.getLongOpt()));
                }
                if (command.isEnableDebug()) {
                    System.err.println(ElytronToolMessages.msg.commandExecuteException());
                    e.printStackTrace(System.err);
                } else {
                    if (e.getLocalizedMessage() != null && (e.getLocalizedMessage().startsWith("ELYTOOL")
                            || e instanceof org.apache.commons.cli.ParseException)) {
                        System.err.println(ElytronToolMessages.msg.commandExecuteException());
                        System.err.println(e.getLocalizedMessage());
                    } else {
                        System.err.println(ElytronToolMessages.msg.commandExecuteExceptionNoDebug());
                    }
                }
                System.exit(command.getStatus());
            }
        } else if ("--help".equals(args[0]) || "-h".equals(args[0])) {
            tool.generalHelp();
        } else if (command != null) {
            command.help();
        } else {
            if (args[0].trim().isEmpty() && newArgs.length == 0) {
                tool.generalHelp();
            } else {
                System.err.println(ElytronToolMessages.msg.commandOrAliasNotFound(args[0]));
                System.exit(ElytronToolExitStatus_unrecognizedCommand);
            }
        }
    } else {
        // no arguments supplied, print general help message and exist.
        tool.generalHelp();
    }
}