Java Code Examples for java.security.cert.Certificate

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project spring-security-oauth, under directory /spring-security-oauth/src/test/java/org/springframework/security/oauth/common/signature/.

Source file: TestRSA_SHA1SignatureMethod.java

  25 
vote

/** 
 * tests how to instantiate a public key from text.
 */
@Test public void testInstantiatePublicKey() throws Exception {
  String googleOAuthCert="-----BEGIN CERTIFICATE-----\n" + "MIIDBDCCAm2gAwIBAgIJAK8dGINfkSTHMA0GCSqGSIb3DQEBBQUAMGAxCzAJBgNV\n" + "BAYTAlVTMQswCQYDVQQIEwJDQTEWMBQGA1UEBxMNTW91bnRhaW4gVmlldzETMBEG\n"+ "A1UEChMKR29vZ2xlIEluYzEXMBUGA1UEAxMOd3d3Lmdvb2dsZS5jb20wHhcNMDgx\n"+ "MDA4MDEwODMyWhcNMDkxMDA4MDEwODMyWjBgMQswCQYDVQQGEwJVUzELMAkGA1UE\n"+ "CBMCQ0ExFjAUBgNVBAcTDU1vdW50YWluIFZpZXcxEzARBgNVBAoTCkdvb2dsZSBJ\n"+ "bmMxFzAVBgNVBAMTDnd3dy5nb29nbGUuY29tMIGfMA0GCSqGSIb3DQEBAQUAA4GN\n"+ "ADCBiQKBgQDQUV7ukIfIixbokHONGMW9+ed0E9X4m99I8upPQp3iAtqIvWs7XCbA\n"+ "bGqzQH1qX9Y00hrQ5RRQj8OI3tRiQs/KfzGWOdvLpIk5oXpdT58tg4FlYh5fbhIo\n"+ "VoVn4GvtSjKmJFsoM8NRtEJHL1aWd++dXzkQjEsNcBXwQvfDb0YnbQIDAQABo4HF\n"+ "MIHCMB0GA1UdDgQWBBSm/h1pNY91bNfW08ac9riYzs3cxzCBkgYDVR0jBIGKMIGH\n"+ "gBSm/h1pNY91bNfW08ac9riYzs3cx6FkpGIwYDELMAkGA1UEBhMCVVMxCzAJBgNV\n"+ "BAgTAkNBMRYwFAYDVQQHEw1Nb3VudGFpbiBWaWV3MRMwEQYDVQQKEwpHb29nbGUg\n"+ "SW5jMRcwFQYDVQQDEw53d3cuZ29vZ2xlLmNvbYIJAK8dGINfkSTHMAwGA1UdEwQF\n"+ "MAMBAf8wDQYJKoZIhvcNAQEFBQADgYEAYpHTr3vQNsHHHUm4MkYcDB20a5KvcFoX\n"+ "gCcYtmdyd8rh/FKeZm2me7eQCXgBfJqQ4dvVLJ4LgIQiU3R5ZDe0WbW7rJ3M9ADQ\n"+ "FyQoRJP8OIMYW3BoMi0Z4E730KSLRh6kfLq4rK6vw7lkH9oynaHHWZSJLDAp17cP\n"+ "j+6znWkN9/g=\n"+ "-----END CERTIFICATE-----";
  Certificate cert=CertificateFactory.getInstance("X.509").generateCertificate(new ByteArrayInputStream(googleOAuthCert.getBytes("utf-8")));
  RSAKeySecret secret=new RSAKeySecret(cert.getPublicKey());
  assertNotNull(secret);
}
 

Example 2

From project jetty-project, under directory /jetty-pkcs12/src/main/java/org/mortbay/jetty/server/ssl/.

Source file: PKCS12Import.java

  23 
vote

static void dumpChain(Certificate[] chain){
  for (int i=0; i < chain.length; i++) {
    Certificate cert=chain[i];
    if (cert instanceof X509Certificate) {
      X509Certificate x509=(X509Certificate)chain[i];
      System.err.println("subject: " + x509.getSubjectDN());
      System.err.println("issuer: " + x509.getIssuerDN());
    }
  }
}
 

Example 3

From project dnieprov, under directory /src/org/dnieprov/jce/provider/.

Source file: DnieKeyStore.java

  22 
vote

@Override public Certificate[] engineGetCertificateChain(String alias){
  Certificate cert=engineGetCertificate(alias);
  if (cert == null) {
    return null;
  }
  Certificate[] certArray=new Certificate[1];
  certArray[0]=cert;
  return certArray;
}
 

Example 4

From project eucalyptus, under directory /clc/modules/core/src/edu/ucsb/eucalyptus/keys/.

Source file: AbstractKeyStore.java

  22 
vote

public KeyPair getKeyPair(String alias,String password) throws GeneralSecurityException {
  Certificate cert=this.keyStore.getCertificate(alias);
  PrivateKey privateKey=(PrivateKey)this.keyStore.getKey(alias,password.toCharArray());
  KeyPair kp=new KeyPair(cert.getPublicKey(),privateKey);
  return kp;
}
 

Example 5

From project jftp, under directory /src/main/java/com/myjavaworld/jftp/ssl/.

Source file: CertificateManagerDlg.java

  22 
vote

private void viewServerCertificate(){
  int selectedRow=serverCertificatesTable.getSelectedRow();
  if (selectedRow >= 0) {
    Certificate certificate=serverCertificatesTableModel.getCertificateAt(selectedRow);
    CertificateDlg dlg=new CertificateDlg(parent,certificate);
    dlg.setLocationRelativeTo(this);
    dlg.setVisible(true);
    dlg.dispose();
  }
}
 

Example 6

From project Maimonides, under directory /src/com/codeko/apps/maimonides/dnie/.

Source file: DNIe.java

  22 
vote

private Certificate getCertificado(String alias) throws Exception {
  Certificate myCert=null;
  Enumeration<String> aliases=getKeyStore().aliases();
  while (aliases.hasMoreElements()) {
    String currAlias=aliases.nextElement();
    if (currAlias.equals(alias)) {
      myCert=getKeyStore().getCertificate(currAlias);
    }
  }
  return myCert;
}
 

