use of org.openecard.bouncycastle.asn1.x500.X500Name in project oxTrust by GluuFederation.
the class UpdateTrustRelationshipAction method getCertForGeneratedSP.
/**
* If there is no certificate selected, or certificate is invalid -
* generates one.
*
* @author �Oleksiy Tataryn�
* @return certificate for generated SP
* @throws IOException
* @throws CertificateEncodingException
*/
public String getCertForGeneratedSP() throws IOException {
X509Certificate cert = null;
if ((certWrapper != null) && (certWrapper.getInputStream() != null)) {
try {
cert = sslService.getPEMCertificate(certWrapper.getInputStream());
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
if ((cert == null) && (trustRelationship.getUrl() != null)) {
facesMessages.add(FacesMessage.SEVERITY_ERROR, "Certificate were not provided, or was incorrect. Appliance will create a self-signed certificate.");
if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
Security.addProvider(new BouncyCastleProvider());
}
try {
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA", "BC");
keyPairGen.initialize(2048);
KeyPair pair = keyPairGen.generateKeyPair();
StringWriter keyWriter = new StringWriter();
PEMWriter pemFormatWriter = new PEMWriter(keyWriter);
pemFormatWriter.writeObject(pair.getPrivate());
pemFormatWriter.close();
String url = trustRelationship.getUrl().replaceFirst(".*//", "");
X509v3CertificateBuilder v3CertGen = new JcaX509v3CertificateBuilder(new X500Name("CN=" + url + ", OU=None, O=None L=None, C=None"), BigInteger.valueOf(new SecureRandom().nextInt()), new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30), new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10)), new X500Name("CN=" + url + ", OU=None, O=None L=None, C=None"), pair.getPublic());
cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(v3CertGen.build(new JcaContentSignerBuilder("MD5withRSA").setProvider("BC").build(pair.getPrivate())));
org.apache.commons.codec.binary.Base64 encoder = new org.apache.commons.codec.binary.Base64(64);
byte[] derCert = cert.getEncoded();
String pemCertPre = new String(encoder.encode(derCert));
log.debug(Shibboleth3ConfService.PUBLIC_CERTIFICATE_START_LINE);
log.debug(pemCertPre);
log.debug(Shibboleth3ConfService.PUBLIC_CERTIFICATE_END_LINE);
shibboleth3ConfService.saveCert(trustRelationship, pemCertPre);
shibboleth3ConfService.saveKey(trustRelationship, keyWriter.toString());
} catch (Exception e) {
e.printStackTrace();
}
// String certName = appConfiguration.getCertDir() + File.separator + StringHelper.removePunctuation(appConfiguration.getOrgInum())
// + "-shib.crt";
// File certFile = new File(certName);
// if (certFile.exists()) {
// cert = SSLService.instance().getPEMCertificate(certName);
// }
}
String certificate = null;
if (cert != null) {
try {
certificate = new String(Base64.encode(cert.getEncoded()));
log.info("##### certificate = " + certificate);
} catch (CertificateEncodingException e) {
certificate = null;
facesMessages.add(FacesMessage.SEVERITY_ERROR, "Failed to encode provided certificate. Please notify Gluu support about this.");
log.error("Failed to encode certificate to DER", e);
}
} else {
facesMessages.add(FacesMessage.SEVERITY_ERROR, "Certificate were not provided, or was incorrect. Appliance will create a self-signed certificate.");
}
return certificate;
}
use of org.openecard.bouncycastle.asn1.x500.X500Name in project oxTrust by GluuFederation.
the class TrustRelationshipWebService method generateCertForGeneratedSP.
/**
* @return certificate for generated SP
* @throws IOException
* @throws CertificateEncodingException
*/
public String generateCertForGeneratedSP(GluuSAMLTrustRelationship trustRelationship) throws IOException {
X509Certificate cert = null;
// facesMessages.add(FacesMessage.SEVERITY_ERROR, "Certificate were not provided, or was incorrect. Appliance will create a self-signed certificate.");
if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
Security.addProvider(new BouncyCastleProvider());
}
try {
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA", "BC");
keyPairGen.initialize(2048);
KeyPair pair = keyPairGen.generateKeyPair();
StringWriter keyWriter = new StringWriter();
PEMWriter pemFormatWriter = new PEMWriter(keyWriter);
pemFormatWriter.writeObject(pair.getPrivate());
pemFormatWriter.close();
String url = trustRelationship.getUrl().replaceFirst(".*//", "");
X509v3CertificateBuilder v3CertGen = new JcaX509v3CertificateBuilder(new X500Name("CN=" + url + ", OU=None, O=None L=None, C=None"), BigInteger.valueOf(new SecureRandom().nextInt()), new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30), new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10)), new X500Name("CN=" + url + ", OU=None, O=None L=None, C=None"), pair.getPublic());
cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(v3CertGen.build(new JcaContentSignerBuilder("MD5withRSA").setProvider("BC").build(pair.getPrivate())));
org.apache.commons.codec.binary.Base64 encoder = new org.apache.commons.codec.binary.Base64(64);
byte[] derCert = cert.getEncoded();
String pemCertPre = new String(encoder.encode(derCert));
logger.debug(Shibboleth3ConfService.PUBLIC_CERTIFICATE_START_LINE);
logger.debug(pemCertPre);
logger.debug(Shibboleth3ConfService.PUBLIC_CERTIFICATE_END_LINE);
shibboleth3ConfService.saveCert(trustRelationship, pemCertPre);
shibboleth3ConfService.saveKey(trustRelationship, keyWriter.toString());
} catch (Exception e) {
e.printStackTrace();
logger.error("Failed to generate certificate", e);
}
// String certName = appConfiguration.getCertDir() + File.separator + StringHelper.removePunctuation(appConfiguration.getOrgInum())
// + "-shib.crt";
// File certFile = new File(certName);
// if (certFile.exists()) {
// cert = SSLService.instance().getPEMCertificate(certName);
// }
String certificate = null;
if (cert != null) {
try {
certificate = new String(Base64.encode(cert.getEncoded()));
logger.info("##### certificate = " + certificate);
} catch (CertificateEncodingException e) {
certificate = null;
// facesMessages.add(FacesMessage.SEVERITY_ERROR, "Failed to encode provided certificate. Please notify Gluu support about this.");
logger.error("Failed to encode certificate to DER", e);
}
} else {
// facesMessages.add(FacesMessage.SEVERITY_ERROR, "Certificate were not provided, or was incorrect. Appliance will create a self-signed certificate.");
}
return certificate;
}
use of org.openecard.bouncycastle.asn1.x500.X500Name in project Payara by payara.
the class SecurityMechanismSelector method getIdentity.
/**
* Get the principal/distinguished name from thread local storage.
*
* @return the security context.
*/
private SecurityContext getIdentity() throws SecurityMechanismException {
if (_logger.isLoggable(Level.FINE)) {
_logger.log(Level.FINE, "Getting PRINCIPAL/DN from TLS");
}
SecurityContext ctx = new SecurityContext();
final SecurityContext sCtx = ctx;
// get stuff from the SecurityContext class
com.sun.enterprise.security.SecurityContext scontext = com.sun.enterprise.security.SecurityContext.getCurrent();
if ((scontext == null) || scontext.didServerGenerateCredentials()) {
// a default guest/guest123 was created
sCtx.identcls = AnonCredential.class;
AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public java.lang.Object run() {
// remove all the public and private credentials
Subject sub = new Subject();
sCtx.subject = sub;
sCtx.subject.getPublicCredentials().add(new AnonCredential());
return null;
}
});
return sCtx;
}
Subject s = getSubjectFromSecurityCurrent();
ctx.subject = s;
// Figure out the credential class
final Subject sub = s;
Set<PasswordCredential> credSet = AccessController.doPrivileged(new PrivilegedAction<Set>() {
@Override
public Set run() {
return sub.getPrivateCredentials(PasswordCredential.class);
}
});
if (credSet.size() == 1) {
ctx.identcls = GSSUPName.class;
final Set cs = credSet;
Subject subj = AccessController.doPrivileged(new PrivilegedAction<Subject>() {
@Override
public Subject run() {
Subject ss = new Subject();
Iterator<PasswordCredential> iter = cs.iterator();
PasswordCredential pc = iter.next();
GSSUPName gssname = new GSSUPName(pc.getUser(), pc.getRealm());
ss.getPublicCredentials().add(gssname);
return ss;
}
});
ctx.subject = subj;
return ctx;
}
Set pubCredSet = s.getPublicCredentials();
if (pubCredSet.size() != 1) {
_logger.log(Level.SEVERE, "iiop.principal_error");
return null;
} else {
Iterator credIter = pubCredSet.iterator();
if (credIter.hasNext()) {
Object o = credIter.next();
if (o instanceof GSSUPName) {
ctx.identcls = GSSUPName.class;
} else if (o instanceof X500Name) {
ctx.identcls = X500Name.class;
} else {
ctx.identcls = X509CertificateCredential.class;
}
} else {
_logger.log(Level.SEVERE, "iiop.credential_error");
return null;
}
}
return ctx;
}
use of org.openecard.bouncycastle.asn1.x500.X500Name in project Payara by payara.
the class JarSigner method signJar.
/**
* Signs a JAR, adding caller-specified attributes to the manifest's main attrs and also
* inserting (and signing) additional caller-supplied content as new entries in the
* zip output stream.
* @param input input JAR file
* @param zout Zip output stream created
* @param alias signing alias in the keystore
* @param additionalAttrs additional attributes to add to the manifest's main attrs (null if none)
* @param additionalEntries entry-name/byte[] pairs of additional content to add to the signed output
* @throws IOException
* @throws KeyStoreException
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
* @throws UnrecoverableKeyException
* @throws SignatureException
*/
public void signJar(File input, ZipOutputStream zout, String alias, final Attributes additionalAttrs, Map<String, byte[]> additionalEntries) throws IOException, KeyStoreException, NoSuchAlgorithmException, InvalidKeyException, UnrecoverableKeyException, SignatureException {
JarFile jf = new JarFile(input);
try {
Enumeration<JarEntry> jes;
// manifestEntries is content of META-INF/MANIFEST.MF
StringBuilder manifestEntries = new StringBuilder();
byte[] manifestContent;
byte[] sigFileContent = getExistingSignatureFile(jf);
boolean signed = (sigFileContent != null);
if (!signed || !additionalEntries.isEmpty()) {
// manifestHeader is header of META-INF/MANIFEST.MF, initialized to default
jes = jf.entries();
Manifest manifest = retrieveManifest(jf);
StringBuilder manifestHeader = new StringBuilder();
Attributes mfAttrs = manifest.getMainAttributes();
if (additionalAttrs != null) {
mfAttrs.putAll(additionalAttrs);
}
appendAttributes(manifestHeader, mfAttrs);
// sigFileEntries is content of META-INF/ME.SF
StringBuilder sigFileEntries = new StringBuilder();
while (jes.hasMoreElements()) {
JarEntry je = jes.nextElement();
String name = je.getName();
if ((je.isDirectory() && manifest.getAttributes(name) == null) || name.equals(JarFile.MANIFEST_NAME)) {
continue;
}
processMetadataForEntry(manifest, manifestEntries, sigFileEntries, name, readJarEntry(jf, je));
}
if (additionalEntries != null) {
for (Map.Entry<String, byte[]> entry : additionalEntries.entrySet()) {
processMetadataForEntry(manifest, manifestEntries, sigFileEntries, entry.getKey(), entry.getValue());
}
}
// META-INF/ME.SF
StringBuilder sigFile = new StringBuilder("Signature-Version: 1.0\r\n").append(digestAlgorithm).append("-Digest-Manifest-Main-Attributes: ").append(hash(manifestHeader.toString())).append("\r\n").append("Created-By: ").append(System.getProperty("java.version")).append(" (").append(System.getProperty("java.vendor")).append(")\r\n");
// Combine header and content of MANIFEST.MF, and rehash
manifestHeader.append(manifestEntries);
sigFile.append(digestAlgorithm).append("-Digest-Manifest: ").append(hash(manifestHeader.toString())).append("\r\n\r\n");
// Combine header and content of ME.SF
sigFile.append(sigFileEntries);
manifestContent = manifestHeader.toString().getBytes();
sigFileContent = sigFile.toString().getBytes();
} else {
manifestContent = readJarEntry(jf, jf.getJarEntry(JarFile.MANIFEST_NAME));
}
X509Certificate[] certChain = null;
PrivateKey privKey = null;
KeyStore[] ks = securitySupport.getKeyStores();
for (int i = 0; i < ks.length; i++) {
privKey = securitySupport.getPrivateKeyForAlias(alias, i);
if (privKey != null) {
Certificate[] cs = ks[i].getCertificateChain(alias);
certChain = new X509Certificate[cs.length];
for (int j = 0; j < cs.length; j++) {
certChain[j] = (X509Certificate) cs[j];
}
}
}
// Sign ME.SF
Signature sig = Signature.getInstance(digestAlgorithm + "with" + keyAlgorithm);
sig.initSign(privKey);
sig.update(sigFileContent);
// Create PKCS7 block
PKCS7 pkcs7 = new PKCS7(new AlgorithmId[] { AlgorithmId.get(digestAlgorithm) }, new ContentInfo(sigFileContent), certChain, new SignerInfo[] { new SignerInfo((X500Name) certChain[0].getIssuerDN(), certChain[0].getSerialNumber(), AlgorithmId.get(digestAlgorithm), AlgorithmId.get(keyAlgorithm), sig.sign()) });
ByteArrayOutputStream bout = new ByteArrayOutputStream();
pkcs7.encodeSignedData(bout);
// Write output
zout.putNextEntry((signed) ? getZipEntry(jf.getJarEntry(JarFile.MANIFEST_NAME)) : new ZipEntry(JarFile.MANIFEST_NAME));
zout.write(manifestContent);
zout.putNextEntry(new ZipEntry("META-INF/" + alias.toUpperCase(Locale.US) + ".SF"));
zout.write(sigFileContent);
zout.putNextEntry(new ZipEntry("META-INF/" + alias.toUpperCase(Locale.US) + "." + keyAlgorithm));
zout.write(bout.toByteArray());
jes = jf.entries();
while (jes.hasMoreElements()) {
JarEntry je = jes.nextElement();
String name = je.getName();
if (!name.equals(JarFile.MANIFEST_NAME)) {
zout.putNextEntry(getZipEntry(je));
byte[] data = readJarEntry(jf, je);
zout.write(data);
}
}
if (additionalEntries != null) {
for (Map.Entry<String, byte[]> entry : additionalEntries.entrySet()) {
final ZipEntry newZipEntry = new ZipEntry(entry.getKey());
zout.putNextEntry(newZipEntry);
zout.write(entry.getValue());
}
}
} finally {
jf.close();
}
}
use of org.openecard.bouncycastle.asn1.x500.X500Name in project Payara by payara.
the class LoginContextDriver method jmacLogin.
public static Subject jmacLogin(Subject subject, X500Principal x500Principal) throws LoginException {
if (subject == null) {
subject = new Subject();
}
final Subject fs = subject;
String userName = "";
try {
final X500Name x500Name = new X500Name(x500Principal.getName(X500Principal.RFC1779));
userName = x500Name.toString();
AppservAccessController.doPrivileged(new PrivilegedAction() {
public java.lang.Object run() {
fs.getPublicCredentials().add(x500Name);
return fs;
}
});
Realm realm = Realm.getInstance(CertificateRealm.AUTH_TYPE);
CertificateRealm certRealm = (CertificateRealm) realm;
String jaasCtx = certRealm.getJAASContext();
if (jaasCtx != null) {
// The subject has the Cretificate Credential.
LoginContext lg = new LoginContext(jaasCtx, fs, dummyCallback);
lg.login();
}
certRealm.authenticate(fs, x500Name);
} catch (Exception ex) {
if (_logger.isLoggable(Level.INFO)) {
_logger.log(Level.INFO, SecurityLoggerInfo.auditAtnRefusedError, userName);
}
if (getAuditManager().isAuditOn()) {
getAuditManager().authentication(userName, CertificateRealm.AUTH_TYPE, false);
}
if (ex instanceof LoginException) {
throw (LoginException) ex;
} else {
throw (LoginException) new LoginException(ex.toString()).initCause(ex);
}
}
if (_logger.isLoggable(Level.FINE)) {
_logger.fine("jmac cert login succeeded for: " + userName);
}
if (getAuditManager().isAuditOn()) {
getAuditManager().authentication(userName, CertificateRealm.AUTH_TYPE, true);
}
return subject;
}
Aggregations