Example usage for java.security PublicKey getEncoded

List of usage examples for java.security PublicKey getEncoded

Introduction

In this page you can find the example usage for java.security PublicKey getEncoded.

Prototype

public byte[] getEncoded();

Source Link

Document

Returns the key in its primary encoding format, or null if this key does not support encoding.

Usage

From source file:MainClass.java

public static void main(String args[]) throws Exception {
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    FileInputStream in = new FileInputStream(args[0]);
    java.security.cert.Certificate c = cf.generateCertificate(in);
    in.close();/*from w w  w.j a v a 2  s  . c  o m*/

    X509Certificate t = (X509Certificate) c;
    System.out.println(t.getVersion());
    System.out.println(t.getSerialNumber().toString(16));
    System.out.println(t.getSubjectDN());
    System.out.println(t.getIssuerDN());
    System.out.println(t.getNotBefore());
    System.out.println(t.getNotAfter());
    System.out.println(t.getSigAlgName());
    byte[] sig = t.getSignature();
    System.out.println(new BigInteger(sig).toString(16));
    PublicKey pk = t.getPublicKey();
    byte[] pkenc = pk.getEncoded();
    for (int i = 0; i < pkenc.length; i++) {
        System.out.print(pkenc[i] + ",");
    }
}

From source file:MainClass.java

public static void main(String args[]) throws Exception {
    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    List mylist = new ArrayList();

    FileInputStream in = new FileInputStream(args[0]);
    Certificate c = cf.generateCertificate(in);
    mylist.add(c);/*from w w w. j a  v a 2s .co m*/

    CertPath cp = cf.generateCertPath(mylist);

    FileInputStream kin = new FileInputStream(args[0]);
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(kin, args[1].toCharArray());

    PKIXParameters params = new PKIXParameters(ks);
    params.setRevocationEnabled(false);

    CertPathValidator cpv = CertPathValidator.getInstance("PKIX");

    PKIXCertPathValidatorResult result = (PKIXCertPathValidatorResult) cpv.validate(cp, params);

    PublicKey pbk = result.getPublicKey();
    byte[] pkenc = pbk.getEncoded();
    BigInteger pk = new BigInteger(pkenc);
    System.out.println(pk.toString(16));

    TrustAnchor anc = result.getTrustAnchor();
    X509Certificate xc = anc.getTrustedCert();
    System.out.println(xc.getSubjectDN());
    System.out.println(xc.getIssuerDN());

}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    String algorithm = "DSA"; // or RSA, DH, etc.

    // Generate a 1024-bit Digital Signature Algorithm (DSA) key pair
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance(algorithm);
    keyGen.initialize(1024);//from  w  w  w. j a va  2  s.c o  m
    KeyPair keypair = keyGen.genKeyPair();
    PrivateKey privateKey = keypair.getPrivate();
    PublicKey publicKey = keypair.getPublic();

    byte[] privateKeyBytes = privateKey.getEncoded();
    byte[] publicKeyBytes = publicKey.getEncoded();
}

From source file:cn.lynx.emi.license.GenerateKeyPairs.java

public static void main(String[] args) throws NoSuchAlgorithmException {
    KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA");
    SecureRandom secrand = new SecureRandom();
    secrand.setSeed("cn.lynx.emi".getBytes());
    keygen.initialize(4096, secrand);//from  w w  w. ja  v  a2  s .  c o  m
    KeyPair keys = keygen.genKeyPair();

    PublicKey pubkey = keys.getPublic();
    PrivateKey prikey = keys.getPrivate();

    String myPubKey = Base64.encodeBase64String(pubkey.getEncoded());
    String myPriKey = Base64.encodeBase64String(prikey.getEncoded());
    System.out.println(prikey);
    System.out.println("pubKey=" + myPubKey);
    System.out.println("priKey=" + myPriKey);
}

From source file:MainClass.java

