use of java.security.cert.CertificateEncodingException in project android_frameworks_base by ResurrectionRemix.
the class SslCertificate method saveState.
/**
* Saves the certificate state to a bundle
* @param certificate The SSL certificate to store
* @return A bundle with the certificate stored in it or null if fails
*/
public static Bundle saveState(SslCertificate certificate) {
if (certificate == null) {
return null;
}
Bundle bundle = new Bundle();
bundle.putString(ISSUED_TO, certificate.getIssuedTo().getDName());
bundle.putString(ISSUED_BY, certificate.getIssuedBy().getDName());
bundle.putString(VALID_NOT_BEFORE, certificate.getValidNotBefore());
bundle.putString(VALID_NOT_AFTER, certificate.getValidNotAfter());
X509Certificate x509Certificate = certificate.mX509Certificate;
if (x509Certificate != null) {
try {
bundle.putByteArray(X509_CERTIFICATE, x509Certificate.getEncoded());
} catch (CertificateEncodingException ignored) {
}
}
return bundle;
}
use of java.security.cert.CertificateEncodingException in project android_frameworks_base by ResurrectionRemix.
the class SslCertificate method getDigest.
/**
* Convenience for UI presentation, not intended as public API.
*/
private static String getDigest(X509Certificate x509Certificate, String algorithm) {
if (x509Certificate == null) {
return "";
}
try {
byte[] bytes = x509Certificate.getEncoded();
MessageDigest md = MessageDigest.getInstance(algorithm);
byte[] digest = md.digest(bytes);
return fingerprint(digest);
} catch (CertificateEncodingException ignored) {
return "";
} catch (NoSuchAlgorithmException ignored) {
return "";
}
}
use of java.security.cert.CertificateEncodingException in project android_frameworks_base by ResurrectionRemix.
the class AndroidKeyStoreSpi method setPrivateKeyEntry.
private void setPrivateKeyEntry(String alias, PrivateKey key, Certificate[] chain, java.security.KeyStore.ProtectionParameter param) throws KeyStoreException {
int flags = 0;
KeyProtection spec;
if (param == null) {
spec = getLegacyKeyProtectionParameter(key);
} else if (param instanceof KeyStoreParameter) {
spec = getLegacyKeyProtectionParameter(key);
KeyStoreParameter legacySpec = (KeyStoreParameter) param;
if (legacySpec.isEncryptionRequired()) {
flags = KeyStore.FLAG_ENCRYPTED;
}
} else if (param instanceof KeyProtection) {
spec = (KeyProtection) param;
} else {
throw new KeyStoreException("Unsupported protection parameter class:" + param.getClass().getName() + ". Supported: " + KeyProtection.class.getName() + ", " + KeyStoreParameter.class.getName());
}
// Make sure the chain exists since this is a PrivateKey
if ((chain == null) || (chain.length == 0)) {
throw new KeyStoreException("Must supply at least one Certificate with PrivateKey");
}
// Do chain type checking.
X509Certificate[] x509chain = new X509Certificate[chain.length];
for (int i = 0; i < chain.length; i++) {
if (!"X.509".equals(chain[i].getType())) {
throw new KeyStoreException("Certificates must be in X.509 format: invalid cert #" + i);
}
if (!(chain[i] instanceof X509Certificate)) {
throw new KeyStoreException("Certificates must be in X.509 format: invalid cert #" + i);
}
x509chain[i] = (X509Certificate) chain[i];
}
final byte[] userCertBytes;
try {
userCertBytes = x509chain[0].getEncoded();
} catch (CertificateEncodingException e) {
throw new KeyStoreException("Failed to encode certificate #0", e);
}
/*
* If we have a chain, store it in the CA certificate slot for this
* alias as concatenated DER-encoded certificates. These can be
* deserialized by {@link CertificateFactory#generateCertificates}.
*/
final byte[] chainBytes;
if (chain.length > 1) {
/*
* The chain is passed in as {user_cert, ca_cert_1, ca_cert_2, ...}
* so we only need the certificates starting at index 1.
*/
final byte[][] certsBytes = new byte[x509chain.length - 1][];
int totalCertLength = 0;
for (int i = 0; i < certsBytes.length; i++) {
try {
certsBytes[i] = x509chain[i + 1].getEncoded();
totalCertLength += certsBytes[i].length;
} catch (CertificateEncodingException e) {
throw new KeyStoreException("Failed to encode certificate #" + i, e);
}
}
/*
* Serialize this into one byte array so we can later call
* CertificateFactory#generateCertificates to recover them.
*/
chainBytes = new byte[totalCertLength];
int outputOffset = 0;
for (int i = 0; i < certsBytes.length; i++) {
final int certLength = certsBytes[i].length;
System.arraycopy(certsBytes[i], 0, chainBytes, outputOffset, certLength);
outputOffset += certLength;
certsBytes[i] = null;
}
} else {
chainBytes = null;
}
final String pkeyAlias;
if (key instanceof AndroidKeyStorePrivateKey) {
pkeyAlias = ((AndroidKeyStoreKey) key).getAlias();
} else {
pkeyAlias = null;
}
byte[] pkcs8EncodedPrivateKeyBytes;
KeymasterArguments importArgs;
final boolean shouldReplacePrivateKey;
if (pkeyAlias != null && pkeyAlias.startsWith(Credentials.USER_PRIVATE_KEY)) {
final String keySubalias = pkeyAlias.substring(Credentials.USER_PRIVATE_KEY.length());
if (!alias.equals(keySubalias)) {
throw new KeyStoreException("Can only replace keys with same alias: " + alias + " != " + keySubalias);
}
shouldReplacePrivateKey = false;
importArgs = null;
pkcs8EncodedPrivateKeyBytes = null;
} else {
shouldReplacePrivateKey = true;
// Make sure the PrivateKey format is the one we support.
final String keyFormat = key.getFormat();
if ((keyFormat == null) || (!"PKCS#8".equals(keyFormat))) {
throw new KeyStoreException("Unsupported private key export format: " + keyFormat + ". Only private keys which export their key material in PKCS#8 format are" + " supported.");
}
// Make sure we can actually encode the key.
pkcs8EncodedPrivateKeyBytes = key.getEncoded();
if (pkcs8EncodedPrivateKeyBytes == null) {
throw new KeyStoreException("Private key did not export any key material");
}
importArgs = new KeymasterArguments();
try {
importArgs.addEnum(KeymasterDefs.KM_TAG_ALGORITHM, KeyProperties.KeyAlgorithm.toKeymasterAsymmetricKeyAlgorithm(key.getAlgorithm()));
@KeyProperties.PurposeEnum int purposes = spec.getPurposes();
importArgs.addEnums(KeymasterDefs.KM_TAG_PURPOSE, KeyProperties.Purpose.allToKeymaster(purposes));
if (spec.isDigestsSpecified()) {
importArgs.addEnums(KeymasterDefs.KM_TAG_DIGEST, KeyProperties.Digest.allToKeymaster(spec.getDigests()));
}
importArgs.addEnums(KeymasterDefs.KM_TAG_BLOCK_MODE, KeyProperties.BlockMode.allToKeymaster(spec.getBlockModes()));
int[] keymasterEncryptionPaddings = KeyProperties.EncryptionPadding.allToKeymaster(spec.getEncryptionPaddings());
if (((purposes & KeyProperties.PURPOSE_ENCRYPT) != 0) && (spec.isRandomizedEncryptionRequired())) {
for (int keymasterPadding : keymasterEncryptionPaddings) {
if (!KeymasterUtils.isKeymasterPaddingSchemeIndCpaCompatibleWithAsymmetricCrypto(keymasterPadding)) {
throw new KeyStoreException("Randomized encryption (IND-CPA) required but is violated by" + " encryption padding mode: " + KeyProperties.EncryptionPadding.fromKeymaster(keymasterPadding) + ". See KeyProtection documentation.");
}
}
}
importArgs.addEnums(KeymasterDefs.KM_TAG_PADDING, keymasterEncryptionPaddings);
importArgs.addEnums(KeymasterDefs.KM_TAG_PADDING, KeyProperties.SignaturePadding.allToKeymaster(spec.getSignaturePaddings()));
KeymasterUtils.addUserAuthArgs(importArgs, spec.isUserAuthenticationRequired(), spec.getUserAuthenticationValidityDurationSeconds(), spec.isUserAuthenticationValidWhileOnBody(), spec.isInvalidatedByBiometricEnrollment());
importArgs.addDateIfNotNull(KeymasterDefs.KM_TAG_ACTIVE_DATETIME, spec.getKeyValidityStart());
importArgs.addDateIfNotNull(KeymasterDefs.KM_TAG_ORIGINATION_EXPIRE_DATETIME, spec.getKeyValidityForOriginationEnd());
importArgs.addDateIfNotNull(KeymasterDefs.KM_TAG_USAGE_EXPIRE_DATETIME, spec.getKeyValidityForConsumptionEnd());
} catch (IllegalArgumentException | IllegalStateException e) {
throw new KeyStoreException(e);
}
}
boolean success = false;
try {
// Store the private key, if necessary
if (shouldReplacePrivateKey) {
// Delete the stored private key and any related entries before importing the
// provided key
Credentials.deleteAllTypesForAlias(mKeyStore, alias, mUid);
KeyCharacteristics resultingKeyCharacteristics = new KeyCharacteristics();
int errorCode = mKeyStore.importKey(Credentials.USER_PRIVATE_KEY + alias, importArgs, KeymasterDefs.KM_KEY_FORMAT_PKCS8, pkcs8EncodedPrivateKeyBytes, mUid, flags, resultingKeyCharacteristics);
if (errorCode != KeyStore.NO_ERROR) {
throw new KeyStoreException("Failed to store private key", KeyStore.getKeyStoreException(errorCode));
}
} else {
// Keep the stored private key around -- delete all other entry types
Credentials.deleteCertificateTypesForAlias(mKeyStore, alias, mUid);
Credentials.deleteSecretKeyTypeForAlias(mKeyStore, alias, mUid);
}
// Store the leaf certificate
int errorCode = mKeyStore.insert(Credentials.USER_CERTIFICATE + alias, userCertBytes, mUid, flags);
if (errorCode != KeyStore.NO_ERROR) {
throw new KeyStoreException("Failed to store certificate #0", KeyStore.getKeyStoreException(errorCode));
}
// Store the certificate chain
errorCode = mKeyStore.insert(Credentials.CA_CERTIFICATE + alias, chainBytes, mUid, flags);
if (errorCode != KeyStore.NO_ERROR) {
throw new KeyStoreException("Failed to store certificate chain", KeyStore.getKeyStoreException(errorCode));
}
success = true;
} finally {
if (!success) {
if (shouldReplacePrivateKey) {
Credentials.deleteAllTypesForAlias(mKeyStore, alias, mUid);
} else {
Credentials.deleteCertificateTypesForAlias(mKeyStore, alias, mUid);
Credentials.deleteSecretKeyTypeForAlias(mKeyStore, alias, mUid);
}
}
}
}
use of java.security.cert.CertificateEncodingException in project OpenAM by OpenRock.
the class AuthXMLUtils method getX509CertificateCallbackXML.
static String getX509CertificateCallbackXML(X509CertificateCallback certCallback) {
StringBuilder xmlString = new StringBuilder();
xmlString.append(AuthXMLTags.CERT_CALLBACK_BEGIN).append(AuthXMLTags.SPACE).append(AuthXMLTags.SIGN_REQUIRED).append(AuthXMLTags.EQUAL).append(AuthXMLTags.QUOTE).append(certCallback.getReqSignature()).append(AuthXMLTags.QUOTE).append(AuthXMLTags.ELEMENT_END);
xmlString.append(AuthXMLTags.PROMPT_BEGIN).append(XMLUtils.escapeSpecialCharacters(certCallback.getPrompt())).append(AuthXMLTags.PROMPT_END);
X509Certificate cert = certCallback.getCertificate();
if (cert != null) {
try {
xmlString.append(AuthXMLTags.X509CERTIFICATE_BEGIN).append(Base64.encode(cert.getEncoded())).append(AuthXMLTags.X509CERTIFICATE_END);
} catch (CertificateEncodingException e) {
debug.error("getX509CertificateCallbackXML : ", e);
}
}
xmlString.append(AuthXMLTags.CERT_CALLBACK_END);
return xmlString.toString();
}
use of java.security.cert.CertificateEncodingException in project XobotOS by xamarin.
the class PackageParser method collectCertificates.
public boolean collectCertificates(Package pkg, int flags) {
pkg.mSignatures = null;
WeakReference<byte[]> readBufferRef;
byte[] readBuffer = null;
synchronized (mSync) {
readBufferRef = mReadBuffer;
if (readBufferRef != null) {
mReadBuffer = null;
readBuffer = readBufferRef.get();
}
if (readBuffer == null) {
readBuffer = new byte[8192];
readBufferRef = new WeakReference<byte[]>(readBuffer);
}
}
try {
JarFile jarFile = new JarFile(mArchiveSourcePath);
Certificate[] certs = null;
if ((flags & PARSE_IS_SYSTEM) != 0) {
// If this package comes from the system image, then we
// can trust it... we'll just use the AndroidManifest.xml
// to retrieve its signatures, not validating all of the
// files.
JarEntry jarEntry = jarFile.getJarEntry(ANDROID_MANIFEST_FILENAME);
certs = loadCertificates(jarFile, jarEntry, readBuffer);
if (certs == null) {
Slog.e(TAG, "Package " + pkg.packageName + " has no certificates at entry " + jarEntry.getName() + "; ignoring!");
jarFile.close();
mParseError = PackageManager.INSTALL_PARSE_FAILED_NO_CERTIFICATES;
return false;
}
if (DEBUG_JAR) {
Slog.i(TAG, "File " + mArchiveSourcePath + ": entry=" + jarEntry + " certs=" + (certs != null ? certs.length : 0));
if (certs != null) {
final int N = certs.length;
for (int i = 0; i < N; i++) {
Slog.i(TAG, " Public key: " + certs[i].getPublicKey().getEncoded() + " " + certs[i].getPublicKey());
}
}
}
} else {
Enumeration<JarEntry> entries = jarFile.entries();
final Manifest manifest = jarFile.getManifest();
while (entries.hasMoreElements()) {
final JarEntry je = entries.nextElement();
if (je.isDirectory())
continue;
final String name = je.getName();
if (name.startsWith("META-INF/"))
continue;
if (ANDROID_MANIFEST_FILENAME.equals(name)) {
final Attributes attributes = manifest.getAttributes(name);
pkg.manifestDigest = ManifestDigest.fromAttributes(attributes);
}
final Certificate[] localCerts = loadCertificates(jarFile, je, readBuffer);
if (DEBUG_JAR) {
Slog.i(TAG, "File " + mArchiveSourcePath + " entry " + je.getName() + ": certs=" + certs + " (" + (certs != null ? certs.length : 0) + ")");
}
if (localCerts == null) {
Slog.e(TAG, "Package " + pkg.packageName + " has no certificates at entry " + je.getName() + "; ignoring!");
jarFile.close();
mParseError = PackageManager.INSTALL_PARSE_FAILED_NO_CERTIFICATES;
return false;
} else if (certs == null) {
certs = localCerts;
} else {
// Ensure all certificates match.
for (int i = 0; i < certs.length; i++) {
boolean found = false;
for (int j = 0; j < localCerts.length; j++) {
if (certs[i] != null && certs[i].equals(localCerts[j])) {
found = true;
break;
}
}
if (!found || certs.length != localCerts.length) {
Slog.e(TAG, "Package " + pkg.packageName + " has mismatched certificates at entry " + je.getName() + "; ignoring!");
jarFile.close();
mParseError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
return false;
}
}
}
}
}
jarFile.close();
synchronized (mSync) {
mReadBuffer = readBufferRef;
}
if (certs != null && certs.length > 0) {
final int N = certs.length;
pkg.mSignatures = new Signature[certs.length];
for (int i = 0; i < N; i++) {
pkg.mSignatures[i] = new Signature(certs[i].getEncoded());
}
} else {
Slog.e(TAG, "Package " + pkg.packageName + " has no certificates; ignoring!");
mParseError = PackageManager.INSTALL_PARSE_FAILED_NO_CERTIFICATES;
return false;
}
} catch (CertificateEncodingException e) {
Slog.w(TAG, "Exception reading " + mArchiveSourcePath, e);
mParseError = PackageManager.INSTALL_PARSE_FAILED_CERTIFICATE_ENCODING;
return false;
} catch (IOException e) {
Slog.w(TAG, "Exception reading " + mArchiveSourcePath, e);
mParseError = PackageManager.INSTALL_PARSE_FAILED_CERTIFICATE_ENCODING;
return false;
} catch (RuntimeException e) {
Slog.w(TAG, "Exception reading " + mArchiveSourcePath, e);
mParseError = PackageManager.INSTALL_PARSE_FAILED_UNEXPECTED_EXCEPTION;
return false;
}
return true;
}
Aggregations