use of java.security.PublicKey in project OpenAM by OpenRock.
the class AuthenticatorOathService method getEncryptionKeyPair.
private KeyPair getEncryptionKeyPair() {
try {
final KeyStore keyStore = new KeyStoreBuilder().withKeyStoreFile(new File(CollectionHelper.getMapAttr(options, OATH_KEYSTORE_FILE))).withPassword(CollectionHelper.getMapAttr(options, OATH_KEYSTORE_PASSWORD)).withKeyStoreType(KeyStoreType.valueOf(CollectionHelper.getMapAttr(options, OATH_KEYSTORE_TYPE))).build();
final Certificate cert = keyStore.getCertificate(CollectionHelper.getMapAttr(options, OATH_KEYSTORE_KEYPAIR_ALIAS));
final PublicKey publicKey = cert.getPublicKey();
final PrivateKey privateKey = (PrivateKey) keyStore.getKey(CollectionHelper.getMapAttr(options, OATH_KEYSTORE_KEYPAIR_ALIAS), CollectionHelper.getMapAttr(options, OATH_KEYSTORE_PRIVATEKEY_PASSWORD).toCharArray());
return new KeyPair(publicKey, privateKey);
} catch (FileNotFoundException e) {
throw new IllegalArgumentException("Invalid keystore location specified", e);
} catch (KeyStoreException | UnrecoverableKeyException | NoSuchAlgorithmException e) {
debug.error("AuthenticatorOathService.getEncryptionKeyPair(): Unable to load encryption key pair", e);
throw new IllegalStateException(e);
}
}
use of java.security.PublicKey in project GNS by MobilityFirst.
the class NSAccessSupport method verifySignatureInternalSecretKey.
private static synchronized boolean verifySignatureInternalSecretKey(byte[] publickeyBytes, String signature, String message) throws InvalidKeyException, SignatureException, UnsupportedEncodingException, InvalidKeySpecException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
PublicKey publicKey = keyFactory.generatePublic(new X509EncodedKeySpec(publickeyBytes));
// FIXME: The reason why we use CHARSET should be more throughly documented here.
byte[] sigBytes = signature.getBytes(GNSProtocol.CHARSET.toString());
byte[] bytes = message.getBytes(GNSProtocol.CHARSET.toString());
// Pull the parts out of the signature
// See CommandUtils.signDigestOfMessage for the other side of this.
ByteBuffer bbuf = ByteBuffer.wrap(sigBytes);
byte[] sign = new byte[bbuf.getShort()];
bbuf.get(sign);
byte[] skCertEncoded = new byte[bbuf.getShort()];
bbuf.get(skCertEncoded);
SecretKey secretKey = SessionKeys.getSecretKeyFromCertificate(skCertEncoded, publicKey);
MessageDigest md = getMessageDigestInstance();
byte[] digest;
synchronized (md) {
digest = md.digest(bytes);
}
Cipher cipher = getCipherInstance();
synchronized (cipher) {
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
return Arrays.equals(sign, cipher.doFinal(digest));
}
}
use of java.security.PublicKey in project GNS by MobilityFirst.
the class NSAccessSupport method verifySignatureInternal.
private static synchronized boolean verifySignatureInternal(byte[] publickeyBytes, String signature, String message) throws InvalidKeyException, SignatureException, UnsupportedEncodingException, InvalidKeySpecException {
if (Config.getGlobalBoolean(GNSC.ENABLE_SECRET_KEY)) {
try {
return verifySignatureInternalSecretKey(publickeyBytes, signature, message);
} catch (Exception e) {
// This provided backward support for clients that don't have ENABLE_SECRET_KEY on by
// falling through to non-secret method.
// At the cost of potentially masking other issues that might cause exceptions
// in the above code.
ClientSupportConfig.getLogger().log(Level.FINE, "Falling through to non-secret key verification: {0}", new Object[] { e });
}
}
// Non-secret method kept for backwards compatbility with older clients.
X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publickeyBytes);
PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);
Signature sigInstance = getSignatureInstance();
synchronized (sigInstance) {
sigInstance.initVerify(publicKey);
// iOS client uses UTF-8 - should switch to ISO-8859-1 to be consistent with
// secret key version
sigInstance.update(message.getBytes("UTF-8"));
// we need to keep this for now.
try {
return sigInstance.verify(DatatypeConverter.parseHexBinary(signature));
// This will get thrown if the signature is not a hex string.
} catch (IllegalArgumentException e) {
return false;
}
//return sigInstance.verify(ByteUtils.hexStringToByteArray(signature));
}
}
use of java.security.PublicKey in project android_frameworks_base by DirtyUnicorns.
the class ApkSignatureSchemeV2Verifier method verifySigner.
private static X509Certificate[] verifySigner(ByteBuffer signerBlock, Map<Integer, byte[]> contentDigests, CertificateFactory certFactory) throws SecurityException, IOException {
ByteBuffer signedData = getLengthPrefixedSlice(signerBlock);
ByteBuffer signatures = getLengthPrefixedSlice(signerBlock);
byte[] publicKeyBytes = readLengthPrefixedByteArray(signerBlock);
int signatureCount = 0;
int bestSigAlgorithm = -1;
byte[] bestSigAlgorithmSignatureBytes = null;
List<Integer> signaturesSigAlgorithms = new ArrayList<>();
while (signatures.hasRemaining()) {
signatureCount++;
try {
ByteBuffer signature = getLengthPrefixedSlice(signatures);
if (signature.remaining() < 8) {
throw new SecurityException("Signature record too short");
}
int sigAlgorithm = signature.getInt();
signaturesSigAlgorithms.add(sigAlgorithm);
if (!isSupportedSignatureAlgorithm(sigAlgorithm)) {
continue;
}
if ((bestSigAlgorithm == -1) || (compareSignatureAlgorithm(sigAlgorithm, bestSigAlgorithm) > 0)) {
bestSigAlgorithm = sigAlgorithm;
bestSigAlgorithmSignatureBytes = readLengthPrefixedByteArray(signature);
}
} catch (IOException | BufferUnderflowException e) {
throw new SecurityException("Failed to parse signature record #" + signatureCount, e);
}
}
if (bestSigAlgorithm == -1) {
if (signatureCount == 0) {
throw new SecurityException("No signatures found");
} else {
throw new SecurityException("No supported signatures found");
}
}
String keyAlgorithm = getSignatureAlgorithmJcaKeyAlgorithm(bestSigAlgorithm);
Pair<String, ? extends AlgorithmParameterSpec> signatureAlgorithmParams = getSignatureAlgorithmJcaSignatureAlgorithm(bestSigAlgorithm);
String jcaSignatureAlgorithm = signatureAlgorithmParams.first;
AlgorithmParameterSpec jcaSignatureAlgorithmParams = signatureAlgorithmParams.second;
boolean sigVerified;
try {
PublicKey publicKey = KeyFactory.getInstance(keyAlgorithm).generatePublic(new X509EncodedKeySpec(publicKeyBytes));
Signature sig = Signature.getInstance(jcaSignatureAlgorithm);
sig.initVerify(publicKey);
if (jcaSignatureAlgorithmParams != null) {
sig.setParameter(jcaSignatureAlgorithmParams);
}
sig.update(signedData);
sigVerified = sig.verify(bestSigAlgorithmSignatureBytes);
} catch (NoSuchAlgorithmException | InvalidKeySpecException | InvalidKeyException | InvalidAlgorithmParameterException | SignatureException e) {
throw new SecurityException("Failed to verify " + jcaSignatureAlgorithm + " signature", e);
}
if (!sigVerified) {
throw new SecurityException(jcaSignatureAlgorithm + " signature did not verify");
}
// Signature over signedData has verified.
byte[] contentDigest = null;
signedData.clear();
ByteBuffer digests = getLengthPrefixedSlice(signedData);
List<Integer> digestsSigAlgorithms = new ArrayList<>();
int digestCount = 0;
while (digests.hasRemaining()) {
digestCount++;
try {
ByteBuffer digest = getLengthPrefixedSlice(digests);
if (digest.remaining() < 8) {
throw new IOException("Record too short");
}
int sigAlgorithm = digest.getInt();
digestsSigAlgorithms.add(sigAlgorithm);
if (sigAlgorithm == bestSigAlgorithm) {
contentDigest = readLengthPrefixedByteArray(digest);
}
} catch (IOException | BufferUnderflowException e) {
throw new IOException("Failed to parse digest record #" + digestCount, e);
}
}
if (!signaturesSigAlgorithms.equals(digestsSigAlgorithms)) {
throw new SecurityException("Signature algorithms don't match between digests and signatures records");
}
int digestAlgorithm = getSignatureAlgorithmContentDigestAlgorithm(bestSigAlgorithm);
byte[] previousSignerDigest = contentDigests.put(digestAlgorithm, contentDigest);
if ((previousSignerDigest != null) && (!MessageDigest.isEqual(previousSignerDigest, contentDigest))) {
throw new SecurityException(getContentDigestAlgorithmJcaDigestAlgorithm(digestAlgorithm) + " contents digest does not match the digest specified by a preceding signer");
}
ByteBuffer certificates = getLengthPrefixedSlice(signedData);
List<X509Certificate> certs = new ArrayList<>();
int certificateCount = 0;
while (certificates.hasRemaining()) {
certificateCount++;
byte[] encodedCert = readLengthPrefixedByteArray(certificates);
X509Certificate certificate;
try {
certificate = (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(encodedCert));
} catch (CertificateException e) {
throw new SecurityException("Failed to decode certificate #" + certificateCount, e);
}
certificate = new VerbatimX509Certificate(certificate, encodedCert);
certs.add(certificate);
}
if (certs.isEmpty()) {
throw new SecurityException("No certificates listed");
}
X509Certificate mainCertificate = certs.get(0);
byte[] certificatePublicKeyBytes = mainCertificate.getPublicKey().getEncoded();
if (!Arrays.equals(publicKeyBytes, certificatePublicKeyBytes)) {
throw new SecurityException("Public key mismatch between certificate and signature record");
}
return certs.toArray(new X509Certificate[certs.size()]);
}
use of java.security.PublicKey in project XobotOS by xamarin.
the class PackageParser method parseVerifier.
private static VerifierInfo parseVerifier(Resources res, XmlPullParser parser, AttributeSet attrs, int flags, String[] outError) throws XmlPullParserException, IOException {
final TypedArray sa = res.obtainAttributes(attrs, com.android.internal.R.styleable.AndroidManifestPackageVerifier);
final String packageName = sa.getNonResourceString(com.android.internal.R.styleable.AndroidManifestPackageVerifier_name);
final String encodedPublicKey = sa.getNonResourceString(com.android.internal.R.styleable.AndroidManifestPackageVerifier_publicKey);
sa.recycle();
if (packageName == null || packageName.length() == 0) {
Slog.i(TAG, "verifier package name was null; skipping");
return null;
} else if (encodedPublicKey == null) {
Slog.i(TAG, "verifier " + packageName + " public key was null; skipping");
}
EncodedKeySpec keySpec;
try {
final byte[] encoded = Base64.decode(encodedPublicKey, Base64.DEFAULT);
keySpec = new X509EncodedKeySpec(encoded);
} catch (IllegalArgumentException e) {
Slog.i(TAG, "Could not parse verifier " + packageName + " public key; invalid Base64");
return null;
}
/* First try the key as an RSA key. */
try {
final KeyFactory keyFactory = KeyFactory.getInstance("RSA");
final PublicKey publicKey = keyFactory.generatePublic(keySpec);
return new VerifierInfo(packageName, publicKey);
} catch (NoSuchAlgorithmException e) {
Log.wtf(TAG, "Could not parse public key because RSA isn't included in build");
return null;
} catch (InvalidKeySpecException e) {
// Not a RSA public key.
}
/* Now try it as a DSA key. */
try {
final KeyFactory keyFactory = KeyFactory.getInstance("DSA");
final PublicKey publicKey = keyFactory.generatePublic(keySpec);
return new VerifierInfo(packageName, publicKey);
} catch (NoSuchAlgorithmException e) {
Log.wtf(TAG, "Could not parse public key because DSA isn't included in build");
return null;
} catch (InvalidKeySpecException e) {
// Not a DSA public key.
}
return null;
}
Aggregations