List of usage examples for java.security KeyPair getPrivate
public PrivateKey getPrivate()
From source file:com.peterphi.std.crypto.keygen.CaHelper.java
public static void main(String[] args) throws Exception { String casubject = "C=UK, O=SOMEORG, OU=Org Unit, CN=Example Certificate Authority"; X509Certificate cacert = null; PrivateKey caPrivateKey = null; if (true) {/* w w w .ja v a 2s. c om*/ KeyStore ks = KeyStore.getInstance("PKCS12", "BC"); ks.load(new FileInputStream(new File("/tmp/someorg-ca.p12")), new char[] {}); caPrivateKey = (PrivateKey) ks.getKey("ca", new char[] {}); cacert = (X509Certificate) ks.getCertificate("ca"); } else { KeyPair cakeys = generateKeyPair(2048); caPrivateKey = cakeys.getPrivate(); cacert = generateCaCertificate(casubject, cakeys, (BigInteger) null, new X509Name(casubject)); } { // CA .p12 { KeyStore ks = KeyStore.getInstance("PKCS12", "BC"); ks.load(null); //ks.setCertificateEntry("ca", cacert); ks.setKeyEntry("ca", caPrivateKey, new char[] {}, new java.security.cert.Certificate[] { cacert }); ks.store(new FileOutputStream("/tmp/someorg-ca.p12"), new char[] {}); } // CA .jks (public key only) { KeyStore ks = KeyStore.getInstance("JKS"); ks.load(null); ks.setCertificateEntry("ca", cacert); ks.store(new FileOutputStream("/tmp/ca-public.jks"), new char[] {}); } // CA .pem (public key only) { PEMWriter pem = new PEMWriter(new FileWriter(new File("/tmp/d3ca.crt"))); pem.writeObject(cacert); pem.close(); } } /* // User { String user = "C=UK, O=SOMEORG, OU=Org Unit, L=SomeCompany, CN=Some User (test)"; KeyPair keys = generateKeyPair(1024); X509Certificate cert = generateClientCertificate(keys.getPublic(), caPrivateKey, new X509Name(subject), new X509Name(user)); { KeyStore ks = KeyStore.getInstance("PKCS12", "BC"); ks.load(null); ks.setCertificateEntry("issuer", cacert); ks.setCertificateEntry("me", cert); ks.setKeyEntry("me", keys.getPrivate(), new char[] {}, new java.security.cert.Certificate[] { cert, cacert }); ks.store(new FileOutputStream("/tmp/someorg-someuser.p12"), "SomeCompanysecurity".toCharArray()); } { KeyStore ks = KeyStore.getInstance("JKS"); ks.load(null); ks.setKeyEntry("me", keys.getPrivate(), new char[] {}, new java.security.cert.Certificate[] { cert, cacert }); // ks.setCertificateEntry("issuer", cacert); // ks.setCertificateEntry("me", cert); ks.store(new FileOutputStream("/tmp/someorg-someuser.jks"), new char[] {}); } }//*/ // examplehost hostkey: { String user = "C=UK, O=SOMEORG, OU=Org Unit, L=SomeCompany, CN=examplehost.example.com"; KeyPair keys = generateKeyPair(1024); X509Certificate cert = generateServerCertificate(keys.getPublic(), caPrivateKey, new X509Name(casubject), new X509Name(user)); { KeyStore ks = KeyStore.getInstance("JKS"); ks.load(null); ks.setKeyEntry("me", keys.getPrivate(), new char[] {}, new java.security.cert.Certificate[] { cert, cacert }); // ks.setCertificateEntry("issuer", cacert); // ks.setCertificateEntry("me", cert); ks.store(new FileOutputStream("/tmp/host.jks"), new char[] {}); } { KeyStore ks = KeyStore.getInstance("PKCS12", "BC"); ks.load(null); ks.setCertificateEntry("issuer", cacert); ks.setCertificateEntry("me", cert); ks.setKeyEntry("me", keys.getPrivate(), new char[] {}, new java.security.cert.Certificate[] { cert, cacert }); ks.store(new FileOutputStream("/tmp/host.p12"), new char[] {}); } } }
From source file:org.aon.esolutions.appconfig.client.util.RSAEncryptUtil.java
public static void main(String... args) throws Exception { if (args.length < 2) { System.out.println(//from w ww . j a va 2 s . c o m "Usage: java org.aon.esolutions.appconfig.util.RSAEncryptUtil generateKeys <passphrase>"); System.out.println( "Usage: java org.aon.esolutions.appconfig.util.RSAEncryptUtil encryptPrivate <passphrase> <encryptText>"); System.out.println( "Usage: java org.aon.esolutions.appconfig.util.RSAEncryptUtil encryptPublic <passphrase> <encryptText>"); return; } String method = args[0]; if (method.equals("generateKeys")) { String passphrase = args[1]; KeyPair keyPair = generateKey(passphrase); System.out.println("Keys for Passphrase: " + passphrase); System.out.println("\nPUBLIC KEY:"); System.out.println(getKeyAsString(keyPair.getPublic())); System.out.println("\nPRIVATE KEY:"); System.out.println(getKeyAsString(keyPair.getPrivate())); } else if (method.startsWith("encrypt")) { String passphrase = args[1]; String toEncrypt = args[2]; KeyPair keyPair = generateKey(passphrase); Key toUse = null; if (method.toLowerCase().endsWith("private")) { System.out.println("USING PRIVATE KEY (" + passphrase + "):"); toUse = keyPair.getPrivate(); } else { System.out.println("USING PUBLIC KEY (" + passphrase + "):"); toUse = keyPair.getPublic(); } System.out.println(getKeyAsString(toUse)); String encrypted = encrypt(toEncrypt, toUse); System.out.println("\nUN-ENCRYPTED STRING:"); System.out.println(toEncrypt); System.out.println("\nENCRYPTED STRING:"); System.out.println(encrypted); } else { System.out.println(method + " is not a known command"); } }
From source file:mitm.common.security.ca.handlers.ejbca.ws.EjbcaWSClient.java
public static void main(String args[]) throws Exception { BasicConfigurator.configure();//from www. j a v a2 s . c o m JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean(); factory.setServiceClass(EjbcaWS.class); factory.setAddress("https://192.168.178.113:8443/ejbca/ejbcaws/ejbcaws"); factory.setServiceName(SERVICE_NAME); EjbcaWS client = (EjbcaWS) factory.create(); Client proxy = ClientProxy.getClient(client); HTTPConduit conduit = (HTTPConduit) proxy.getConduit(); TLSClientParameters tlsClientParameters = new TLSClientParameters(); KeyManagerFactory keyManagerFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); java.security.KeyStore keyStore = java.security.KeyStore.getInstance("PKCS12"); InputStream keyInput = new FileInputStream("/home/martijn/temp/superadmin.p12"); String password = "ejbca"; keyStore.load(keyInput, password.toCharArray()); keyInput.close(); keyManagerFactory.init(keyStore, password.toCharArray()); KeyManager[] keyManagers = keyManagerFactory.getKeyManagers(); tlsClientParameters.setDisableCNCheck(true); tlsClientParameters.setKeyManagers(keyManagers); X509TrustManager trustAll = new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] paramArrayOfX509Certificate, String paramString) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] paramArrayOfX509Certificate, String paramString) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return null; } }; TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(new KeyStoreLoader().loadKeyStore(new File("/home/martijn/temp/truststore.jks"), "changeit".toCharArray())); tlsClientParameters.setTrustManagers(new TrustManager[] { trustAll }); //tlsClientParameters.setTrustManagers(trustManagerFactory.getTrustManagers()); conduit.setTlsClientParameters(tlsClientParameters); System.out.println(client.getEjbcaVersion()); UserDataVOWS userData = new UserDataVOWS(); userData.setEmail("test@example.com"); userData.setUsername("test@example.com"); //userData.setPassword("test@example.com"); userData.setSubjectDN("CN=test@example.com"); userData.setSubjectAltName("rfc822Name=test@example.com"); userData.setEndEntityProfileName("test"); userData.setCaName("AdminCA1"); userData.setCertificateProfileName("ENDUSER"); userData.setStatus(EJBCAConst.STATUS_NEW); userData.setTokenType(EJBCAConst.TOKEN_TYPE_USERGENERATED); try { //client.editUser(userData); SecurityFactory securityFactory = SecurityFactoryFactory.getSecurityFactory(); SecureRandom randomSource = securityFactory.createSecureRandom(); KeyPairGenerator keyPairGenerator = securityFactory.createKeyPairGenerator("RSA"); keyPairGenerator.initialize(2048, randomSource); KeyPair keyPair = keyPairGenerator.generateKeyPair(); X500PrincipalBuilder builder = new X500PrincipalBuilder(); builder.setCommonName("john doe"); builder.setEmail("test@example.com"); PKCS10CertificationRequestBuilder requestBuilder = new PKCS10CertificationRequestBuilder( X500PrincipalUtils.toX500Name(builder.buildPrincipal()), SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded())); PKCS10CertificationRequest pkcs10 = requestBuilder .build(getContentSigner("SHA1WithRSA", keyPair.getPrivate())); String base64PKCS10 = Base64Utils.encode(pkcs10.getEncoded()); CertificateResponse certificateResponse = client.certificateRequest(userData, base64PKCS10, EJBCAConst.CERT_REQ_TYPE_PKCS10, null, EJBCAConst.RESPONSETYPE_CERTIFICATE); if (certificateResponse != null && certificateResponse.getData() != null) { /* * The result is a base64 encoded certificate */ Collection<X509Certificate> certificates = CertificateUtils.readX509Certificates( new ByteArrayInputStream(Base64.decode(certificateResponse.getData()))); if (CollectionUtils.isNotEmpty(certificates)) { for (X509Certificate certificate : certificates) { System.out.println(certificate); } } else { System.out.println("No certificates found"); } } else { System.out.println("certificateResponse is empty"); } } catch (Exception e) { e.printStackTrace(); } }
From source file:Signing.java
public static void main(String[] args) throws Exception { SOAPMessage soapMessage = MessageFactory.newInstance().createMessage(); SOAPPart soapPart = soapMessage.getSOAPPart(); SOAPEnvelope soapEnvelope = soapPart.getEnvelope(); SOAPHeader soapHeader = soapEnvelope.getHeader(); SOAPHeaderElement headerElement = soapHeader.addHeaderElement(soapEnvelope.createName("Signature", "SOAP-SEC", "http://schemas.xmlsoap.org/soap/security/2000-12")); SOAPBody soapBody = soapEnvelope.getBody(); soapBody.addAttribute(/*from ww w . j a v a2s. c o m*/ soapEnvelope.createName("id", "SOAP-SEC", "http://schemas.xmlsoap.org/soap/security/2000-12"), "Body"); Name bodyName = soapEnvelope.createName("FooBar", "z", "http://example.com"); SOAPBodyElement gltp = soapBody.addBodyElement(bodyName); Source source = soapPart.getContent(); Node root = null; if (source instanceof DOMSource) { root = ((DOMSource) source).getNode(); } else if (source instanceof SAXSource) { InputSource inSource = ((SAXSource) source).getInputSource(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder db = null; db = dbf.newDocumentBuilder(); Document doc = db.parse(inSource); root = (Node) doc.getDocumentElement(); } dumpDocument(root); KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA"); kpg.initialize(1024, new SecureRandom()); KeyPair keypair = kpg.generateKeyPair(); XMLSignatureFactory sigFactory = XMLSignatureFactory.getInstance(); Reference ref = sigFactory.newReference("#Body", sigFactory.newDigestMethod(DigestMethod.SHA1, null)); SignedInfo signedInfo = sigFactory.newSignedInfo( sigFactory.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null), sigFactory.newSignatureMethod(SignatureMethod.DSA_SHA1, null), Collections.singletonList(ref)); KeyInfoFactory kif = sigFactory.getKeyInfoFactory(); KeyValue kv = kif.newKeyValue(keypair.getPublic()); KeyInfo keyInfo = kif.newKeyInfo(Collections.singletonList(kv)); XMLSignature sig = sigFactory.newXMLSignature(signedInfo, keyInfo); System.out.println("Signing the message..."); PrivateKey privateKey = keypair.getPrivate(); Element envelope = getFirstChildElement(root); Element header = getFirstChildElement(envelope); DOMSignContext sigContext = new DOMSignContext(privateKey, header); sigContext.putNamespacePrefix(XMLSignature.XMLNS, "ds"); sigContext.setIdAttributeNS(getNextSiblingElement(header), "http://schemas.xmlsoap.org/soap/security/2000-12", "id"); sig.sign(sigContext); dumpDocument(root); System.out.println("Validate the signature..."); Element sigElement = getFirstChildElement(header); DOMValidateContext valContext = new DOMValidateContext(keypair.getPublic(), sigElement); valContext.setIdAttributeNS(getNextSiblingElement(header), "http://schemas.xmlsoap.org/soap/security/2000-12", "id"); boolean valid = sig.validate(valContext); System.out.println("Signature valid? " + valid); }
From source file:com.netscape.cmstools.CRMFPopClient.java
public static void main(String args[]) throws Exception { Options options = createOptions();/*w w w . j a va 2 s. com*/ CommandLine cmd = null; try { CommandLineParser parser = new PosixParser(); cmd = parser.parse(options, args); } catch (Exception e) { printError(e.getMessage()); System.exit(1); } if (cmd.hasOption("help")) { printHelp(); System.exit(0); } boolean verbose = cmd.hasOption("v"); String databaseDir = cmd.getOptionValue("d", "."); String tokenPassword = cmd.getOptionValue("p"); String tokenName = cmd.getOptionValue("h"); String algorithm = cmd.getOptionValue("a", "rsa"); int keySize = Integer.parseInt(cmd.getOptionValue("l", "2048")); String profileID = cmd.getOptionValue("f"); String subjectDN = cmd.getOptionValue("n"); boolean encodingEnabled = Boolean.parseBoolean(cmd.getOptionValue("k", "false")); // if transportCertFilename is not specified then assume no key archival String transportCertFilename = cmd.getOptionValue("b"); String popOption = cmd.getOptionValue("q", "POP_SUCCESS"); String curve = cmd.getOptionValue("c", "nistp256"); boolean sslECDH = Boolean.parseBoolean(cmd.getOptionValue("x", "false")); boolean temporary = Boolean.parseBoolean(cmd.getOptionValue("t", "true")); int sensitive = Integer.parseInt(cmd.getOptionValue("s", "-1")); int extractable = Integer.parseInt(cmd.getOptionValue("e", "-1")); boolean self_sign = cmd.hasOption("y"); // get the keywrap algorithm KeyWrapAlgorithm keyWrapAlgorithm = null; String kwAlg = KeyWrapAlgorithm.AES_KEY_WRAP_PAD.toString(); if (cmd.hasOption("w")) { kwAlg = cmd.getOptionValue("w"); } else { String alg = System.getenv("KEY_ARCHIVAL_KEYWRAP_ALGORITHM"); if (alg != null) { kwAlg = alg; } } String output = cmd.getOptionValue("o"); String hostPort = cmd.getOptionValue("m"); String username = cmd.getOptionValue("u"); String requestor = cmd.getOptionValue("r"); if (hostPort != null) { if (cmd.hasOption("w")) { printError("Any value specified for the key wrap parameter (-w) " + "will be overriden. CRMFPopClient will contact the " + "CA to determine the supported algorithm when " + "hostport is specified"); } } if (subjectDN == null) { printError("Missing subject DN"); System.exit(1); } if (tokenPassword == null) { printError("Missing token password"); System.exit(1); } if (algorithm.equals("rsa")) { if (cmd.hasOption("c")) { printError("Illegal parameter for RSA: -c"); System.exit(1); } if (cmd.hasOption("t")) { printError("Illegal parameter for RSA: -t"); System.exit(1); } if (cmd.hasOption("s")) { printError("Illegal parameter for RSA: -s"); System.exit(1); } if (cmd.hasOption("e")) { printError("Illegal parameter for RSA: -e"); System.exit(1); } if (cmd.hasOption("x")) { printError("Illegal parameter for RSA: -x"); System.exit(1); } } else if (algorithm.equals("ec")) { if (cmd.hasOption("l")) { printError("Illegal parameter for ECC: -l"); System.exit(1); } if (sensitive != 0 && sensitive != 1 && sensitive != -1) { printError("Illegal input parameters for -s: " + sensitive); System.exit(1); } if (extractable != 0 && extractable != 1 && extractable != -1) { printError("Illegal input parameters for -e: " + extractable); System.exit(1); } } else { printError("Invalid algorithm: " + algorithm); System.exit(1); } if (!popOption.equals("POP_SUCCESS") && !popOption.equals("POP_FAIL") && !popOption.equals("POP_NONE")) { printError("Invalid POP option: " + popOption); System.exit(1); } if (profileID == null) { if (algorithm.equals("rsa")) { profileID = "caEncUserCert"; } else if (algorithm.equals("ec")) { profileID = "caEncECUserCert"; } else { throw new Exception("Unknown algorithm: " + algorithm); } } try { if (verbose) System.out.println("Initializing security database: " + databaseDir); CryptoManager.initialize(databaseDir); CryptoManager manager = CryptoManager.getInstance(); CryptoToken token = CryptoUtil.getKeyStorageToken(tokenName); tokenName = token.getName(); manager.setThreadToken(token); Password password = new Password(tokenPassword.toCharArray()); try { token.login(password); } catch (Exception e) { throw new Exception("Unable to login: " + e, e); } CRMFPopClient client = new CRMFPopClient(); client.setVerbose(verbose); String encoded = null; X509Certificate transportCert = null; if (transportCertFilename != null) { if (verbose) System.out.println("archival option enabled"); if (verbose) System.out.println("Loading transport certificate"); encoded = new String(Files.readAllBytes(Paths.get(transportCertFilename))); byte[] transportCertData = Cert.parseCertificate(encoded); transportCert = manager.importCACertPackage(transportCertData); } else { if (verbose) System.out.println("archival option not enabled"); } if (verbose) System.out.println("Parsing subject DN"); Name subject = client.createName(subjectDN, encodingEnabled); if (subject == null) { subject = new Name(); subject.addCommonName("Me"); subject.addCountryName("US"); subject.addElement( new AVA(new OBJECT_IDENTIFIER("0.9.2342.19200300.100.1.1"), new PrintableString("MyUid"))); } if (verbose) System.out.println("Generating key pair"); KeyPair keyPair; if (algorithm.equals("rsa")) { keyPair = CryptoUtil.generateRSAKeyPair(token, keySize); } else if (algorithm.equals("ec")) { keyPair = client.generateECCKeyPair(token, curve, sslECDH, temporary, sensitive, extractable); } else { throw new Exception("Unknown algorithm: " + algorithm); } // print out keyid to be used in cmc decryptPOP PrivateKey privateKey = (PrivateKey) keyPair.getPrivate(); @SuppressWarnings("deprecation") byte id[] = privateKey.getUniqueID(); String kid = CryptoUtil.encodeKeyID(id); System.out.println("Keypair private key id: " + kid); if ((transportCert != null) && (hostPort != null)) { // check the CA for the required key wrap algorithm // if found, override whatever has been set by the command line // options for the key wrap algorithm ClientConfig config = new ClientConfig(); String host = hostPort.substring(0, hostPort.indexOf(':')); int port = Integer.parseInt(hostPort.substring(hostPort.indexOf(':') + 1)); config.setServerURL("http", host, port); PKIClient pkiclient = new PKIClient(config); kwAlg = getKeyWrapAlgotihm(pkiclient); } if (verbose && (transportCert != null)) System.out.println("Using key wrap algorithm: " + kwAlg); if (transportCert != null) { keyWrapAlgorithm = KeyWrapAlgorithm.fromString(kwAlg); } if (verbose) System.out.println("Creating certificate request"); CertRequest certRequest = client.createCertRequest(self_sign, token, transportCert, algorithm, keyPair, subject, keyWrapAlgorithm); ProofOfPossession pop = null; if (!popOption.equals("POP_NONE")) { if (verbose) System.out.println("Creating signer"); Signature signer = client.createSigner(token, algorithm, keyPair); if (popOption.equals("POP_SUCCESS")) { ByteArrayOutputStream bo = new ByteArrayOutputStream(); certRequest.encode(bo); signer.update(bo.toByteArray()); } else if (popOption.equals("POP_FAIL")) { byte[] data = { 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1 }; signer.update(data); } byte[] signature = signer.sign(); if (verbose) System.out.println("Creating POP"); pop = client.createPop(algorithm, signature); } if (verbose) System.out.println("Creating CRMF request"); String request = client.createCRMFRequest(certRequest, pop); StringWriter sw = new StringWriter(); try (PrintWriter out = new PrintWriter(sw)) { out.println(Cert.REQUEST_HEADER); out.print(request); out.println(Cert.REQUEST_FOOTER); } String csr = sw.toString(); if (hostPort != null) { System.out.println("Submitting CRMF request to " + hostPort); client.submitRequest(request, hostPort, username, profileID, requestor); } else if (output != null) { System.out.println("Storing CRMF request into " + output); try (FileWriter out = new FileWriter(output)) { out.write(csr); } } else { System.out.println(csr); } } catch (Exception e) { if (verbose) e.printStackTrace(); printError(e.getMessage()); System.exit(1); } }
From source file:ai.susi.tools.JsonSignature.java
public static void main(String[] args) throws Exception { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(2048);//w w w . java 2s . co m KeyPair keyPair = keyGen.genKeyPair(); String jsonString = "{\n" + " \"_id\": \"57b44e738d9af9fa2df13b27\",\n" + " \"index\": 0,\n" + " \"guid\": \"13af6838-08c8-4709-8dff-5ecb20bbaaa7\",\n" + " \"isActive\": false,\n" + " \"balance\": \"$2,092.08\",\n" + " \"picture\": \"http://placehold.it/32x32\",\n" + " \"age\": 22,\n" + " \"eyeColor\": \"blue\",\n" + " \"name\": \"Wyatt Jefferson\",\n" + " \"gender\": \"male\",\n" + " \"company\": \"GEEKFARM\",\n" + " \"email\": \"wyattjefferson@geekfarm.com\",\n" + " \"phone\": \"+1 (855) 405-2375\",\n" + " \"address\": \"506 Court Street, Gambrills, Minnesota, 8953\",\n" + " \"about\": \"Ea sunt quis non occaecat aliquip sint eiusmod. Aliquip id non ut sunt est laboris proident reprehenderit incididunt velit. Quis deserunt dolore aliqua voluptate magna laborum minim. Pariatur voluptate ad consequat culpa sit veniam eiusmod et ex ipsum.\\r\\n\",\n" + " \"registered\": \"2015-08-08T03:21:53 -02:00\",\n" + " \"latitude\": -39.880621,\n" + " \"longitude\": 44.053688,\n" + " \"tags\": [\n" + " \"non\",\n" + " \"cupidatat\",\n" + " \"in\",\n" + " \"Lorem\",\n" + " \"tempor\",\n" + " \"fugiat\",\n" + " \"aliqua\"\n" + " ],\n" + " \"friends\": [\n" + " {\n" + " \"id\": 0,\n" + " \"name\": \"Gail Blevins\"\n" + " },\n" + " {\n" + " \"id\": 1,\n" + " \"name\": \"Tricia Francis\"\n" + " },\n" + " {\n" + " \"id\": 2,\n" + " \"name\": \"Letitia Winters\"\n" + " }\n" + " ],\n" + " \"greeting\": \"Hello, Wyatt Jefferson! You have 1 unread messages.\",\n" + " \"favoriteFruit\": \"strawberry\"\n" + " }"; String jsonStringSimple = "{\n" + " \"_id\": \"57b44e738d9af9fa2df13b27\",\n" + " \"index\": 0,\n" + " \"guid\": \"13af6838-08c8-4709-8dff-5ecb20bbaaa7\",\n" + " \"isActive\": false,\n" + " \"balance\": \"$2,092.08\",\n" + " \"picture\": \"http://placehold.it/32x32\",\n" + " \"age\": 22,\n" + " \"eyeColor\": \"blue\",\n" + " \"name\": \"Wyatt Jefferson\",\n" + " \"gender\": \"male\",\n" + " \"company\": \"GEEKFARM\",\n" + " \"email\": \"wyattjefferson@geekfarm.com\",\n" + " \"phone\": \"+1 (855) 405-2375\",\n" + " \"address\": \"506 Court Street, Gambrills, Minnesota, 8953\",\n" + " \"about\": \"Ea sunt quis non occaecat aliquip sint eiusmod. Aliquip id non ut sunt est laboris proident reprehenderit incididunt velit. Quis deserunt dolore aliqua voluptate magna laborum minim. Pariatur voluptate ad consequat culpa sit veniam eiusmod et ex ipsum.\\r\\n\",\n" + " \"registered\": \"2015-08-08T03:21:53 -02:00\",\n" + " \"latitude\": -39.880621,\n" + " \"longitude\": 44.053688,\n" + " }"; JSONObject randomObj = new JSONObject(jsonString); JSONObject tmp = new JSONObject(jsonStringSimple); Map<String, byte[]> randomObj2 = new HashMap<String, byte[]>(); for (String key : tmp.keySet()) { Object value = tmp.get(key); randomObj2.put(key, value.toString().getBytes()); } addSignature(randomObj, keyPair.getPrivate()); addSignature(randomObj2, keyPair.getPrivate()); if (hasSignature(randomObj)) System.out.println("Verify 1: " + verify(randomObj, keyPair.getPublic())); if (hasSignature(randomObj2)) System.out.println("Verify 2: " + verify(randomObj, keyPair.getPublic())); removeSignature(randomObj); removeSignature(randomObj2); }
From source file:MainClass.java
static byte[] performSigning(String s, String alg, KeyPair keyPair) throws Exception { Signature sign = Signature.getInstance(alg); PrivateKey privateKey = keyPair.getPrivate(); PublicKey publicKey = keyPair.getPublic(); sign.initSign(privateKey);//from w w w . j a v a 2 s .c o m sign.update(s.getBytes()); return sign.sign(); }
From source file:com.vimukti.accounter.developer.api.PublicKeyGenerator.java
private static void generate() throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException, KeyStoreException, CertificateException, IOException, URISyntaxException { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA"); SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); random.setSeed("VimTech".getBytes("UTF-8")); keyGen.initialize(1024, random);//from w w w . j a va 2 s. c o m KeyPair pair = keyGen.generateKeyPair(); PrivateKey priv = pair.getPrivate(); PublicKey pub = pair.getPublic(); System.out.println(priv); System.out.println(pub); byte[] encoded = pub.getEncoded(); byte[] encodeBase64 = Base64.encodeBase64(encoded); System.out.println("Public Key:" + new String(encodeBase64)); byte[] encodedPrv = priv.getEncoded(); byte[] encodeBase64Prv = Base64.encodeBase64(encodedPrv); System.out.println("Private Key:" + new String(encodeBase64Prv)); byte[] decodeBase64 = Base64.decodeBase64(encodeBase64); X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(decodeBase64); KeyFactory keyFactory = KeyFactory.getInstance("DSA"); System.out.println(keyFactory.generatePublic(pubKeySpec).equals(pub)); }
From source file:com.boubei.tss.modules.license.LicenseFactory.java
/** * ???/*from w ww . j a v a 2s . c o m*/ * ????hacker??license * @throws Exception */ public static void generateKey() throws Exception { KeyPairGenerator keyGen = KeyPairGenerator.getInstance(KEY_ALGORITHM); keyGen.initialize(1024, new SecureRandom()); KeyPair pair = keyGen.generateKeyPair(); PrivateKey priv = pair.getPrivate(); PublicKey pub = pair.getPublic(); log.info("?"); DataOutputStream out = new DataOutputStream(new FileOutputStream(PUBLIC_KEY_FILE)); out.writeBytes(EasyUtils.encodeHex(pub.getEncoded())); out.close(); log.info("??" + PUBLIC_KEY_FILE); out = new DataOutputStream(new FileOutputStream(PRIVATE_KEY_FILE)); out.writeBytes(EasyUtils.encodeHex(priv.getEncoded())); out.close(); log.info("??" + PRIVATE_KEY_FILE); }
From source file:com.dianxin.imessage.common.util.SignUtil.java
public static PrivateKey getPrivateKey(String keypath) { if (privateKey != null) return privateKey; log.debug("???"); Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); try {//w w w. jav a 2s . co m FileReader fileReader = new FileReader(keypath); char[] cbuf = new char[40960]; fileReader.read(cbuf, 0, 40960); PEMReader reader = new PEMReader(new StringReader(new String(cbuf))); KeyPair keyPair = (KeyPair) reader.readObject(); privateKey = keyPair.getPrivate(); reader.close(); } catch (Exception e) { log.warn("??", e); } return privateKey; }