Example 7

From project openclaws, under directory /cat/WEB-INF/src/edu/rit/its/claws/cat/.

Source file: CatSecureSocketFactory.java

  22 
vote

/** 
 * Create a socket.
 * @param host
 * @param port
 * @param otherHeaders
 * @param useFullURL
 * @throws Exception
 */
public Socket create(java.lang.String host,int port,java.lang.StringBuffer otherHeaders,BooleanHolder useFullURL) throws Exception {
  log.debug("Creating a secure socket to " + host + ":"+ port);
  SSLSocket ssl=(SSLSocket)ssf.createSocket();
  ssl.setSoTimeout(30000);
  ssl.connect(new InetSocketAddress(host,port),5000);
  ssl.startHandshake();
  final Certificate[] peerCerts=ssl.getSession().getPeerCertificates();
  final String reqCN=getRequiredCN(host,port);
  if (reqCN == null)   throw new IOException("Can not find required CN for " + host + ":"+ port);
  final Certificate peerCert=peerCerts[0];
  if (!certificateContainsCN(peerCert,reqCN))   throw new IOException("Could not find CN=" + reqCN + " in Peer's DN.");
  return ssl;
}
 

Example 8

From project picketbox-keystore, under directory /src/main/java/org/picketbox/keystore/.

Source file: PicketBoxDBKeyStore.java

  22 
vote

private static void generateCSR(PicketBoxDBKeyStore ks,String alias,char[] keyPass,FileOutputStream fos) throws Exception {
  CertificateUtil util=new CertificateUtil();
  Certificate cert=ks.engineGetCertificate(alias);
  PrivateKey privateKey=(PrivateKey)ks.engineGetKey(alias,keyPass);
  KeyPair keyPair=new KeyPair(cert.getPublicKey(),privateKey);
  X509Certificate x509=(X509Certificate)cert;
  byte[] csr=util.createCSR(x509.getSubjectDN().getName(),keyPair);
  String pem=util.getPEM(csr);
  fos.write(pem.getBytes());
  System.out.println("CSR stored");
}
 

Example 9

From project skmclauncher, under directory /src/main/java/com/sk89q/mclauncher/security/.

Source file: X509KeyStore.java

  22 
vote

/** 
 * Add root certificates from an input stream.
 * @param in input
 * @throws CertificateException on error
 * @throws IOException on I/O error
 */
public void addRootCertificates(InputStream in) throws CertificateException, IOException {
  try {
    BufferedInputStream bufferedIn=new BufferedInputStream(in);
    CertificateFactory cf=CertificateFactory.getInstance("X.509");
    while (bufferedIn.available() > 0) {
      Certificate cert=cf.generateCertificate(bufferedIn);
      addRootCertificate((X509Certificate)cert);
    }
  }
  finally {
    Util.close(in);
  }
}
 

Example 10

From project spring-crypto-utils, under directory /src/main/java/com/springcryptoutils/core/certificate/.

Source file: CertificateFactoryBean.java

  22 
vote

public void afterPropertiesSet() throws KeyStoreException {
  Certificate cert=keystore.getCertificate(alias);
  if (cert == null) {
    throw new CertificateException("no such certificate with alias: " + alias);
  }
  certificate=cert;
}
 

Example 11

From project spring-security-opensaml, under directory /src/main/java/nl/surfnet/spring/security/opensaml/.

Source file: CertificateStoreImpl.java

  22 
vote

private void appendToKeyStore(String keyAlias,String pemCert) throws Exception {
  String wrappedCert="-----BEGIN CERTIFICATE-----\n" + pemCert + "\n-----END CERTIFICATE-----";
  ByteArrayInputStream certificateInputStream=new ByteArrayInputStream(wrappedCert.getBytes());
  final CertificateFactory certificateFactory=CertificateFactory.getInstance("X.509");
  final Certificate cert=certificateFactory.generateCertificate(certificateInputStream);
  IOUtils.closeQuietly(certificateInputStream);
  keyStore.setCertificateEntry(keyAlias,cert);
}
 

Example 12

From project upm-android, under directory /src/com/u17od/upm/transport/.

Source file: HTTPTransport.java

  22 
vote

private void buildSSLFactory() throws CertificateException, KeyStoreException, NoSuchAlgorithmException, IOException, KeyManagementException {
  FileInputStream fileStream=new FileInputStream(certFile);
  CertificateFactory certFactory=CertificateFactory.getInstance("X.509");
  Certificate cert=certFactory.generateCertificate(fileStream);
  KeyStore keyStore=KeyStore.getInstance(KeyStore.getDefaultType());
  keyStore.load(null);
  keyStore.setCertificateEntry("cert0",cert);
  TrustManagerFactory trustManager=TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
  trustManager.init(keyStore);
  SSLContext context=SSLContext.getInstance("TLS");
  context.init(null,trustManager.getTrustManagers(),null);
  sslFactory=context.getSocketFactory();
}
 

Example 13

From project apjp, under directory /APJP_LOCAL_JAVA/src/main/java/APJP/HTTPS/.

Source file: HTTPS.java

  21 
vote

public static synchronized SSLSocket createSSLSocket() throws HTTPSException {
  try {
    KeyStore defaultKeyStore=getDefaultKeyStore();
    PrivateKey privateKey=(PrivateKey)defaultKeyStore.getKey("APJP","APJP".toCharArray());
    Certificate certificateAuthority=defaultKeyStore.getCertificate("APJP");
    Certificate[] certificateArray=new Certificate[1];
    certificateArray[0]=certificateAuthority;
    KeyStore keyStore=KeyStore.getInstance(KeyStore.getDefaultType());
    keyStore.load(null,"APJP".toCharArray());
    keyStore.setCertificateEntry("APJP",certificateAuthority);
    keyStore.setKeyEntry("APJP",privateKey,"APJP".toCharArray(),certificateArray);
    SSLContext sslContext=SSLContext.getInstance("TLS");
    KeyManagerFactory keyManagerFactory=KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keyStore,"APJP".toCharArray());
    TrustManagerFactory trustManagerFactory=TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(keyStore);
    sslContext.init(keyManagerFactory.getKeyManagers(),trustManagerFactory.getTrustManagers(),null);
    SSLSocketFactory sslSocketFactory=(SSLSocketFactory)sslContext.getSocketFactory();
    return (SSLSocket)sslSocketFactory.createSocket();
  }
 catch (  Exception e) {
    logger.log(2,"HTTPS/CREATE_SSL_SOCKET: EXCEPTION",e);
    throw new HTTPSException("HTTPS/CREATE_SSL_SOCKET",e);
  }
}
 