public static void main(String args[]) throws Exception {
    MainClass kpge = new MainClass();
    KeyPair kp = kpge.generateKeyPair(999);
    System.out.println("-- Public Key ----");
    PublicKey pubKey = kp.getPublic();
    System.out.println("   Algorithm=" + pubKey.getAlgorithm());
    System.out.println("   Encoded=" + pubKey.getEncoded());
    System.out.println("   Format=" + pubKey.getFormat());
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    String algorithm = "DSA"; // or RSA, DH, etc.

    // Generate a 1024-bit Digital Signature Algorithm (DSA) key pair
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance(algorithm);
    keyGen.initialize(1024);//from w w w . java 2 s  .  c  o m
    KeyPair keypair = keyGen.genKeyPair();
    PrivateKey privateKey = keypair.getPrivate();
    PublicKey publicKey = keypair.getPublic();

    byte[] privateKeyBytes = privateKey.getEncoded();
    byte[] publicKeyBytes = publicKey.getEncoded();

    KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
    EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
    PrivateKey privateKey2 = keyFactory.generatePrivate(privateKeySpec);

    EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKeyBytes);
    PublicKey publicKey2 = keyFactory.generatePublic(publicKeySpec);

    // The orginal and new keys are the same
    boolean same = privateKey.equals(privateKey2);
    same = publicKey.equals(publicKey2);
}

From source file:com.vimukti.accounter.developer.api.PublicKeyGenerator.java

/**
 * @param args//from www .ja  va  2  s . c  o m
 * @throws NoSuchProviderException
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 * @throws IOException
 * @throws CertificateException
 * @throws KeyStoreException
 * @throws UnrecoverableEntryException
 * @throws URISyntaxException
 */
public static void main(String[] args) throws KeyStoreException, NoSuchAlgorithmException, CertificateException,
        IOException, UnrecoverableEntryException {
    FileInputStream is = new FileInputStream(
            ServerConfiguration.getConfig() + File.separator + "license.keystore");
    KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
    String password = "liceseStorePassword";
    keystore.load(is, password.toCharArray());
    PrivateKeyEntry entry = (PrivateKeyEntry) keystore.getEntry("licenseAlias",
            new PasswordProtection(ServerConfiguration.getLicenseKeystorePWD().toCharArray()));
    Key key = entry.getPrivateKey();
    System.out.println((PrivateKey) key);
    PublicKey publicKey = entry.getCertificate().getPublicKey();
    System.out.println(publicKey);

    byte[] encoded = publicKey.getEncoded();
    byte[] encodeBase64 = Base64.encodeBase64(encoded);
    System.out.println("Public Key:" + new String(encodeBase64));

}

From source file:at.asitplus.regkassen.demo.RKSVCashboxSimulator.java

