use of java.security.cert.CertificateEncodingException in project XobotOS by xamarin.
the class PKIXCertPath method getEncoded.
/**
* Returns the encoded form of this certification path, using
* the specified encoding.
*
* @param encoding the name of the encoding to use
* @return the encoded bytes
* @exception CertificateEncodingException if an encoding error
* occurs or the encoding requested is not supported
*
**/
public byte[] getEncoded(String encoding) throws CertificateEncodingException {
if (encoding.equalsIgnoreCase("PkiPath")) {
ASN1EncodableVector v = new ASN1EncodableVector();
ListIterator iter = certificates.listIterator(certificates.size());
while (iter.hasPrevious()) {
v.add(toASN1Object((X509Certificate) iter.previous()));
}
return toDEREncoded(new DERSequence(v));
} else if (encoding.equalsIgnoreCase("PKCS7")) {
ContentInfo encInfo = new ContentInfo(PKCSObjectIdentifiers.data, null);
ASN1EncodableVector v = new ASN1EncodableVector();
for (int i = 0; i != certificates.size(); i++) {
v.add(toASN1Object((X509Certificate) certificates.get(i)));
}
SignedData sd = new SignedData(new DERInteger(1), new DERSet(), encInfo, new DERSet(v), null, new DERSet());
return toDEREncoded(new ContentInfo(PKCSObjectIdentifiers.signedData, sd));
} else // BEGIN android-removed
// else if (encoding.equalsIgnoreCase("PEM"))
// {
// ByteArrayOutputStream bOut = new ByteArrayOutputStream();
// PEMWriter pWrt = new PEMWriter(new OutputStreamWriter(bOut));
//
// try
// {
// for (int i = 0; i != certificates.size(); i++)
// {
// pWrt.writeObject(certificates.get(i));
// }
//
// pWrt.close();
// }
// catch (Exception e)
// {
// throw new CertificateEncodingException("can't encode certificate for PEM encoded path");
// }
//
// return bOut.toByteArray();
// }
// END android-removed
{
throw new CertificateEncodingException("unsupported encoding: " + encoding);
}
}
use of java.security.cert.CertificateEncodingException in project XobotOS by xamarin.
the class JDKPKCS12KeyStore method doStore.
private void doStore(OutputStream stream, char[] password, boolean useDEREncoding) throws IOException {
if (password == null) {
throw new NullPointerException("No password supplied for PKCS#12 KeyStore.");
}
//
// handle the key
//
ASN1EncodableVector keyS = new ASN1EncodableVector();
Enumeration ks = keys.keys();
while (ks.hasMoreElements()) {
byte[] kSalt = new byte[SALT_SIZE];
random.nextBytes(kSalt);
String name = (String) ks.nextElement();
PrivateKey privKey = (PrivateKey) keys.get(name);
PKCS12PBEParams kParams = new PKCS12PBEParams(kSalt, MIN_ITERATIONS);
byte[] kBytes = wrapKey(keyAlgorithm.getId(), privKey, kParams, password);
AlgorithmIdentifier kAlgId = new AlgorithmIdentifier(keyAlgorithm, kParams.getDERObject());
org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo kInfo = new org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo(kAlgId, kBytes);
boolean attrSet = false;
ASN1EncodableVector kName = new ASN1EncodableVector();
if (privKey instanceof PKCS12BagAttributeCarrier) {
PKCS12BagAttributeCarrier bagAttrs = (PKCS12BagAttributeCarrier) privKey;
//
// make sure we are using the local alias on store
//
DERBMPString nm = (DERBMPString) bagAttrs.getBagAttribute(pkcs_9_at_friendlyName);
if (nm == null || !nm.getString().equals(name)) {
bagAttrs.setBagAttribute(pkcs_9_at_friendlyName, new DERBMPString(name));
}
//
if (bagAttrs.getBagAttribute(pkcs_9_at_localKeyId) == null) {
Certificate ct = engineGetCertificate(name);
bagAttrs.setBagAttribute(pkcs_9_at_localKeyId, createSubjectKeyId(ct.getPublicKey()));
}
Enumeration e = bagAttrs.getBagAttributeKeys();
while (e.hasMoreElements()) {
DERObjectIdentifier oid = (DERObjectIdentifier) e.nextElement();
ASN1EncodableVector kSeq = new ASN1EncodableVector();
kSeq.add(oid);
kSeq.add(new DERSet(bagAttrs.getBagAttribute(oid)));
attrSet = true;
kName.add(new DERSequence(kSeq));
}
}
if (!attrSet) {
//
// set a default friendly name (from the key id) and local id
//
ASN1EncodableVector kSeq = new ASN1EncodableVector();
Certificate ct = engineGetCertificate(name);
kSeq.add(pkcs_9_at_localKeyId);
kSeq.add(new DERSet(createSubjectKeyId(ct.getPublicKey())));
kName.add(new DERSequence(kSeq));
kSeq = new ASN1EncodableVector();
kSeq.add(pkcs_9_at_friendlyName);
kSeq.add(new DERSet(new DERBMPString(name)));
kName.add(new DERSequence(kSeq));
}
SafeBag kBag = new SafeBag(pkcs8ShroudedKeyBag, kInfo.getDERObject(), new DERSet(kName));
keyS.add(kBag);
}
byte[] keySEncoded = new DERSequence(keyS).getDEREncoded();
BERConstructedOctetString keyString = new BERConstructedOctetString(keySEncoded);
//
// certificate processing
//
byte[] cSalt = new byte[SALT_SIZE];
random.nextBytes(cSalt);
ASN1EncodableVector certSeq = new ASN1EncodableVector();
PKCS12PBEParams cParams = new PKCS12PBEParams(cSalt, MIN_ITERATIONS);
AlgorithmIdentifier cAlgId = new AlgorithmIdentifier(certAlgorithm, cParams.getDERObject());
Hashtable doneCerts = new Hashtable();
Enumeration cs = keys.keys();
while (cs.hasMoreElements()) {
try {
String name = (String) cs.nextElement();
Certificate cert = engineGetCertificate(name);
boolean cAttrSet = false;
CertBag cBag = new CertBag(x509Certificate, new DEROctetString(cert.getEncoded()));
ASN1EncodableVector fName = new ASN1EncodableVector();
if (cert instanceof PKCS12BagAttributeCarrier) {
PKCS12BagAttributeCarrier bagAttrs = (PKCS12BagAttributeCarrier) cert;
//
// make sure we are using the local alias on store
//
DERBMPString nm = (DERBMPString) bagAttrs.getBagAttribute(pkcs_9_at_friendlyName);
if (nm == null || !nm.getString().equals(name)) {
bagAttrs.setBagAttribute(pkcs_9_at_friendlyName, new DERBMPString(name));
}
//
if (bagAttrs.getBagAttribute(pkcs_9_at_localKeyId) == null) {
bagAttrs.setBagAttribute(pkcs_9_at_localKeyId, createSubjectKeyId(cert.getPublicKey()));
}
Enumeration e = bagAttrs.getBagAttributeKeys();
while (e.hasMoreElements()) {
DERObjectIdentifier oid = (DERObjectIdentifier) e.nextElement();
ASN1EncodableVector fSeq = new ASN1EncodableVector();
fSeq.add(oid);
fSeq.add(new DERSet(bagAttrs.getBagAttribute(oid)));
fName.add(new DERSequence(fSeq));
cAttrSet = true;
}
}
if (!cAttrSet) {
ASN1EncodableVector fSeq = new ASN1EncodableVector();
fSeq.add(pkcs_9_at_localKeyId);
fSeq.add(new DERSet(createSubjectKeyId(cert.getPublicKey())));
fName.add(new DERSequence(fSeq));
fSeq = new ASN1EncodableVector();
fSeq.add(pkcs_9_at_friendlyName);
fSeq.add(new DERSet(new DERBMPString(name)));
fName.add(new DERSequence(fSeq));
}
SafeBag sBag = new SafeBag(certBag, cBag.getDERObject(), new DERSet(fName));
certSeq.add(sBag);
doneCerts.put(cert, cert);
} catch (CertificateEncodingException e) {
throw new IOException("Error encoding certificate: " + e.toString());
}
}
cs = certs.keys();
while (cs.hasMoreElements()) {
try {
String certId = (String) cs.nextElement();
Certificate cert = (Certificate) certs.get(certId);
boolean cAttrSet = false;
if (keys.get(certId) != null) {
continue;
}
CertBag cBag = new CertBag(x509Certificate, new DEROctetString(cert.getEncoded()));
ASN1EncodableVector fName = new ASN1EncodableVector();
if (cert instanceof PKCS12BagAttributeCarrier) {
PKCS12BagAttributeCarrier bagAttrs = (PKCS12BagAttributeCarrier) cert;
//
// make sure we are using the local alias on store
//
DERBMPString nm = (DERBMPString) bagAttrs.getBagAttribute(pkcs_9_at_friendlyName);
if (nm == null || !nm.getString().equals(certId)) {
bagAttrs.setBagAttribute(pkcs_9_at_friendlyName, new DERBMPString(certId));
}
Enumeration e = bagAttrs.getBagAttributeKeys();
while (e.hasMoreElements()) {
DERObjectIdentifier oid = (DERObjectIdentifier) e.nextElement();
// If we find one, we'll prune it out.
if (oid.equals(PKCSObjectIdentifiers.pkcs_9_at_localKeyId)) {
continue;
}
ASN1EncodableVector fSeq = new ASN1EncodableVector();
fSeq.add(oid);
fSeq.add(new DERSet(bagAttrs.getBagAttribute(oid)));
fName.add(new DERSequence(fSeq));
cAttrSet = true;
}
}
if (!cAttrSet) {
ASN1EncodableVector fSeq = new ASN1EncodableVector();
fSeq.add(pkcs_9_at_friendlyName);
fSeq.add(new DERSet(new DERBMPString(certId)));
fName.add(new DERSequence(fSeq));
}
SafeBag sBag = new SafeBag(certBag, cBag.getDERObject(), new DERSet(fName));
certSeq.add(sBag);
doneCerts.put(cert, cert);
} catch (CertificateEncodingException e) {
throw new IOException("Error encoding certificate: " + e.toString());
}
}
cs = chainCerts.keys();
while (cs.hasMoreElements()) {
try {
CertId certId = (CertId) cs.nextElement();
Certificate cert = (Certificate) chainCerts.get(certId);
if (doneCerts.get(cert) != null) {
continue;
}
CertBag cBag = new CertBag(x509Certificate, new DEROctetString(cert.getEncoded()));
ASN1EncodableVector fName = new ASN1EncodableVector();
if (cert instanceof PKCS12BagAttributeCarrier) {
PKCS12BagAttributeCarrier bagAttrs = (PKCS12BagAttributeCarrier) cert;
Enumeration e = bagAttrs.getBagAttributeKeys();
while (e.hasMoreElements()) {
DERObjectIdentifier oid = (DERObjectIdentifier) e.nextElement();
// If we find one, we'll prune it out.
if (oid.equals(PKCSObjectIdentifiers.pkcs_9_at_localKeyId)) {
continue;
}
ASN1EncodableVector fSeq = new ASN1EncodableVector();
fSeq.add(oid);
fSeq.add(new DERSet(bagAttrs.getBagAttribute(oid)));
fName.add(new DERSequence(fSeq));
}
}
SafeBag sBag = new SafeBag(certBag, cBag.getDERObject(), new DERSet(fName));
certSeq.add(sBag);
} catch (CertificateEncodingException e) {
throw new IOException("Error encoding certificate: " + e.toString());
}
}
byte[] certSeqEncoded = new DERSequence(certSeq).getDEREncoded();
byte[] certBytes = cryptData(true, cAlgId, password, false, certSeqEncoded);
EncryptedData cInfo = new EncryptedData(data, cAlgId, new BERConstructedOctetString(certBytes));
ContentInfo[] info = new ContentInfo[] { new ContentInfo(data, keyString), new ContentInfo(encryptedData, cInfo.getDERObject()) };
AuthenticatedSafe auth = new AuthenticatedSafe(info);
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
DEROutputStream asn1Out;
if (useDEREncoding) {
asn1Out = new DEROutputStream(bOut);
} else {
asn1Out = new BEROutputStream(bOut);
}
asn1Out.writeObject(auth);
byte[] pkg = bOut.toByteArray();
ContentInfo mainInfo = new ContentInfo(data, new BERConstructedOctetString(pkg));
//
// create the mac
//
byte[] mSalt = new byte[20];
int itCount = MIN_ITERATIONS;
random.nextBytes(mSalt);
byte[] data = ((ASN1OctetString) mainInfo.getContent()).getOctets();
MacData mData;
try {
byte[] res = calculatePbeMac(id_SHA1, mSalt, itCount, password, false, data);
// BEGIN android-changed
AlgorithmIdentifier algId = new AlgorithmIdentifier(id_SHA1, DERNull.INSTANCE);
// END android-changed
DigestInfo dInfo = new DigestInfo(algId, res);
mData = new MacData(dInfo, mSalt, itCount);
} catch (Exception e) {
throw new IOException("error constructing MAC: " + e.toString());
}
//
// output the Pfx
//
Pfx pfx = new Pfx(mainInfo, mData);
if (useDEREncoding) {
asn1Out = new DEROutputStream(stream);
} else {
asn1Out = new BEROutputStream(stream);
}
asn1Out.writeObject(pfx);
}
use of java.security.cert.CertificateEncodingException in project OpenAM by OpenRock.
the class CertificateAuthenticationRequestDispatcher method postCertInHeader.
private String postCertInHeader(URL url, X509Certificate certificate, AuthTargetMapping.AuthTarget target) throws TokenValidationException {
final String base64Certificate;
try {
base64Certificate = Base64.encode(certificate.getEncoded());
} catch (CertificateEncodingException e) {
throw new TokenValidationException(org.forgerock.json.resource.ResourceException.BAD_REQUEST, "Could not obtain the base64-encoded representation of the client certificate: " + e, e);
}
if (target == null) {
throw new TokenValidationException(org.forgerock.json.resource.ResourceException.BAD_REQUEST, "When validatating X509 Certificates, an AuthTarget needs to be configured with a Map containing a String " + "entry referenced by key" + AMSTSConstants.X509_TOKEN_AUTH_TARGET_HEADER_KEY + " which specifies the header name which will reference the client's X509 Certificate.");
}
Object headerKey = target.getContext().get(AMSTSConstants.X509_TOKEN_AUTH_TARGET_HEADER_KEY);
if (!(headerKey instanceof String)) {
//checks both for null and String
throw new TokenValidationException(org.forgerock.json.resource.ResourceException.BAD_REQUEST, "When validatating X509 Certificates, an AuthTarget needs to be configured with a Map containing a String " + "entry referenced by key" + AMSTSConstants.X509_TOKEN_AUTH_TARGET_HEADER_KEY + " which specifies the header name which will reference the client's X509 Certificate.");
}
try {
Map<String, String> headerMap = new HashMap<>();
headerMap.put(AMSTSConstants.CONTENT_TYPE, AMSTSConstants.APPLICATION_JSON);
headerMap.put(AMSTSConstants.CREST_VERSION_HEADER_KEY, crestVersionAuthNService);
headerMap.put((String) headerKey, base64Certificate);
HttpURLConnectionWrapper.ConnectionResult connectionResult = httpURLConnectionWrapperFactory.httpURLConnectionWrapper(url).setRequestHeaders(headerMap).setRequestMethod(AMSTSConstants.POST).makeInvocation();
final int responseCode = connectionResult.getStatusCode();
if (responseCode != HttpURLConnection.HTTP_OK) {
throw new TokenValidationException(responseCode, "Non-200 response from posting x509 token " + "to rest authN: " + connectionResult.getResult());
} else {
return connectionResult.getResult();
}
} catch (IOException e) {
throw new TokenValidationException(org.forgerock.json.resource.ResourceException.INTERNAL_ERROR, "Exception caught posting x509 token to rest authN: " + e, e);
}
}
use of java.security.cert.CertificateEncodingException in project OpenAM by OpenRock.
the class CreateMetaDataModelImpl method createWSFedProvider.
/**
* Creates a WS Federation provider.
*
* @param realm Realm Name.
* @param entityId Entity Id.
* @param values Map of property name to values.
*
* @throws AMConsoleException if duplicate metaAliases provided or unable to create or import metadata.
* */
public void createWSFedProvider(String realm, String entityId, Map values) throws AMConsoleException {
try {
List<String> metaAliases = getFederationAlias(values, MetaTemplateParameters.P_WS_FED_ALIASES);
Set<String> duplicateCheck = new HashSet<String>(metaAliases);
if (duplicateCheck.size() < metaAliases.size()) {
throw new AMConsoleException(getLocalizedString("federation.create.provider.duplicate.metaAlias"));
}
WSFederationMetaManager metaManager = new WSFederationMetaManager();
metaManager.validateMetaAliasForNewEntity(realm, metaAliases);
String metadata = CreateWSFedMetaDataTemplate.createStandardMetaTemplate(entityId, values, requestURL);
String extendedData = CreateWSFedMetaDataTemplate.createExtendedMetaTemplate(entityId, values);
FederationElement elt = (FederationElement) WSFederationMetaUtils.convertStringToJAXB(metadata);
String federationID = elt.getFederationID();
if (federationID == null) {
federationID = WSFederationConstants.DEFAULT_FEDERATION_ID;
}
metaManager.createFederation(realm, elt);
FederationConfigElement cfg = (FederationConfigElement) WSFederationMetaUtils.convertStringToJAXB(extendedData);
metaManager.createEntityConfig(realm, cfg);
} catch (WSFederationMetaException ex) {
throw new AMConsoleException(ex.getMessage());
} catch (JAXBException ex) {
throw new AMConsoleException(ex.getMessage());
} catch (CertificateEncodingException ex) {
throw new AMConsoleException(ex.getMessage());
}
}
use of java.security.cert.CertificateEncodingException in project OpenAM by OpenRock.
the class CreateMetaDataTemplate method buildWSFedDescriptorTemplate.
private void buildWSFedDescriptorTemplate() throws CLIException {
Writer pw = null;
try {
boolean writeToFile = !isWebBased && (metadata != null) && (metadata.length() > 0);
if (writeToFile) {
pw = new PrintWriter(new FileWriter(metadata));
} else {
pw = new StringWriter();
}
String xml = CreateWSFedMetaDataTemplate.createStandardMetaTemplate(entityID, getWorkflowParamMap(), protocol + "://" + host + ":" + port + deploymentURI);
pw.write(xml);
if (writeToFile) {
Object[] objs = { metadata };
getOutputWriter().printlnMessage(MessageFormat.format(getResourceString("create-meta-template-created-descriptor-template"), objs));
}
} catch (IOException e) {
Object[] objs = { metadata };
throw new CLIException(MessageFormat.format(getResourceString("cannot-write-to-file"), objs), ExitCodes.REQUEST_CANNOT_BE_PROCESSED);
} catch (JAXBException e) {
throw new CLIException(e.getMessage(), ExitCodes.REQUEST_CANNOT_BE_PROCESSED);
} catch (CertificateEncodingException e) {
throw new CLIException(e.getMessage(), ExitCodes.REQUEST_CANNOT_BE_PROCESSED);
} finally {
if ((pw != null) && (pw instanceof PrintWriter)) {
((PrintWriter) pw).close();
} else {
this.getOutputWriter().printlnMessage(((StringWriter) pw).toString());
}
}
}
Aggregations