Example 14

From project core_1, under directory /security/src/test/java/org/switchyard/security/credential/extract/.

Source file: SOAPMessageCredentialsExtractorTests.java

  21 
vote

@Test public void testBinarySecurityToken() throws Exception {
  SOAPMessage source=createMessage(BINARY_SECURITY_TOKEN_XML);
  Set<Credential> creds=new SOAPMessageCredentialsExtractor().extractCredentials(source);
  boolean foundCertificate=false;
  for (  Credential cred : creds) {
    if (cred instanceof CertificateCredential) {
      foundCertificate=true;
      Certificate certificate=((CertificateCredential)cred).getCertificate();
      Assert.assertEquals("X.509",certificate.getType());
    }
  }
  if (!foundCertificate) {
    Assert.fail("certificate not found");
  }
}
 

Example 15

From project freemind, under directory /freemind/plugins/script/.

Source file: SignedScriptHandler.java

  21 
vote

public boolean isScriptSigned(String pScript,OutputStream pOutStream){
  ScriptContents content=new ScriptContents(pScript);
  if (content.mSignature != null) {
    try {
      Signature instanceVerify=Signature.getInstance("SHA1withDSA");
      if (content.mKeyName == null) {
        String cer="-----BEGIN CERTIFICATE-----\n" + "MIIDKDCCAuWgAwIBAgIESAY2ADALBgcqhkjOOAQDBQAwdzELMAkGA1UEBhMCREUxCzAJBgNVBAgT" + "AkRFMRMwEQYDVQQHEwpPcGVuU291cmNlMRgwFgYDVQQKEw9zb3VyY2Vmb3JnZS5uZXQxETAPBgNV"+ "BAsTCEZyZWVNaW5kMRkwFwYDVQQDExBDaHJpc3RpYW4gRm9sdGluMB4XDTA4MDQxNjE3MjMxMloX"+ "DTA4MDcxNTE3MjMxMlowdzELMAkGA1UEBhMCREUxCzAJBgNVBAgTAkRFMRMwEQYDVQQHEwpPcGVu"+ "U291cmNlMRgwFgYDVQQKEw9zb3VyY2Vmb3JnZS5uZXQxETAPBgNVBAsTCEZyZWVNaW5kMRkwFwYD"+ "VQQDExBDaHJpc3RpYW4gRm9sdGluMIIBtzCCASwGByqGSM44BAEwggEfAoGBAP1/U4EddRIpUt9K"+ "nC7s5Of2EbdSPO9EAMMeP4C2USZpRV1AIlH7WT2NWPq/xfW6MPbLm1Vs14E7gB00b/JmYLdrmVCl"+ "pJ+f6AR7ECLCT7up1/63xhv4O1fnxqimFQ8E+4P208UewwI1VBNaFpEy9nXzrith1yrv8iIDGZ3R"+ "SAHHAhUAl2BQjxUjC8yykrmCouuEC/BYHPUCgYEA9+GghdabPd7LvKtcNrhXuXmUr7v6OuqC+VdM"+ "Cz0HgmdRWVeOutRZT+ZxBxCBgLRJFnEj6EwoFhO3zwkyjMim4TwWeotUfI0o4KOuHiuzpnWRbqN/"+ "C/ohNWLx+2J6ASQ7zKTxvqhRkImog9/hWuWfBpKLZl6Ae1UlZAFMO/7PSSoDgYQAAoGAZm5z5EZX"+ "Vhtye5jY3X9w24DJ3yNJbNl2tfkOBIc0KfgyxONTSJKtUpmLI3btUxy3pQf/T8BShlY3PAC0fp3M"+ "eDG8WRq1wM3luLd1V9SS8EG6tPJBZ3mciCUymTT7n9CZNzATIpqNIXHSD/wljRABedUi8PMg4KbV"+ "Pnhu6Y6b1uAwCwYHKoZIzjgEAwUAAzAAMC0CFQCFHGwe+HHOvY0MmKYHbiq7fRxMGwIUC0voAGYU"+ "u6vgVFqdLI5F96JLTqk="+ "\n-----END CERTIFICATE-----\n";
        CertificateFactory cf=CertificateFactory.getInstance("X.509");
        Collection c=cf.generateCertificates(new ByteArrayInputStream(cer.getBytes()));
        Iterator i=c.iterator();
        if (i.hasNext()) {
          Certificate cert=(Certificate)i.next();
          instanceVerify.initVerify(cert);
        }
 else {
          throw new IllegalArgumentException("Internal certificate wrong.");
        }
      }
 else {
        initializeKeystore(null);
        instanceVerify.initVerify(mKeyStore.getCertificate(content.mKeyName));
      }
      instanceVerify.update(content.mScript.getBytes());
      boolean verify=instanceVerify.verify(Tools.fromBase64(content.mSignature));
      return verify;
    }
 catch (    Exception e) {
      Resources.getInstance().logException(e);
      try {
        pOutStream.write(e.toString().getBytes());
        pOutStream.write("\n".getBytes());
      }
 catch (      Exception e1) {
        Resources.getInstance().logException(e1);
      }
    }
  }
  return false;
}
 

Example 16

From project heritrix3, under directory /engine/src/main/java/org/archive/crawler/.

Source file: Heritrix.java

  21 
vote

/** 
 * Perform preparation to use an ad-hoc, created-as-necessary  certificate/keystore for HTTPS access. A keystore with new cert is created if necessary, as adhoc.keystore in the working directory. Otherwise, a preexisting adhoc.keystore is read  and the certificate fingerprint shown to assist in operator browser-side verification.
 * @param startupOut where to report fingerprint
 */
