List of usage examples for java.security.cert X509Certificate getEncoded
public abstract byte[] getEncoded() throws CertificateEncodingException;
From source file:net.sourceforge.myvd.quickstart.util.GetSSLCert.java
public static void main(String[] args) throws Exception { javax.security.cert.X509Certificate cert = getCert("test.mydomain.com", 636); if (cert != null) { //System.out.println("Cert DN : " + cert.getIssuerDN()); } else {/* www . j av a 2 s .c o m*/ //System.out.println("No cert"); } FileOutputStream fso = new FileOutputStream("/tmp/cert.der"); fso.write(cert.getEncoded()); fso.flush(); fso.close(); }
From source file:net.sf.jsignpdf.InstallCert.java
/** * The main - whole logic of Install Cert Tool. * //from w w w . j a va 2s. co m * @param args * @throws Exception */ public static void main(String[] args) { String host; int port; char[] passphrase; System.out.println("InstallCert - Install CA certificate to Java Keystore"); System.out.println("====================================================="); final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); try { if ((args.length == 1) || (args.length == 2)) { String[] c = args[0].split(":"); host = c[0]; port = (c.length == 1) ? 443 : Integer.parseInt(c[1]); String p = (args.length == 1) ? "changeit" : args[1]; passphrase = p.toCharArray(); } else { String tmpStr; do { System.out.print("Enter hostname or IP address: "); tmpStr = StringUtils.defaultIfEmpty(reader.readLine(), null); } while (tmpStr == null); host = tmpStr; System.out.print("Enter port number [443]: "); tmpStr = StringUtils.defaultIfEmpty(reader.readLine(), null); port = tmpStr == null ? 443 : Integer.parseInt(tmpStr); System.out.print("Enter keystore password [changeit]: "); tmpStr = reader.readLine(); String p = "".equals(tmpStr) ? "changeit" : tmpStr; passphrase = p.toCharArray(); } char SEP = File.separatorChar; final File dir = new File(System.getProperty("java.home") + SEP + "lib" + SEP + "security"); final File file = new File(dir, "cacerts"); System.out.println("Loading KeyStore " + file + "..."); InputStream in = new FileInputStream(file); KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(in, passphrase); in.close(); SSLContext context = SSLContext.getInstance("TLS"); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ks); X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0]; SavingTrustManager tm = new SavingTrustManager(defaultTrustManager); context.init(null, new TrustManager[] { tm }, null); SSLSocketFactory factory = context.getSocketFactory(); System.out.println("Opening connection to " + host + ":" + port + "..."); SSLSocket socket = (SSLSocket) factory.createSocket(host, port); socket.setSoTimeout(10000); try { System.out.println("Starting SSL handshake..."); socket.startHandshake(); socket.close(); System.out.println(); System.out.println("No errors, certificate is already trusted"); } catch (SSLException e) { System.out.println(); System.out.println("Certificate is not yet trusted."); // e.printStackTrace(System.out); } X509Certificate[] chain = tm.chain; if (chain == null) { System.out.println("Could not obtain server certificate chain"); return; } System.out.println(); System.out.println("Server sent " + chain.length + " certificate(s):"); System.out.println(); MessageDigest sha1 = MessageDigest.getInstance("SHA1"); MessageDigest md5 = MessageDigest.getInstance("MD5"); for (int i = 0; i < chain.length; i++) { X509Certificate cert = chain[i]; System.out.println(" " + (i + 1) + " Subject " + cert.getSubjectDN()); System.out.println(" Issuer " + cert.getIssuerDN()); sha1.update(cert.getEncoded()); System.out.println(" sha1 " + toHexString(sha1.digest())); md5.update(cert.getEncoded()); System.out.println(" md5 " + toHexString(md5.digest())); System.out.println(); } System.out.print("Enter certificate to add to trusted keystore or 'q' to quit [1]: "); String line = reader.readLine().trim(); int k = -1; try { k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1; } catch (NumberFormatException e) { } if (k < 0 || k >= chain.length) { System.out.println("KeyStore not changed"); } else { try { System.out.println("Creating keystore backup"); final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); final File backupFile = new File(dir, CACERTS_KEYSTORE + "." + dateFormat.format(new java.util.Date())); final FileInputStream fis = new FileInputStream(file); final FileOutputStream fos = new FileOutputStream(backupFile); IOUtils.copy(fis, fos); fis.close(); fos.close(); } catch (Exception e) { e.printStackTrace(); } System.out.println("Installing certificate..."); X509Certificate cert = chain[k]; String alias = host + "-" + (k + 1); ks.setCertificateEntry(alias, cert); OutputStream out = new FileOutputStream(file); ks.store(out, passphrase); out.close(); System.out.println(); System.out.println(cert); System.out.println(); System.out.println("Added certificate to keystore '" + file + "' using alias '" + alias + "'"); } } catch (Exception e) { System.out.println(); System.out.println("----------------------------------------------"); System.out.println("Problem occured during installing certificate:"); e.printStackTrace(); System.out.println("----------------------------------------------"); } System.out.println("Press Enter to finish..."); try { reader.readLine(); } catch (IOException e) { e.printStackTrace(); } }
From source file:at.asitplus.regkassen.demo.RKSVCashboxSimulator.java
public static void main(String[] args) { try {/*from w w w . j av a 2 s. co 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:com.thoughtworks.go.security.CertificateUtil.java
public static String md5Fingerprint(X509Certificate certificate) { try {/*from w ww .j a v a 2 s.c o m*/ return DigestUtils.sha256Hex(certificate.getEncoded()); } catch (GeneralSecurityException gse) { throw bomb(gse); } }
From source file:Main.java
public static String certHash(final X509Certificate cert, String digest) { try {/*from w w w . j a va 2s . c o m*/ return certHash(cert.getEncoded(), digest); } catch (Exception ex) { throw new RuntimeException(ex); } }
From source file:fi.laverca.util.X509Util.java
/** * Convert an X509 certificate to byte[] DER * @param cert Certificate to convert//from ww w. j ava 2s. co m * @return Converted certificate as byte[] DER or null if the conversion failed */ public static byte[] X509CertificateToDER(final X509Certificate cert) { try { return cert.getEncoded(); } catch (Exception e) { log.error(e); } return null; }
From source file:eu.europa.esig.dss.TokenIdentifier.java
/** * Return the DSS certificate's unique id for a given * {@link X509Certificate}./* w ww . j av a2 s . c o m*/ * * @param cert * @return * @deprecated Use constructor instead */ @Deprecated public static TokenIdentifier getId(final X509Certificate cert) { try { return new TokenIdentifier(cert.getEncoded()); } catch (CertificateEncodingException e) { throw new DSSException(e); } }
From source file:Main.java
public static String toString(X509Certificate certificate) throws CertificateEncodingException { String header = "-----BEGIN CERTIFICATE-----\n"; String cert = Base64.encodeToString(certificate.getEncoded(), Base64.DEFAULT); String footer = "-----END CERTIFICATE-----"; return header + cert + footer; }
From source file:ee.sk.hwcrypto.demo.signature.TestSigningData.java
public static String getSigningCertificateInHex() { try {//from ww w . ja v a 2 s . co m X509Certificate certificate = getSigningCert(); byte[] derEncodedCertificate = certificate.getEncoded(); String hexString = Hex.encodeHexString(derEncodedCertificate); return hexString; } catch (Exception e) { throw new RuntimeException("Certificate loading failed", e); } }
From source file:com.aqnote.shared.cryptology.cert.io.PKCSTransformer.java
public static String getCrtFileB64(X509Certificate x509Cert) throws Exception { return Base64.encodeBase64String(x509Cert.getEncoded()); }