public static void main(String[] args) {
    try {/*from   w  w  w . j a  va  2  s.  c  o  m*/
        //IMPORTANT HINT REGARDING STRING ENCODING
        //in Java all Strings have UTF-8 as default encoding
        //therefore: there are only a few references to UTF-8 encoding in this demo code
        //however, if values are retrieved from a database or another program language is used, then one needs to
        //make sure that the UTF-8 encoding is correctly implemented

        //this demo cashbox does not implement error handling
        //it should only demonstrate the core elements of the RKSV and any boilerplate code is avoided as much as possible
        //if an error occurs, only the stacktraces are logged
        //obviously this needs to be adapted in a productive cashbox

        //----------------------------------------------------------------------------------------------------
        //basic inits
        //add bouncycastle provider
        Security.addProvider(new BouncyCastleProvider());

        //----------------------------------------------------------------------------------------------------
        //check if unlimited strength policy files are installed, they are required for strong crypto algorithms ==> AES 256
        if (!CryptoUtil.isUnlimitedStrengthPolicyAvailable()) {
            System.out.println(
                    "Your JVM does not provide the unlimited strength policy. However, this policy is required to enable strong cryptography (e.g. AES with 256 bits). Please install the required policy files.");
            System.exit(0);
        }

        //----------------------------------------------------------------------------------------------------
        //parse cmd line options
        Options options = new Options();

        // add CMD line options
        options.addOption("o", "output-dir", true,
                "specify base output directory, if none is specified, a new directory will be created in the current working directory");
        //options.addOption("i", "simulation-file-or-directory", true, "cashbox simulation (file) or multiple cashbox simulation files (directory), if none is specified the internal test suites will be executed (can also be considered as demo mode)");
        options.addOption("v", "verbose", false, "dump demo receipts to cmd line");
        options.addOption("c", "closed system", false, "simulate closed system");

        ///parse CMD line options
        CommandLineParser parser = new DefaultParser();
        CommandLine cmd = parser.parse(options, args);

        //setup inputs from cmd line
        //verbose
        VERBOSE = cmd.hasOption("v");
        CLOSED_SYSTEM = cmd.hasOption("c");

        //output directory
        String outputParentDirectoryString = cmd.getOptionValue("o");
        if (outputParentDirectoryString == null) {
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH-mm-ss");
            outputParentDirectoryString = "./CashBoxDemoOutput" + df.format(new Date());
        }
        File OUTPUT_PARENT_DIRECTORY = new File(outputParentDirectoryString);
        OUTPUT_PARENT_DIRECTORY.mkdirs();

        //----------------------------------------------------------------------------------------------------
        //external simulation runs... not implemented yet, currently only the internal test suites can be executed
        //String simulationFileOrDirectoryPath = cmd.getOptionValue("i");
        //handling of arbitrary input simulation files will be possible in 0.7
        //if (simulationFileOrDirectoryPath == null) {
        //} else {
        //                File simulationFileOrDirectory = new File(simulationFileOrDirectoryPath);
        //                cashBoxSimulationList = readCashBoxSimulationFromFile(simulationFileOrDirectory);
        //}

        List<CashBoxSimulation> cashBoxSimulationList = TestSuiteGenerator.getSimulationRuns();

        //setup simulation and execute
        int index = 1;
        for (CashBoxSimulation cashboxSimulation : cashBoxSimulationList) {
            System.out.println("Executing simulation run " + index + "/" + cashBoxSimulationList.size());
            System.out.println("Simulation run: " + cashboxSimulation.getSimulationRunLabel());
            index++;

            File testSetDirectory = new File(OUTPUT_PARENT_DIRECTORY,
                    cashboxSimulation.getSimulationRunLabel());
            testSetDirectory.mkdirs();

            CashBoxParameters cashBoxParameters = new CashBoxParameters();
            cashBoxParameters.setCashBoxId(cashboxSimulation.getCashBoxId());
            cashBoxParameters.setTurnOverCounterAESKey(
                    CryptoUtil.convertBase64KeyToSecretKey(cashboxSimulation.getBase64AesKey()));
            cashBoxParameters.setDepModul(new SimpleMemoryDEPModule());
            cashBoxParameters.setPrinterModule(new SimplePDFPrinterModule());
            cashBoxParameters.setCompanyID(cashboxSimulation.getCompanyID());

            //create pre-defined number of signature devices
            for (int i = 0; i < cashboxSimulation.getNumberOfSignatureDevices(); i++) {
                JWSModule jwsModule = new ManualJWSModule();
                SignatureModule signatureModule;
                if (!CLOSED_SYSTEM) {
                    signatureModule = new NEVER_USE_IN_A_REAL_SYSTEM_SoftwareCertificateOpenSystemSignatureModule(
                            RKSuite.R1_AT100, null);
                } else {
                    signatureModule = new NEVER_USE_IN_A_REAL_SYSTEM_SoftwareKeySignatureModule(
                            cashboxSimulation.getCompanyID() + "-" + "K" + i);
                }
                jwsModule.setOpenSystemSignatureModule(signatureModule);
                cashBoxParameters.getJwsSignatureModules().add(jwsModule);
            }

            //init cashbox
            DemoCashBox demoCashBox = new DemoCashBox(cashBoxParameters);

            //exceute simulation run
            demoCashBox.executeSimulation(cashboxSimulation.getCashBoxInstructionList());

            //----------------------------------------------------------------------------------------------------
            //export DEP
            DEPExportFormat depExportFormat = demoCashBox.exportDEP();
            //get JSON rep and dump export format to file/std output
            File depExportFile = new File(testSetDirectory, "dep-export.json");
            dumpJSONRepOfObject(depExportFormat, depExportFile, true,
                    "------------DEP-EXPORT-FORMAT------------");

            //----------------------------------------------------------------------------------------------------
            //store signature certificates and AES key (so that they can be used for verification purposes)
            CryptographicMaterialContainer cryptographicMaterialContainer = new CryptographicMaterialContainer();
            HashMap<String, CertificateOrPublicKeyContainer> certificateContainerMap = new HashMap<>();
            cryptographicMaterialContainer.setCertificateOrPublicKeyMap(certificateContainerMap);

            //store AES key as BASE64 String
            //ATTENTION, this is only for demonstration purposes, the AES key must be stored in a secure location
            cryptographicMaterialContainer.setBase64AESKey(cashboxSimulation.getBase64AesKey());
            List<JWSModule> jwsSignatureModules = demoCashBox.getCashBoxParameters().getJwsSignatureModules();
            for (JWSModule jwsSignatureModule : jwsSignatureModules) {
                CertificateOrPublicKeyContainer certificateOrPublicKeyContainer = new CertificateOrPublicKeyContainer();
                certificateOrPublicKeyContainer.setId(jwsSignatureModule.getSerialNumberOfKeyID());
                certificateContainerMap.put(jwsSignatureModule.getSerialNumberOfKeyID(),
                        certificateOrPublicKeyContainer);
                X509Certificate certificate = (X509Certificate) jwsSignatureModule.getSignatureModule()
                        .getSigningCertificate();
                if (certificate == null) {
                    //must be public key based... (closed system)
                    PublicKey publicKey = jwsSignatureModule.getSignatureModule().getSigningPublicKey();
                    certificateOrPublicKeyContainer.setSignatureCertificateOrPublicKey(
                            CashBoxUtils.base64Encode(publicKey.getEncoded(), false));
                    certificateOrPublicKeyContainer.setSignatureDeviceType(SignatureDeviceType.PUBLIC_KEY);
                } else {
                    certificateOrPublicKeyContainer.setSignatureCertificateOrPublicKey(
                            CashBoxUtils.base64Encode(certificate.getEncoded(), false));
                    certificateOrPublicKeyContainer.setSignatureDeviceType(SignatureDeviceType.CERTIFICATE);
                }
            }

            File cryptographicMaterialContainerFile = new File(testSetDirectory,
                    "cryptographicMaterialContainer.json");
            dumpJSONRepOfObject(cryptographicMaterialContainer, cryptographicMaterialContainerFile, true,
                    "------------CRYPTOGRAPHIC MATERIAL------------");

            //----------------------------------------------------------------------------------------------------
            //export QR codes to file
            //dump machine readable code of receipts (this "code" is used for the QR-codes)
            //REF TO SPECIFICATION: Detailspezifikation/Abs 12
            //dump to File
            File qrCoreRepExportFile = new File(testSetDirectory, "qr-code-rep.json");
            List<ReceiptPackage> receiptPackages = demoCashBox.getStoredReceipts();
            List<String> qrCodeRepList = new ArrayList<>();
            for (ReceiptPackage receiptPackage : receiptPackages) {
                qrCodeRepList.add(CashBoxUtils.getQRCodeRepresentationFromJWSCompactRepresentation(
                        receiptPackage.getJwsCompactRepresentation()));
            }
            dumpJSONRepOfObject(qrCodeRepList, qrCoreRepExportFile, true,
                    "------------QR-CODE-REP------------");

            //----------------------------------------------------------------------------------------------------
            //export OCR codes to file
            //dump machine readable code of receipts (this "code" is used for the OCR-codes)
            //REF TO SPECIFICATION: Detailspezifikation/Abs 14
            //dump to File
            File ocrCoreRepExportFile = new File(testSetDirectory, "ocr-code-rep.json");
            List<String> ocrCodeRepList = new ArrayList<>();
            for (ReceiptPackage receiptPackage : receiptPackages) {
                ocrCodeRepList.add(CashBoxUtils.getOCRCodeRepresentationFromJWSCompactRepresentation(
                        receiptPackage.getJwsCompactRepresentation()));
            }
            dumpJSONRepOfObject(ocrCodeRepList, ocrCoreRepExportFile, true,
                    "------------OCR-CODE-REP------------");

            //----------------------------------------------------------------------------------------------------
            //create PDF receipts and print to directory
            //REF TO SPECIFICATION: Detailspezifikation/Abs 12
            File qrCodeDumpDirectory = new File(testSetDirectory, "qr-code-dir-pdf");
            qrCodeDumpDirectory.mkdirs();
            List<byte[]> printedQRCodeReceipts = demoCashBox.printReceipt(receiptPackages,
                    ReceiptPrintType.QR_CODE);
            CashBoxUtils.writeReceiptsToFiles(printedQRCodeReceipts, "QR-", qrCodeDumpDirectory);

            //----------------------------------------------------------------------------------------------------
            //export receipts as PDF (OCR)
            //REF TO SPECIFICATION: Detailspezifikation/Abs 14
            File ocrCodeDumpDirectory = new File(testSetDirectory, "ocr-code-dir-pdf");
            ocrCodeDumpDirectory.mkdirs();
            List<byte[]> printedOCRCodeReceipts = demoCashBox.printReceipt(receiptPackages,
                    ReceiptPrintType.OCR);
            CashBoxUtils.writeReceiptsToFiles(printedOCRCodeReceipts, "OCR-", ocrCodeDumpDirectory);

            //----------------------------------------------------------------------------------------------------
            //dump executed testsuite
            File testSuiteDumpFile = new File(testSetDirectory,
                    cashboxSimulation.getSimulationRunLabel() + ".json");
            dumpJSONRepOfObject(cashboxSimulation, testSuiteDumpFile, true,
                    "------------CASHBOX Simulation------------");
        }
    } catch (CertificateEncodingException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    }
}