protected void useAdhocKeystore(PrintStream startupOut){
  try {
    File keystoreFile=new File(ADHOC_KEYSTORE);
    if (!keystoreFile.exists()) {
      String[] args={"-keystore",ADHOC_KEYSTORE,"-storepass",ADHOC_PASSWORD,"-keypass",ADHOC_PASSWORD,"-alias","adhoc","-genkey","-keyalg","RSA","-dname","CN=Heritrix Ad-Hoc HTTPS Certificate","-validity","3650"};
      KeyTool.main(args);
    }
    KeyStore keystore=KeyStore.getInstance(KeyStore.getDefaultType());
    InputStream inStream=new ByteArrayInputStream(FileUtils.readFileToByteArray(keystoreFile));
    keystore.load(inStream,ADHOC_PASSWORD.toCharArray());
    Certificate cert=keystore.getCertificate("adhoc");
    byte[] certBytes=cert.getEncoded();
    byte[] sha1=MessageDigest.getInstance("SHA1").digest(certBytes);
    startupOut.print("Using ad-hoc HTTPS certificate with fingerprint...\nSHA1");
    for (    byte b : sha1) {
      startupOut.print(String.format(":%02X",b));
    }
    startupOut.println("\nVerify in browser before accepting exception.");
  }
 catch (  Exception e) {
    throw new RuntimeException(e);
  }
}
 

Example 17

From project http-testing-harness, under directory /server-provider/src/test/java/org/sonatype/tests/http/server/jetty/impl/.

Source file: ClientSideCertTest.java

  21 
vote

private CertificateHolder getCertificate(String alias,String keystorePath,String keystorePass) throws Exception {
  FileInputStream is=null;
  Certificate cert=null;
  DSAPrivateKey key;
  try {
    is=new FileInputStream(new File(keystorePath));
    KeyStore keystore=KeyStore.getInstance("JKS");
    keystore.load(is,keystorePass == null ? null : keystorePass.toString().toCharArray());
    cert=keystore.getCertificate(alias);
    key=(DSAPrivateKey)keystore.getKey(alias,keystorePass.toCharArray());
  }
  finally {
    if (is != null) {
      is.close();
    }
  }
  return new CertificateHolder(key,cert);
}
 

Example 18

From project JGlobus, under directory /ssl-proxies/src/main/java/org/globus/gsi/stores/.

Source file: PEMKeyStore.java

  21 
vote

/** 
 * Delete a security object from this keystore.
 * @param s The alias of the object to delete.
 * @throws KeyStoreException
 */
@Override public void engineDeleteEntry(String s) throws KeyStoreException {
  SecurityObjectWrapper<?> object=this.aliasObjectMap.remove(s);
  if (object != null) {
    if (object instanceof ResourceTrustAnchor) {
      ResourceTrustAnchor descriptor=(ResourceTrustAnchor)object;
      Certificate cert;
      try {
        cert=descriptor.getTrustAnchor().getTrustedCert();
      }
 catch (      ResourceStoreException e) {
        throw new KeyStoreException(e);
      }
      this.certFilenameMap.remove(cert);
      boolean success=descriptor.getFile().delete();
      if (!success) {
        logger.info("Unable to delete certificate");
      }
    }
 else     if (object instanceof ResourceProxyCredential) {
      ResourceProxyCredential proxy=(ResourceProxyCredential)object;
      try {
        proxy.getCredential();
      }
 catch (      ResourceStoreException e) {
        throw new KeyStoreException(e);
      }
      boolean success=proxy.getFile().delete();
      if (!success) {
        logger.info("Unable to delete credential");
      }
    }
  }
}
 

Example 19

From project Mujina, under directory /mujina-common/src/main/java/nl/surfnet/mujina/model/.

Source file: CommonConfigurationImpl.java

  21 
vote

private void injectKeyStore(String alias,String pemCert,String pemKey) throws Exception {
  CertificateFactory certFact;
  Certificate cert;
  String wrappedCert="-----BEGIN CERTIFICATE-----\n" + pemCert + "\n-----END CERTIFICATE-----";
  ByteArrayInputStream certificateInputStream=new ByteArrayInputStream(wrappedCert.getBytes());
  try {
    certFact=CertificateFactory.getInstance("X.509");
    cert=certFact.generateCertificate(certificateInputStream);
  }
 catch (  CertificateException e) {
    throw new Exception("Could not instantiate cert",e);
  }
  IOUtils.closeQuietly(certificateInputStream);
  ArrayList<Certificate> certs=new ArrayList<Certificate>();
  certs.add(cert);
  final byte[] key=Base64.decodeBase64(pemKey);
  KeyFactory keyFactory=KeyFactory.getInstance("RSA");
  KeySpec ks=new PKCS8EncodedKeySpec(key);
  RSAPrivateKey privKey=(RSAPrivateKey)keyFactory.generatePrivate(ks);
  final Certificate[] certificates=new Certificate[1];
  certificates[0]=certs.get(0);
  keyStore.setKeyEntry(alias,privKey,keystorePassword.toCharArray(),certificates);
}
 

Example 20

From project OWASP-WebScarab, under directory /src/org/owasp/webscarab/plugin/saml/.

Source file: SamlHTTPClient.java

  21 
vote

