use of java.security.spec.InvalidKeySpecException in project GNS by MobilityFirst.
the class HTTPClientExample method main.
/**
* @param args
* @throws IOException
* @throws InvalidKeySpecException
* @throws NoSuchAlgorithmException
* @throws ClientException
* @throws InvalidKeyException
* @throws SignatureException
* @throws Exception
*/
public static void main(String[] args) throws IOException, InvalidKeySpecException, NoSuchAlgorithmException, ClientException, InvalidKeyException, SignatureException, Exception {
// Create the client will connect to GNS HTTP server running locally.
client = new HttpClient("127.0.0.1", 8080);
try {
/**
* Create an account GUID if one doesn't already exists. The true
* flag makes it verbosely print out what it is doing. The password
* is for future use.
* lookupOrCreateAccountGuid "cheats" by bypassing email-based or
* other verification mechanisms using a shared secret between the
* server and the client.
*
*/
System.out.println("// account GUID creation\n" + "GuidUtils.lookupOrCreateAccountGuid(client, ACCOUNT_ALIAS," + " \"password\", true)");
guid = GuidUtils.lookupOrCreateAccountGuid(client, ACCOUNT_ALIAS, "password", true);
} catch (Exception | Error e) {
System.out.println("Exception during accountGuid creation: " + e);
e.printStackTrace();
System.exit(1);
}
// Create a JSON Object to initialize our guid record
JSONObject json = new JSONObject("{\"occupation\":\"busboy\"," + "\"friends\":[\"Joe\",\"Sam\",\"Billy\"]," + "\"gibberish\":{\"meiny\":\"bloop\",\"einy\":\"floop\"}," + "\"location\":\"work\",\"name\":\"frank\"}");
// Write out the JSON Object
client.update(guid, json);
System.out.println("\n// record update\n" + "client.update(GUID, record) // record=" + json);
// and read the entire object back in
JSONObject result = client.read(guid);
System.out.println("client.read(GUID) -> " + result.toString());
// Change a field
client.update(guid, new JSONObject("{\"occupation\":\"rocket scientist\"}"));
System.out.println("\n// field update\n" + "client.update(GUID, fieldKeyValue) // fieldKeyValue={\"occupation\":\"rocket scientist\"}");
// and read the entire object back in
result = client.read(guid);
System.out.println("client.read(GUID) -> " + result.toString());
// Add a field
client.update(guid, new JSONObject("{\"ip address\":\"127.0.0.1\"}"));
System.out.println("\n// field add\n" + "client.update(GUID, fieldKeyValue) // fieldKeyValue= {\"ip address\":\"127.0.0.1\"}");
// and read the entire object back in
result = client.read(guid);
System.out.println("client.read(GUID) -> " + result.toString());
// Remove a field
client.fieldRemove(guid.getGuid(), "gibberish", guid);
System.out.println("\n// field remove\n" + "client.fieldRemove(GUID, \"gibberish\")");
// and read the entire object back in
result = client.read(guid);
System.out.println("client.read(GUID) -> " + result.toString());
// Add some more stuff to read back
JSONObject newJson = new JSONObject();
JSONObject subJson = new JSONObject();
subJson.put("sally", "red");
subJson.put("sammy", "green");
JSONObject subsubJson = new JSONObject();
subsubJson.put("right", "seven");
subsubJson.put("left", "eight");
subJson.put("sally", subsubJson);
newJson.put("flapjack", subJson);
client.update(guid, newJson);
System.out.println("\n// field add with JSON value\n" + "client.update(GUID, fieldKeyValue) // fieldKeyValue=" + newJson);
// Read a single field at the top level
String resultString = client.fieldRead(guid, "flapjack");
System.out.println("client.fieldRead(\"flapjack\") -> " + resultString);
// Read a single field using dot notation
resultString = client.fieldRead(guid, "flapjack.sally.right");
System.out.println("\n// dotted field read\n" + "client.fieldRead(GUID, \"flapjack.sally.right\") -> " + resultString);
// Update a field using dot notation
JSONArray newValue = new JSONArray(Arrays.asList("One", "Ready", "Frap"));
client.fieldUpdate(guid, "flapjack.sammy", newValue);
System.out.println("\n// dotted field update\n" + "client.fieldUpdate(GUID, \"flapjack.sammy\", " + newValue);
// Read the same field using dot notation
resultString = client.fieldRead(guid, "flapjack.sammy");
System.out.println("client.fieldRead(GUID, \"flapjack.sammy\") -> " + resultString);
// Read two fields at a time
resultString = client.fieldRead(guid, new ArrayList<String>(Arrays.asList("name", "occupation")));
System.out.println("\n// multi-field read\n" + "client.fieldRead(GUID, [\"name\",\"occupation\"] -> " + resultString);
// Read the entire object back in
result = client.read(guid);
System.out.println("\nclient.read(GUID) -> " + result.toString());
// Delete created GUID
client.accountGuidRemove(guid);
System.out.println("\n// GUID delete\n" + "client.accountGuidRemove(GUID) // GUID=" + guid);
// Try read the entire record
try {
result = client.read(guid);
} catch (Exception e) {
System.out.println("\n// non-existent GUID error (expected)\n" + "client.read(GUID) // GUID= " + guid + "\n " + e.getMessage());
}
client.close();
System.out.println("\nclient.close() // test successful");
}
use of java.security.spec.InvalidKeySpecException 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.spec.InvalidKeySpecException in project midpoint by Evolveum.
the class ProtectorImpl method compareHashedPbkd.
private boolean compareHashedPbkd(HashedDataType hashedDataType, String algorithmName, char[] clearChars) throws EncryptionException {
DigestMethodType digestMethodType = hashedDataType.getDigestMethod();
byte[] salt = digestMethodType.getSalt();
Integer workFactor = digestMethodType.getWorkFactor();
byte[] digestValue = hashedDataType.getDigestValue();
int keyLen = digestValue.length * 8;
SecretKeyFactory secretKeyFactory;
try {
secretKeyFactory = SecretKeyFactory.getInstance(algorithmName);
} catch (NoSuchAlgorithmException e) {
throw new EncryptionException(e.getMessage(), e);
}
PBEKeySpec keySpec = new PBEKeySpec(clearChars, salt, workFactor, keyLen);
SecretKey key;
try {
key = secretKeyFactory.generateSecret(keySpec);
} catch (InvalidKeySpecException e) {
throw new EncryptionException(e.getMessage(), e);
}
byte[] hashBytes = key.getEncoded();
return Arrays.equals(digestValue, hashBytes);
}
use of java.security.spec.InvalidKeySpecException 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.spec.InvalidKeySpecException 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