From source file:GenSig.java

public static void main(String[] args) {

    /* Generate a DSA signature */

    if (args.length != 1) {
        System.out.println("Usage: GenSig nameOfFileToSign");
    } else//from   w  w w.  j a  va2 s  .  c  om
        try {

            /* Generate a key pair */

            KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA", "SUN");
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");

            keyGen.initialize(1024, random);

            KeyPair pair = keyGen.generateKeyPair();
            PrivateKey priv = pair.getPrivate();
            PublicKey pub = pair.getPublic();

            /*
             * Create a Signature object and initialize it with the private
             * key
             */

            Signature dsa = Signature.getInstance("SHA1withDSA", "SUN");

            dsa.initSign(priv);

            /* Update and sign the data */

            FileInputStream fis = new FileInputStream(args[0]);
            BufferedInputStream bufin = new BufferedInputStream(fis);
            byte[] buffer = new byte[1024];
            int len;
            while (bufin.available() != 0) {
                len = bufin.read(buffer);
                dsa.update(buffer, 0, len);
            }
            ;

            bufin.close();

            /*
             * Now that all the data to be signed has been read in, generate
             * a signature for it
             */

            byte[] realSig = dsa.sign();

            /* Save the signature in a file */
            FileOutputStream sigfos = new FileOutputStream("sig");
            sigfos.write(realSig);

            sigfos.close();

            /* Save the public key in a file */
            byte[] key = pub.getEncoded();
            FileOutputStream keyfos = new FileOutputStream("suepk");
            keyfos.write(key);

            keyfos.close();

        } catch (Exception e) {
            System.err.println("Caught exception " + e.toString());
        }

}