private String signSamlMessage(String samlResponse) throws IOException, ParserConfigurationException, SAXException, Base64DecodingException, TransformerConfigurationException, TransformerException, XMLSecurityException {
  Document document=parseDocument(samlResponse);
  Element protocolSignatureElement=SamlModel.findProtocolSignatureElement(document);
  if (null == protocolSignatureElement) {
    return samlResponse;
  }
  protocolSignatureElement.getParentNode().removeChild(protocolSignatureElement);
  XMLSignature xmlSignature=new XMLSignature(document,null,XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1);
  document.getDocumentElement().insertBefore(xmlSignature.getElement(),document.getDocumentElement().getFirstChild());
  Transforms transforms=new Transforms(document);
  transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE);
  transforms.addTransform(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS);
  xmlSignature.addDocument("",transforms,Constants.ALGO_ID_DIGEST_SHA1);
  KeyStore.PrivateKeyEntry privateKeyEntry=this.samlProxyConfig.getPrivateKeyEntry();
  KeyInfo keyInfo=xmlSignature.getKeyInfo();
  X509Data x509Data=new X509Data(document);
  Certificate[] certificateChain=privateKeyEntry.getCertificateChain();
  for (int certIdx=0; certIdx < certificateChain.length; certIdx++) {
    Certificate certificate=certificateChain[certIdx];
    x509Data.addCertificate((X509Certificate)certificate);
  }
  keyInfo.add(x509Data);
  PrivateKey privateKey=privateKeyEntry.getPrivateKey();
  xmlSignature.sign(privateKey);
  return outputDocument(document);
}
 

Example 21

From project picketlink-integration-tests, under directory /unit-tests/util/src/test/java/org/picketlink/test/integration/util/.

Source file: PicketLinkConfigurationUtil.java

  21 
vote

/** 
 * <p> Adds a new alias to the keystore specified in the <code>jksPath</code> parameter.  </p>
 * @param sp
 * @param jksPath
 * @param alias
 * @throws GeneralSecurityException
 * @throws IOException
 * @throws KeyStoreException
 * @throws FileNotFoundException
 * @throws NoSuchAlgorithmException
 * @throws CertificateException
 */
public static void addKeyStoreAlias(WebArchive sp,String jksPath,String certAlias,String passwd,String alias){
  final Node keystore=getContent(sp,jksPath);
  char[] password=passwd.toCharArray();
  try {
    final KeyStore jks=KeyStoreUtil.getKeyStore(keystore.getAsset().openStream(),password);
    Certificate certificate=jks.getCertificate(certAlias);
    jks.setCertificateEntry(alias,certificate);
    File file=new File("/tmp/tmpjks.jks");
    if (file.exists()) {
      file.delete();
    }
    FileOutputStream stream=new FileOutputStream(file);
    jks.store(stream,password);
    stream.close();
    final FileInputStream fileInputStream=new FileInputStream("/tmp/tmpjks.jks");
    sp.delete(keystore.getPath());
    sp.add(new Asset(){
      public InputStream openStream(){
        return fileInputStream;
      }
    }
,keystore.getPath());
  }
 catch (  Exception e) {
    throw new RuntimeException("Error while adding a new alias to the keystore.",e);
  }
}
 

Example 22

From project rundeck, under directory /core/src/main/java/com/dtolabs/rundeck/core/utils/.

Source file: JARVerifier.java

  21 
vote

/** 
 * Construct a JARVerifier with a keystore and alias and password.
 * @param keystore filepath to the keystore
 * @param alias    alias name of the cert chain to verify with
 * @param passwd   password to use to verify the keystore, or null
 * @return
 * @throws IOException
 * @throws KeyStoreException
 * @throws NoSuchAlgorithmException
 * @throws CertificateException
 */
public static JARVerifier create(String keystore,String alias,char[] passwd) throws IOException, KeyStoreException, NoSuchAlgorithmException, CertificateException {
  KeyStore keyStore=KeyStore.getInstance("JKS");
  FileInputStream fileIn=null;
  try {
    fileIn=new FileInputStream(keystore);
    keyStore.load(fileIn,passwd);
  }
  finally {
    if (null != fileIn) {
      fileIn.close();
    }
  }
  Certificate[] chain=keyStore.getCertificateChain(alias);
  if (chain == null) {
    Certificate cert=keyStore.getCertificate(alias);
    if (cert == null) {
      throw new IllegalArgumentException("No trusted certificate or chain found for alias: " + alias);
    }
    chain=new Certificate[]{cert};
  }
  X509Certificate certChain[]=new X509Certificate[chain.length];
  CertificateFactory cf=CertificateFactory.getInstance("X.509");
  for (int count=0; count < chain.length; count++) {
    ByteArrayInputStream certIn=new ByteArrayInputStream(chain[count].getEncoded());
    X509Certificate cert=(X509Certificate)cf.generateCertificate(certIn);
    certChain[count]=cert;
  }
  JARVerifier jarVerifier=new JARVerifier(certChain);
  return jarVerifier;
}
 

Example 23

From project winstone, under directory /src/java/winstone/ssl/.

Source file: HttpsListener.java

  21 
vote

/** 
 * Extracts the relevant socket stuff and adds it to the request object. This method relies on the base class for everything other than SSL related attributes
 */
protected void parseSocketInfo(Socket socket,WinstoneRequest req) throws IOException {
  super.parseSocketInfo(socket,req);
  if (socket instanceof SSLSocket) {
    SSLSocket s=(SSLSocket)socket;
    SSLSession ss=s.getSession();
    if (ss != null) {
      Certificate certChain[]=null;
      try {
        certChain=ss.getPeerCertificates();
      }
 catch (      Throwable err) {
      }
      if (certChain != null) {
        req.setAttribute("javax.servlet.request.X509Certificate",certChain);
        req.setAttribute("javax.servlet.request.cipher_suite",ss.getCipherSuite());
        req.setAttribute("javax.servlet.request.ssl_session",new String(ss.getId()));
        req.setAttribute("javax.servlet.request.key_size",getKeySize(ss.getCipherSuite()));
      }
    }
    req.setIsSecure(true);
  }
}
 

Example 24

From project AmDroid, under directory /httpclientandroidlib/src/ch/boye/httpclientandroidlib/conn/ssl/.

Source file: AbstractVerifier.java

  19 
vote

public final void verify(String host,SSLSocket ssl) throws IOException {
  if (host == null) {
    throw new NullPointerException("host to verify is null");
  }
  SSLSession session=ssl.getSession();
  if (session == null) {
    InputStream in=ssl.getInputStream();
    in.available();
    session=ssl.getSession();
    if (session == null) {
      ssl.startHandshake();
      session=ssl.getSession();
    }
  }
  Certificate[] certs=session.getPeerCertificates();
  X509Certificate x509=(X509Certificate)certs[0];
  verify(host,x509);
}
 

