use of java.security.SignatureException in project android_frameworks_base by AOSPA.
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.SignatureException in project GNS by MobilityFirst.
the class GNSClientCommandsExample 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 that connects to a default reconfigurator as
* specified in gigapaxos properties file. */
client = new GNSClientCommands();
System.out.println("[Client connected to GNS]\n");
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 and is needed mainly if the keypair is
* generated on the server in order to retrieve the private key.
* 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.SignatureException 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.SignatureException 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.SignatureException in project GNS by MobilityFirst.
the class ClientAsynchExample 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
GNSClientCommands client = new GNSClientCommands(null);
GuidEntry accountGuidEntry = null;
try {
// Create a guid (which is also an account guid)
accountGuidEntry = GuidUtils.lookupOrCreateAccountGuid(client, ACCOUNT_ALIAS, "password", true);
} catch (Exception e) {
System.out.println("Exception during accountGuid creation: " + e);
e.printStackTrace();
System.exit(1);
}
System.out.println("Client connected to GNS");
JSONObject command;
if (args.length > 0 && args[0].equals("-write")) {
JSONObject json = new JSONObject("{\"occupation\":\"busboy\"," + "\"friends\":[\"Joe\",\"Sam\",\"Billy\"]," + "\"gibberish\":{\"meiny\":\"bloop\",\"einy\":\"floop\"}," + "\"location\":\"work\",\"name\":\"frank\"}");
command = createAndSignCommand(CommandType.ReplaceUserJSON, accountGuidEntry, GNSProtocol.GUID.toString(), accountGuidEntry.getGuid(), GNSProtocol.USER_JSON.toString(), json.toString(), GNSProtocol.WRITER.toString(), accountGuidEntry.getGuid());
} else {
command = createAndSignCommand(CommandType.Read, accountGuidEntry, GNSProtocol.GUID.toString(), accountGuidEntry.getGuid(), GNSProtocol.FIELD.toString(), "occupation", GNSProtocol.READER.toString(), accountGuidEntry.getGuid());
}
// Create the command packet with a bogus id
// arun: can not change request ID
CommandPacket commandPacket = new CommandPacket((long) (Math.random() * Long.MAX_VALUE), command);
// Keep track of what we've sent for the other thread to look at.
Set<Long> pendingIds = Collections.newSetFromMap(new ConcurrentHashMap<Long, Boolean>());
// Create and run another thread to pick up the responses
Runnable companion = new Runnable() {
@Override
public void run() {
lookForResponses(client, pendingIds);
}
};
//Does this on Android as of 9/16:
//ERROR: ClientAsynchExample.java:114: Lambda coming from jar file need their interfaces
//on the classpath to be compiled, unknown interfaces are java.lang.Runnable
// Runnable companion = () -> {
// lookForResponses(client, pendingIds);
// };
new Thread(companion).start();
while (true) {
//long id = client.generateNextRequestID();
// Important to set the new request id each time
//commandPacket.setClientRequestId(id);
// Record what we're sending
pendingIds.add(commandPacket.getRequestID());
// arun: disabled
if (true) {
throw new RuntimeException("disabled");
}
// Actually send out the packet
//client.sendCommandPacketAsynch(commandPacket);
// if you generate them too fast you'll clog things up
ThreadUtils.sleep(100);
}
}
Aggregations