From source file:com.clustercontrol.util.KeyCheck.java

/**
 * ????????/* ww w.jav  a 2 s  .com*/
 * 
 * @param args
 */
public static void main(String[] args) {
    PrivateKey privateKey = null;
    PublicKey publicKey = null;

    /// ??????? true
    /// ???????? false (?)
    boolean flag = false;
    if (flag) {
        try {
            // ?
            privateKey = getPrivateKey(
                    "???????privateKey.txt??");

            // ?
            publicKey = getPublicKey("???????");
            // publicKey = getPublicKey(publicKeyStr);
        } catch (Exception e) {
            System.out.println("hoge" + e.getMessage());
        }
    } else {
        KeyPairGenerator generator;
        try {
            generator = KeyPairGenerator.getInstance(ALGORITHM);
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
            // ?? 1024
            generator.initialize(1024, random);
            KeyPair keyPair = generator.generateKeyPair();
            privateKey = keyPair.getPrivate();
            publicKey = keyPair.getPublic();
        } catch (NoSuchAlgorithmException ex) {
            System.out.println(ex.getMessage());
        }
    }

    //
    // ?
    System.out.println("?");
    System.out.println(byte2String(privateKey.getEncoded()));
    System.out.println("?");
    System.out.println(byte2String(publicKey.getEncoded()));

    // ???????
    String string = "20140701_nttdata";
    byte[] src = string.getBytes();
    System.out.println("??String");
    System.out.println(string);
    System.out.println("??byte");
    System.out.println(byte2String(src));

    // ?
    try {
        String encStr = encrypt(string, privateKey);
        System.out.println("?");
        System.out.println(encStr);

        // ?
        String decStr = decrypt(encStr, publicKey);
        System.out.println("?");
        System.out.println(decStr);
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }

}