Example 25

From project candlepin, under directory /src/main/java/org/candlepin/pki/.

Source file: PKIUtility.java

  19 
vote

public boolean verifySHA256WithRSAHash(InputStream input,byte[] signedHash,Certificate certificate){
  try {
    Signature signature=Signature.getInstance("SHA256withRSA");
    signature.initVerify(certificate.getPublicKey());
    updateSignature(input,signature);
    return signature.verify(signedHash);
  }
 catch (  SignatureException se) {
    log.error(se);
    log.warn(ConfigProperties.CA_CERT_UPSTREAM + " may not match the server" + " that signed manifest.");
    return false;
  }
catch (  Exception e) {
    throw new RuntimeException(e);
  }
}
 

Example 26

From project cas, under directory /cas-server-support-x509/src/test/java/org/jasig/cas/adaptors/x509/util/.

Source file: MockX509CRL.java

  19 
vote

/** 
 * @see java.security.cert.CRL#isRevoked(java.security.cert.Certificate)
 */
@Override public boolean isRevoked(final Certificate cert){
  if (cert instanceof X509Certificate) {
    final X509Certificate xcert=(X509Certificate)cert;
    for (    X509CRLEntry entry : getRevokedCertificates()) {
      if (entry.getSerialNumber().equals(xcert.getSerialNumber())) {
        return true;
      }
    }
  }
  return false;
}
 

Example 27

From project commons-compress, under directory /src/main/java/org/apache/commons/compress/archivers/jar/.

Source file: JarArchiveEntry.java

  19 
vote

public Certificate[] getCertificates(){
  if (certificates != null) {
    Certificate[] certs=new Certificate[certificates.length];
    System.arraycopy(certificates,0,certs,0,certs.length);
    return certs;
  }
  return null;
}
 

Example 28

From project Custom-Salem, under directory /src/haven/.

Source file: SslHelper.java

  19 
vote

public synchronized void trust(Certificate cert){
  clear();
  try {
    trusted.setCertificateEntry("cert-" + tserial++,cert);
  }
 catch (  KeyStoreException e) {
    throw (new RuntimeException(e));
  }
}
 

Example 29

From project Haven-and-Hearth-client-modified-by-Ender, under directory /src/haven/.

Source file: SslHelper.java

  19 
vote

public synchronized void trust(Certificate cert){
  clear();
  try {
    trusted.setCertificateEntry("cert-" + tserial++,cert);
  }
 catch (  KeyStoreException e) {
    throw (new RuntimeException(e));
  }
}
 

Example 30

From project hawtdispatch, under directory /hawtdispatch-transport/src/main/java/org/fusesource/hawtdispatch/transport/.

Source file: SslProtocolCodec.java

  19 
vote

public X509Certificate[] getPeerX509Certificates(){
  if (engine == null) {
    return null;
  }
  try {
    ArrayList<X509Certificate> rc=new ArrayList<X509Certificate>();
    for (    Certificate c : engine.getSession().getPeerCertificates()) {
      if (c instanceof X509Certificate) {
        rc.add((X509Certificate)c);
      }
    }
    return rc.toArray(new X509Certificate[rc.size()]);
  }
 catch (  SSLPeerUnverifiedException e) {
    return null;
  }
}
 

Example 31

From project httpClient, under directory /httpclient/src/main/java/org/apache/http/conn/ssl/.

Source file: AbstractVerifier.java

  19 
vote

public final void verify(String host,SSLSocket ssl) throws IOException {
  if (host == null) {
    throw new NullPointerException("host to verify is null");
  }
  SSLSession session=ssl.getSession();
  if (session == null) {
    InputStream in=ssl.getInputStream();
    in.available();
    session=ssl.getSession();
    if (session == null) {
      ssl.startHandshake();
      session=ssl.getSession();
    }
  }
  Certificate[] certs=session.getPeerCertificates();
  X509Certificate x509=(X509Certificate)certs[0];
  verify(host,x509);
}
 

Example 32

From project integration-tests, under directory /picketlink-sts-tests/src/test/java/org/picketlink/test/integration/sts/.

Source file: PicketLinkSTSIntegrationUnitTestCase.java

  19 
vote

/** 
 * <p> Validates the contents of the specified  {@code SubjectConfirmationType} when the {@code HOLDER_OF_KEY}confirmation method has been used. </p>
 * @param subjectConfirmation the  {@code SubjectConfirmationType} to be validated.
 * @param keyType the type of the proof-of-possession key (Symmetric or Public).
 * @param certificate the certificate used in the Public Key scenarios.
 * @param usePublicKey {@code true} if the certificate's Public Key was used as the proof-of-possession token; {@code false}otherwise.
 * @throws Exception if an error occurs while performing the validation.
 */
