use of java.security.spec.InvalidKeySpecException 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.spec.InvalidKeySpecException in project android_frameworks_base by AOSPA.
the class AndroidKeyStoreCipherSpiBase method engineWrap.
@Override
protected final byte[] engineWrap(Key key) throws IllegalBlockSizeException, InvalidKeyException {
if (mKey == null) {
throw new IllegalStateException("Not initilized");
}
if (!isEncrypting()) {
throw new IllegalStateException("Cipher must be initialized in Cipher.WRAP_MODE to wrap keys");
}
if (key == null) {
throw new NullPointerException("key == null");
}
byte[] encoded = null;
if (key instanceof SecretKey) {
if ("RAW".equalsIgnoreCase(key.getFormat())) {
encoded = key.getEncoded();
}
if (encoded == null) {
try {
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(key.getAlgorithm());
SecretKeySpec spec = (SecretKeySpec) keyFactory.getKeySpec((SecretKey) key, SecretKeySpec.class);
encoded = spec.getEncoded();
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
throw new InvalidKeyException("Failed to wrap key because it does not export its key material", e);
}
}
} else if (key instanceof PrivateKey) {
if ("PKCS8".equalsIgnoreCase(key.getFormat())) {
encoded = key.getEncoded();
}
if (encoded == null) {
try {
KeyFactory keyFactory = KeyFactory.getInstance(key.getAlgorithm());
PKCS8EncodedKeySpec spec = keyFactory.getKeySpec(key, PKCS8EncodedKeySpec.class);
encoded = spec.getEncoded();
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
throw new InvalidKeyException("Failed to wrap key because it does not export its key material", e);
}
}
} else if (key instanceof PublicKey) {
if ("X.509".equalsIgnoreCase(key.getFormat())) {
encoded = key.getEncoded();
}
if (encoded == null) {
try {
KeyFactory keyFactory = KeyFactory.getInstance(key.getAlgorithm());
X509EncodedKeySpec spec = keyFactory.getKeySpec(key, X509EncodedKeySpec.class);
encoded = spec.getEncoded();
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
throw new InvalidKeyException("Failed to wrap key because it does not export its key material", e);
}
}
} else {
throw new InvalidKeyException("Unsupported key type: " + key.getClass().getName());
}
if (encoded == null) {
throw new InvalidKeyException("Failed to wrap key because it does not export its key material");
}
try {
return engineDoFinal(encoded, 0, encoded.length);
} catch (BadPaddingException e) {
throw (IllegalBlockSizeException) new IllegalBlockSizeException().initCause(e);
}
}
use of java.security.spec.InvalidKeySpecException in project android_frameworks_base by AOSPA.
the class BackupManagerService method buildCharArrayKey.
private SecretKey buildCharArrayKey(String algorithm, char[] pwArray, byte[] salt, int rounds) {
try {
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algorithm);
KeySpec ks = new PBEKeySpec(pwArray, salt, rounds, PBKDF2_KEY_SIZE);
return keyFactory.generateSecret(ks);
} catch (InvalidKeySpecException e) {
Slog.e(TAG, "Invalid key spec for PBKDF2!");
} catch (NoSuchAlgorithmException e) {
Slog.e(TAG, "PBKDF2 unavailable!");
}
return null;
}
use of java.security.spec.InvalidKeySpecException 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.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");
}
Aggregations