private void validateHolderOfKeyContents(SubjectConfirmationType subjectConfirmation,String keyType,Certificate certificate,boolean usePublicKey) throws Exception {
  SubjectConfirmationDataType subjConfirmationDataType=subjectConfirmation.getSubjectConfirmationData();
  Assert.assertNotNull("Unexpected null subject confirmation data",subjConfirmationDataType);
  KeyInfoType keyInfo=(KeyInfoType)subjConfirmationDataType.getAnyType();
  Assert.assertEquals("Unexpected key info content size",1,keyInfo.getContent().size());
  if (WSTrustConstants.KEY_TYPE_SYMMETRIC.equals(keyType)) {
    Element encKeyElement=(Element)keyInfo.getContent().get(0);
    Assert.assertEquals("Unexpected key info content type",WSTrustConstants.XMLEnc.ENCRYPTED_KEY,encKeyElement.getLocalName());
  }
 else   if (WSTrustConstants.KEY_TYPE_PUBLIC.equals(keyType)) {
    if (usePublicKey == true) {
      KeyValueType keyValue=(KeyValueType)keyInfo.getContent().get(0);
      List<Object> keyValueContent=keyValue.getContent();
      Assert.assertEquals("Unexpected key value content size",1,keyValueContent.size());
      Assert.assertEquals("Unexpected key value content type",RSAKeyValueType.class,keyValueContent.get(0).getClass());
      RSAKeyValueType rsaKeyValue=(RSAKeyValueType)keyValueContent.get(0);
      BigInteger modulus=new BigInteger(1,Base64.decode(new String(rsaKeyValue.getModulus())));
      BigInteger exponent=new BigInteger(1,Base64.decode(new String(rsaKeyValue.getExponent())));
      KeyFactory factory=KeyFactory.getInstance("RSA");
      RSAPublicKeySpec spec=new RSAPublicKeySpec(modulus,exponent);
      RSAPublicKey genKey=(RSAPublicKey)factory.generatePublic(spec);
      Assert.assertEquals("Invalid public key",certificate.getPublicKey(),genKey);
    }
 else {
      X509DataType x509Data=(X509DataType)keyInfo.getContent().get(0);
      Assert.assertEquals("Unexpected X509 data content size",1,x509Data.getDataObjects().size());
      Object content=x509Data.getDataObjects().get(0);
      Assert.assertTrue("Unexpected X509 data content type",content instanceof X509CertificateType);
      byte[] encodedCertificate=((X509CertificateType)content).getEncodedCertificate();
      ByteArrayInputStream byteInputStream=new ByteArrayInputStream(Base64.decode(encodedCertificate,0,encodedCertificate.length));
      Assert.assertEquals("Invalid certificate in key info",certificate,CertificateFactory.getInstance("X.509").generateCertificate(byteInputStream));
    }
  }
}
 

Example 33

From project IOCipherServer, under directory /src/info/guardianproject/iocipher/server/.

Source file: CACertManager.java

  19 
vote

public String getFingerprint(Certificate cert,String type){
  try {
    MessageDigest md=MessageDigest.getInstance(type);
    byte[] publicKey=md.digest(cert.getEncoded());
    StringBuffer hexString=new StringBuffer();
    for (int i=0; i < publicKey.length; i++) {
      String appendString=Integer.toHexString(0xFF & publicKey[i]);
      if (appendString.length() == 1)       hexString.append("0");
      hexString.append(appendString);
      hexString.append(' ');
    }
    return hexString.toString();
  }
 catch (  Exception e1) {
    e1.printStackTrace();
    return null;
  }
}
 

Example 34

From project jboss-vfs, under directory /src/main/java/org/jboss/vfs/.

Source file: VirtualFile.java

  19 
vote

/** 
 * Get the  {@link Certificate}s for the virtual file.  Simply extracts the certificate entries from the code signers array.
 * @return the certificates for the virtual file, or {@code null} if not signed
 */
public Certificate[] getCertificates(){
  final CodeSigner[] codeSigners=getCodeSigners();
  if (codeSigners == null) {
    return null;
  }
  final List<Certificate> certList=new ArrayList<Certificate>(codeSigners.length * 3);
  for (  CodeSigner signer : codeSigners) {
    certList.addAll(signer.getSignerCertPath().getCertificates());
  }
  return certList.toArray(new Certificate[certList.size()]);
}
 

Example 35

From project jentrata-msh, under directory /Commons/src/main/java/hk/hku/cecid/piazza/commons/security/.

Source file: KeyStoreKeyManager.java

  19 
vote

/** 
 * Gets the certificate chain associated with the given alias.
 * @param alias the alias name.
 * @return the certificate chain.
 * @see javax.net.ssl.X509KeyManager#getCertificateChain(java.lang.String)
 */
public X509Certificate[] getCertificateChain(String alias){
  try {
    Certificate[] certs=keyStore.getCertificateChain(alias);
    X509Certificate[] xcerts=new X509Certificate[certs.length];
    System.arraycopy(certs,0,xcerts,0,certs.length);
    return xcerts;
  }
 catch (  Exception e) {
    throw new RuntimeException("Unable to retrieve certificate chain",e);
  }
}
 

Example 36

From project jspwiki, under directory /src/org/apache/wiki/auth/.

Source file: AuthorizationManager.java

  19 
vote

/** 
 * Checks to see if the local security policy allows a particular static Permission. Do not use this method for normal permission checks; use {@link #checkPermission(WikiSession,Permission)} instead.
 * @param principals the Principals to check
 * @param permission the Permission
 * @return the result
 */
protected boolean allowedByLocalPolicy(Principal[] principals,Permission permission){
  for (  Principal principal : principals) {
    ProtectionDomain pd=m_cachedPds.get(principal);
    if (pd == null) {
      ClassLoader cl=this.getClass().getClassLoader();
      CodeSource cs=new CodeSource(null,(Certificate[])null);
      pd=new ProtectionDomain(cs,null,cl,new Principal[]{principal});
      m_cachedPds.put(principal,pd);
    }
    if (m_localPolicy.implies(pd,permission)) {
      return true;
    }
  }
  return false;
}
 

Example 37

From project karaf, under directory /jaas/config/src/main/java/org/apache/karaf/jaas/config/impl/.

Source file: ResourceKeystoreInstance.java

  19 
vote

public Certificate getCertificate(String alias){
  if (!loadKeystoreData()) {
    return null;
  }
  try {
    return keystore.getCertificate(alias);
  }
 catch (  KeyStoreException e) {
    logger.error("Unable to read certificate from keystore",e);
  }
  return null;
}
 

Example 38

From project pdftk, under directory /java/com/lowagie/text/pdf/.

Source file: PdfSigGenericPKCS.java

  19 
vote

/** 
 * Sets the crypto information to sign.
 * @param privKey the private key
 * @param certChain the certificate chain
 * @param crlList the certificate revocation list. It can be <CODE>null</CODE>
 */
public void setSignInfo(PrivateKey privKey,Certificate[] certChain,CRL[] crlList){
  try {
    pkcs=new PdfPKCS7(privKey,certChain,crlList,hashAlgorithm,provider,PdfName.ADBE_PKCS7_SHA1.equals(get(PdfName.SUBFILTER)));
    pkcs.setExternalDigest(externalDigest,externalRSAdata,digestEncryptionAlgorithm);
    if (PdfName.ADBE_X509_RSA_SHA1.equals(get(PdfName.SUBFILTER))) {
      ByteArrayOutputStream bout=new ByteArrayOutputStream();
      for (int k=0; k < certChain.length; ++k) {
        bout.write(certChain[k].getEncoded());
      }
      bout.close();
      setCert(bout.toByteArray());
      setContents(pkcs.getEncodedPKCS1());
    }
 else     setContents(pkcs.getEncodedPKCS7());
    name=PdfPKCS7.getSubjectFields(pkcs.getSigningCertificate()).getField("CN");
    if (name != null)     put(PdfName.NAME,new PdfString(name,PdfObject.TEXT_UNICODE));
    pkcs=new PdfPKCS7(privKey,certChain,crlList,hashAlgorithm,provider,PdfName.ADBE_PKCS7_SHA1.equals(get(PdfName.SUBFILTER)));
    pkcs.setExternalDigest(externalDigest,externalRSAdata,digestEncryptionAlgorithm);
  }
 catch (  Exception e) {
    throw new ExceptionConverter(e);
  }
}
 

Example 39

From project Pitbull, under directory /pitbull-core/src/main/java/org/jboss/pitbull/internal/crypto/.

Source file: KeyTools.java

  19 
vote

public static KeyStore generateKeyStore() throws Exception {
  KeyPair keyPair=KeyPairGenerator.getInstance("RSA","BC").generateKeyPair();
  X509Certificate cert=KeyTools.generateSelfSignedCertificate(keyPair);
  KeyStore ks=KeyStore.getInstance("JKS");
  ks.load(null,null);
  Certificate[] certs={cert};
  ks.setKeyEntry("alias",keyPair.getPrivate(),new char[]{'p','a','s','s','w','o','r','d'},certs);
  return ks;
}
 

Example 40

From project platform_external_apache-http, under directory /src/org/apache/http/conn/ssl/.

Source file: AbstractVerifier.java

  19 
vote

public final void verify(String host,SSLSocket ssl) throws IOException {
  if (host == null) {
    throw new NullPointerException("host to verify is null");
  }
  SSLSession session=ssl.getSession();
  Certificate[] certs=session.getPeerCertificates();
  X509Certificate x509=(X509Certificate)certs[0];
  verify(host,x509);
}
 

Example 41

From project salem, under directory /src/haven/.

Source file: SslHelper.java

  19 
vote

public synchronized void trust(Certificate cert){
  clear();
  try {
    trusted.setCertificateEntry("cert-" + tserial++,cert);
  }
 catch (  KeyStoreException e) {
    throw (new RuntimeException(e));
  }
}
 

Example 42

From project serengeti-ws, under directory /vcext/src/main/java/com/vmware/serengeti/.

Source file: ThumbprintTrustManager.java

  19 
vote

/** 
 * Generates a thumbprint for a certificate
 * @param cert the certificate to generate a thumbprint for
 * @return the certificate thumbprint
 * @throws CertificateEncodingException
 */
public String certificateToThumbprint(Certificate cert) throws CertificateEncodingException {
  sha1.reset();
  try {
    return toHex(sha1.digest(cert.getEncoded()),":");
  }
 catch (  CertificateEncodingException e) {
    logger.error(e);
    throw e;
  }
}
 

Example 43

From project smsc-server, under directory /core/src/main/java/org/apache/smscserver/impl/.

Source file: DefaultSmscIoSession.java

  19 
vote

public Certificate[] getClientCertificates(){
  if (this.getFilterChain().contains(SslFilter.class)) {
    SslFilter sslFilter=(SslFilter)this.getFilterChain().get(SslFilter.class);
    SSLSession sslSession=sslFilter.getSslSession(this);
    if (sslSession != null) {
      try {
        return sslSession.getPeerCertificates();
      }
 catch (      SSLPeerUnverifiedException e) {
      }
    }
  }
  return null;
}
 

Example 44

From project stone-for-Android, under directory /src/jp/klab/stone/certinstaller/.

Source file: CredentialHelper.java

  19 
vote

private synchronized boolean installFrom(PrivateKeyEntry entry){
  mUserKey=entry.getPrivateKey();
  mUserCert=(X509Certificate)entry.getCertificate();
  Certificate[] certs=entry.getCertificateChain();
  Log.d(TAG,"# certs extracted = " + certs.length);
  List<X509Certificate> caCerts=mCaCerts=new ArrayList<X509Certificate>(certs.length);
  for (  Certificate c : certs) {
    X509Certificate cert=(X509Certificate)c;
    if (isCa(cert))     caCerts.add(cert);
  }
  Log.d(TAG,"# ca certs extracted = " + mCaCerts.size());
  return true;
}
 

Example 45

From project Vega, under directory /platform/com.subgraph.vega.http.proxy/src/com/subgraph/vega/internal/http/proxy/ssl/.

Source file: CertificateStore.java

  19 
vote

private boolean loadFromFile() throws GeneralSecurityException, IOException {
  InputStream input=null;
  try {
    input=new FileInputStream(storeFile);
    keyStore.load(input,password);
    caPrivateKey=(PrivateKey)keyStore.getKey(STORE_KEY,password);
    final Certificate[] chain=keyStore.getCertificateChain(STORE_KEY);
    caCertificate=(X509Certificate)chain[0];
    return true;
  }
 catch (  FileNotFoundException e) {
    return false;
  }
 finally {
    if (input != null)     input.close();
  }
}
 

Example 46

From project WaarpCommon, under directory /src/main/java/org/waarp/common/crypto/ssl/.

Source file: WaarpSecureKeyStore.java

  19 
vote

/** 
 * Add a Key and its certificates into the KeyStore based on its alias
 * @param alias
 * @param key
 * @param chain
 * @return True if entry is added
 */
public boolean setKeytoKeyStore(String alias,Key key,Certificate[] chain){
  try {
    keyStore.setKeyEntry(alias,key,getCertificatePassword(),chain);
  }
 catch (  KeyStoreException e) {
    logger.error("Cannot add Key and Certificates to KeyStore Instance",e);
    return false;
  }
  return true;
}