index int64 | repo_id string | file_path string | content string |
|---|---|---|---|
0 | java-sources/al/aldi/sprova4j/0.2.1/al/aldi | java-sources/al/aldi/sprova4j/0.2.1/al/aldi/sprova4j/TestManager.java | package al.aldi.sprova4j;
/**
* Manages the whole lifecycle of the test object.
* @author Aldi Alimuçaj
*/
public class TestManager {
public boolean start(){
return true;
}
public boolean fail(){
return true;
}
public boolean succeed(){
return true;
}
}
|
0 | java-sources/al/aldi/sprova4j/0.2.1/al/aldi/sprova4j | java-sources/al/aldi/sprova4j/0.2.1/al/aldi/sprova4j/exceptions/CycleException.java | package al.aldi.sprova4j.exceptions;
public class CycleException extends Exception {
public CycleException(String s) {
super(s);
}
}
|
0 | java-sources/al/aldi/sprova4j/0.2.1/al/aldi/sprova4j | java-sources/al/aldi/sprova4j/0.2.1/al/aldi/sprova4j/exceptions/ExecutionException.java | package al.aldi.sprova4j.exceptions;
public class ExecutionException extends Exception {
public ExecutionException(String s) {
super(s);
}
}
|
0 | java-sources/al/aldi/sprova4j/0.2.1/al/aldi/sprova4j | java-sources/al/aldi/sprova4j/0.2.1/al/aldi/sprova4j/exceptions/SprovaClientException.java | package al.aldi.sprova4j.exceptions;
public class SprovaClientException extends Exception {
public SprovaClientException(String s) {
super(s);
}
}
|
0 | java-sources/al/aldi/sprova4j/0.2.1/al/aldi/sprova4j | java-sources/al/aldi/sprova4j/0.2.1/al/aldi/sprova4j/exceptions/TestCaseException.java | package al.aldi.sprova4j.exceptions;
public class TestCaseException extends Exception {
public TestCaseException(String s) {
super(s);
}
}
|
0 | java-sources/al/aldi/sprova4j/0.2.1/al/aldi/sprova4j | java-sources/al/aldi/sprova4j/0.2.1/al/aldi/sprova4j/exceptions/TestSetException.java | package al.aldi.sprova4j.exceptions;
public class TestSetException extends Exception {
public TestSetException(String s) {
super(s);
}
}
|
0 | java-sources/al/aldi/sprova4j/0.2.1/al/aldi/sprova4j | java-sources/al/aldi/sprova4j/0.2.1/al/aldi/sprova4j/models/Artifact.java | package al.aldi.sprova4j.models;
public class Artifact {
String _id;
String title;
String description;
String fileName;
String artifactType;
String executionId;
String cycleId;
}
|
0 | java-sources/al/aldi/sprova4j/0.2.1/al/aldi/sprova4j | java-sources/al/aldi/sprova4j/0.2.1/al/aldi/sprova4j/models/Cycle.java | package al.aldi.sprova4j.models;
import al.aldi.sprova4j.exceptions.CycleException;
import al.aldi.sprova4j.exceptions.TestCaseException;
import al.aldi.sprova4j.utils.SprovaObjectFilter;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
public class Cycle extends SprovaObject {
public String _id;
public String title;
public String description;
public String projectId;
public String status;
public List<String> testCaseIDs;
/**
* Find one test case by applying a filter. If there are more then
* one match then the first one is returned.
*
* @param filter
* @return
* @throws TestCaseException
*/
public TestCase findTestCase(SprovaObjectFilter filter) throws TestCaseException {
TestCase result = client.filterCycleTestCase(_id, filter);
result.cycleId = _id;
return result;
}
/**
* Find one test set by applying a filter. If there are more then
* one match then the first one is returned.
*
* @param filter
* @return
* @throws TestCaseException
*/
public TestSet findOneTestSet(final SprovaObjectFilter filter) throws TestCaseException {
TestSet result = null;
filter.add("cycleId", _id);
List<TestSet> testSets = client.filterTestSets(filter);
if (testSets != null && testSets.size() > 0) {
result = testSets.get(0);
}
return result;
}
/**
* Get all test cases;
*
* @return
*/
public List<TestCase> getTestCases() throws TestCaseException {
return client.getCycleTestCases(_id);
}
public List<TestCase> getTestCases(SprovaObjectFilter filter) {
List<TestCase> result = null;
filter.add("cycleId", _id);
try {
result = client.filterTestCases(filter);
if (result != null && result.size() > 0) {
for (TestCase testCase : result) {
testCase.cycleId = _id;
}
}
} catch (TestCaseException e) {
e.printStackTrace();
}
return result;
}
public List<TestSet> getTestSets() {
return this.getTestSets(SprovaObjectFilter.empty());
}
public List<TestSet> getTestSets(SprovaObjectFilter filter) {
List<TestSet> result = null;
filter.add("cycleId", _id);
try {
result = client.filterTestSets(filter);
if (result != null && result.size() > 0) {
for (TestSet testCase : result) {
testCase.cycleId = _id;
}
}
} catch (TestCaseException e) {
e.printStackTrace();
}
return result;
}
public static Cycle toObject(String json) {
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
return gson.fromJson(json, Cycle.class);
}
public static List<Cycle> toObjects(String json) {
Type listType = new TypeToken<ArrayList<Cycle>>() {
}.getType();
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
return gson.fromJson(json, listType);
}
}
|
0 | java-sources/al/aldi/sprova4j/0.2.1/al/aldi/sprova4j | java-sources/al/aldi/sprova4j/0.2.1/al/aldi/sprova4j/models/Execution.java | package al.aldi.sprova4j.models;
import al.aldi.sprova4j.SprovaApiClient;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
public class Execution extends SprovaObject {
public static final String TYPE_MANUAL = "MANUAL";
public static final String TYPE_AUTOMATED = "AUTOMATED";
public static final String TYPE_SEMI_AUTOMATED = "SEMI_AUTOMATED";
public String _id;
public String title;
public String description;
public String testCaseId;
public String testVersion;
public String cycleId;
public String parentId;
public String status;
public String executionType;
public List<TestStep> testSteps;
public Date createdAt;
public Date updatedAt;
public void passTest() {
client.passExecution(this);
}
public void failTest() {
client.failExecution(this);
}
public boolean passStep(int stepIndex) {
return client.passStep(this, stepIndex);
}
public boolean failStep(int stepIndex) {
return client.failStep(this, stepIndex);
}
public static Execution toObject(String json) {
Execution result = null;
if (json != null && !json.isEmpty() && !json.trim().equals("{}")) {
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
result = gson.fromJson(json, Execution.class);
}
return result;
}
public static List<Execution> toObjects(String json) {
Type listType = new TypeToken<ArrayList<Execution>>() {
}.getType();
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
return gson.fromJson(json, listType);
}
}
|
0 | java-sources/al/aldi/sprova4j/0.2.1/al/aldi/sprova4j | java-sources/al/aldi/sprova4j/0.2.1/al/aldi/sprova4j/models/Project.java | package al.aldi.sprova4j.models;
import al.aldi.sprova4j.exceptions.CycleException;
import al.aldi.sprova4j.exceptions.TestCaseException;
import al.aldi.sprova4j.utils.SprovaObjectFilter;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
public class Project extends SprovaObject {
public String _id;
public String title;
public String description;
/**
* Makes API call to filter for cycles with parameter filters in addition
* to the own projectId filter.
*
* @param filter
* @return Cycle if found, null otherwise
* @throws CycleException
*/
public Cycle getCycle(SprovaObjectFilter filter) throws CycleException {
Cycle result = null;
List<Cycle> cycles = this.getCycles(filter);
if (cycles != null && cycles.size() > 0) {
result = cycles.get(0);
}
return result;
}
/**
* Return all cycles for this project
*
* @return
*/
public List<Cycle> getCycles() {
return this.getCycles(SprovaObjectFilter.empty());
}
/**
* Filter cycles for this project
*
* @param filter
* @return
*/
public List<Cycle> getCycles(SprovaObjectFilter filter) {
List<Cycle> result = null;
filter.add("projectId", _id);
try {
result = client.filterCycles(filter);
} catch (CycleException e) {
e.printStackTrace();
}
return result;
}
public List<TestCase> getTestCases() {
return this.getTestCases(SprovaObjectFilter.empty());
}
public List<TestCase> getTestCases(SprovaObjectFilter filter) {
List<TestCase> result = null;
filter.add("projectId", _id);
try {
result = client.filterTestCases(filter);
} catch (TestCaseException e) {
e.printStackTrace();
}
return result;
}
public static Project toObject(String json) {
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
return gson.fromJson(json, Project.class);
}
public static List<Project> toObjects(String json) {
Type listType = new TypeToken<ArrayList<Project>>() {
}.getType();
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
return gson.fromJson(json, listType);
}
@Override
public String toString() {
return "Project{" +
"_id='" + _id + '\'' +
", title='" + title + '\'' +
", description='" + description + '\'' +
'}';
}
}
|
0 | java-sources/al/aldi/sprova4j/0.2.1/al/aldi/sprova4j | java-sources/al/aldi/sprova4j/0.2.1/al/aldi/sprova4j/models/SprovaObject.java | package al.aldi.sprova4j.models;
import al.aldi.sprova4j.SprovaApiClient;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public abstract class SprovaObject {
public static GsonBuilder builder = new GsonBuilder();
public static Gson gson = builder.create();
protected transient SprovaApiClient client;
protected transient String jsonString;
private transient Map<String, String> stringMap = new HashMap<>();
/**
* Return custom field value. These values are not part of the standard object model
* and thus cannot be parsed into the object when mapping it.
*
* @param key
* @return custom field string value
*/
public String getCustomField(final String key) {
if (stringMap == null || stringMap.size() == 0) {
createJsonMap();
}
return stringMap != null? stringMap.get(key): null;
}
private void createJsonMap() {
ObjectMapper objectMapper = new ObjectMapper();
try {
stringMap = objectMapper.readValue(jsonString, HashMap.class);
} catch (IOException e) {
e.printStackTrace();
}
}
public void setClient(SprovaApiClient client) {
this.client = client;
}
public String toJson() {
return gson.toJson(this);
}
public void setJsonString(String jsonString) {
this.jsonString = jsonString;
}
}
|
0 | java-sources/al/aldi/sprova4j/0.2.1/al/aldi/sprova4j | java-sources/al/aldi/sprova4j/0.2.1/al/aldi/sprova4j/models/TestCase.java | package al.aldi.sprova4j.models;
import al.aldi.sprova4j.SprovaApiClient;
import al.aldi.sprova4j.exceptions.TestCaseException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import static al.aldi.sprova4j.models.Execution.TYPE_AUTOMATED;
import static al.aldi.sprova4j.models.TestStep.STATUS_PENDING;
public class TestCase extends SprovaObject {
public String _id;
public String title;
public String description;
public String version;
public String projectId;
public String cycleId;
public String testSetExecutionId;
public String parentId;
public String status;
public List<TestStep> testSteps;
public Execution startExecution(Cycle cycle) throws TestCaseException {
if (cycle == null || cycle._id == null) throw new TestCaseException("Cycle ID cannot be null");
Execution execution = getExecution(cycle._id);
client.startExecution(execution);
return execution;
}
public Execution startExecution() throws TestCaseException {
if (cycleId == null) throw new TestCaseException("Cycle ID cannot be null");
Execution execution = getExecution(cycleId);
client.startExecution(execution);
return execution;
}
private Execution getExecution(String cycleId) {
Execution result = new Execution();
result.setClient(client);
result.testCaseId = _id;
result.cycleId = cycleId;
result.title = title;
result.description = description;
result.testSteps = testSteps;
result.status = STATUS_PENDING;
result.executionType = TYPE_AUTOMATED;
for (int i = 0; i < result.testSteps.size(); i++) {
result.testSteps.get(i).execution = result;
result.testSteps.get(i).index = i;
}
return result;
}
public void setClient(SprovaApiClient client) {
this.client = client;
}
public static TestCase toObject(String json) {
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
TestCase testCase = gson.fromJson(json, TestCase.class);
testCase.setJsonString(json);
return testCase;
}
public static List<TestCase> toObjects(String json) {
Type listType = new TypeToken<ArrayList<TestCase>>() {
}.getType();
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
return gson.fromJson(json, listType);
}
}
|
0 | java-sources/al/aldi/sprova4j/0.2.1/al/aldi/sprova4j | java-sources/al/aldi/sprova4j/0.2.1/al/aldi/sprova4j/models/TestSet.java | package al.aldi.sprova4j.models;
import al.aldi.sprova4j.exceptions.TestCaseException;
import al.aldi.sprova4j.exceptions.TestSetException;
import al.aldi.sprova4j.models.aux.TestSetExecutionResponse;
import al.aldi.sprova4j.utils.SprovaObjectFilter;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
public class TestSet extends SprovaObject {
public String _id;
public String title;
public String description;
public String projectId;
public String cycleId;
public String status;
public TestSet findOneTest(SprovaObjectFilter filter) throws TestCaseException {
TestSet result = client.filterTestSets(filter).get(0);
return result;
}
public List<TestSetExecution> getTestSetExecutions() {
List<TestSetExecution> result = client.getTestSetExecutionsByTestSetId(this._id);
for(TestSetExecution execution: result) {
execution.cycleId = cycleId;
}
return result;
}
public TestSetExecution createExecution() throws TestSetException {
TestSetExecution result = null;
TestSetExecutionResponse response = client.createTestSetExecution(TestSetExecution.fromTestSet(this));
if (response.isSuccessful()) {
result = client.getTestSetExecution(response._id);
} else {
throw new TestSetException("Could not create execution");
}
return result;
}
public static TestSet toObject(String json) {
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
return gson.fromJson(json, TestSet.class);
}
public static List<TestSet> toObjects(String json) {
Type listType = new TypeToken<ArrayList<TestSet>>() {
}.getType();
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
return gson.fromJson(json, listType);
}
}
|
0 | java-sources/al/aldi/sprova4j/0.2.1/al/aldi/sprova4j | java-sources/al/aldi/sprova4j/0.2.1/al/aldi/sprova4j/models/TestSetExecution.java | package al.aldi.sprova4j.models;
import al.aldi.sprova4j.exceptions.TestCaseException;
import al.aldi.sprova4j.models.enums.TestSetExecutionStatus;
import al.aldi.sprova4j.utils.SprovaObjectFilter;
import com.google.gson.*;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
public class TestSetExecution extends SprovaObject {
public String _id;
public String title;
public String description;
public String status;
public String projectId;
public String cycleId;
public String testSetId;
public Instant createdAt;
public Instant updatedAt;
public Instant startedAt;
public Instant finishedAt;
private static GsonBuilder builder = new GsonBuilder();
private static Gson gson = builder.registerTypeAdapter(Instant.class, (JsonDeserializer<Instant>) (json1, type, jsonDeserializationContext) -> {
Instant instant = Instant.parse(json1.getAsString());
return instant;
}).create();
public TestSetExecution() {
}
public TestSetExecution(String title, String description, String testSetId, String cycleId) {
this.title = title;
this.description = description;
this.testSetId = testSetId;
this.cycleId = cycleId;
this.status = TestSetExecutionStatus.PLANNED;
}
public Execution getNextPending() {
return client.getNextPendingExecution(this);
}
public static TestSetExecution fromTestSet(TestSet testSet) {
return new TestSetExecution(testSet.title, testSet.description, testSet._id, testSet.cycleId);
}
public static TestSetExecution toObject(String json) {
return gson.fromJson(json, TestSetExecution.class);
}
public static List<TestSetExecution> toObjects(String json) {
Type listType = new TypeToken<ArrayList<TestSetExecution>>() {
}.getType();
return gson.fromJson(json, listType);
}
}
|
0 | java-sources/al/aldi/sprova4j/0.2.1/al/aldi/sprova4j | java-sources/al/aldi/sprova4j/0.2.1/al/aldi/sprova4j/models/TestStep.java | package al.aldi.sprova4j.models;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
public class TestStep extends SprovaObject {
public String _id;
public String action;
public String payload;
public String expected;
public String comment;
public String updatedAt;
public String status;
public List<Artifact> artifacts;
public transient Execution execution;
public transient int index;
public static final String STATUS_PENDING = "PENDING";
public static final String STATUS_WORKING = "WORKING";
public static final String STATUS_SUCCESSFUL = "SUCCESSFUL";
public static final String STATUS_FAILED = "FAILED";
public TestStep() {
this.status = STATUS_PENDING;
}
public boolean pass(){
return execution.passStep(index);
}
public static TestStep toObject(String json) {
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
return gson.fromJson(json, TestStep.class);
}
public static List<TestStep> toObjects(String json) {
Type listType = new TypeToken<ArrayList<TestStep>>(){}.getType();
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
return gson.fromJson(json, listType);
}
}
|
0 | java-sources/al/aldi/sprova4j/0.2.1/al/aldi/sprova4j | java-sources/al/aldi/sprova4j/0.2.1/al/aldi/sprova4j/models/User.java | package al.aldi.sprova4j.models;
public class User extends SprovaObject {
public String username;
public String password;
public String firstname;
public String lastname;
public String email;
public boolean admin;
User toObject(String json) {
return gson.fromJson(json, User.class);
}
}
|
0 | java-sources/al/aldi/sprova4j/0.2.1/al/aldi/sprova4j/models | java-sources/al/aldi/sprova4j/0.2.1/al/aldi/sprova4j/models/aux/AuthenticationRequest.java | package al.aldi.sprova4j.models.aux;
import al.aldi.sprova4j.models.SprovaObject;
public class AuthenticationRequest extends SprovaObject {
public String username;
public String password;
public AuthenticationRequest() {
}
public AuthenticationRequest(String username, String password) {
this.username = username;
this.password = password;
}
}
|
0 | java-sources/al/aldi/sprova4j/0.2.1/al/aldi/sprova4j/models | java-sources/al/aldi/sprova4j/0.2.1/al/aldi/sprova4j/models/aux/AuthenticationResponse.java | package al.aldi.sprova4j.models.aux;
import al.aldi.sprova4j.models.SprovaObject;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class AuthenticationResponse extends SprovaObject {
public String message;
public String token;
public static AuthenticationResponse toObject(String json) {
return gson.fromJson(json, AuthenticationResponse.class);
}
}
|
0 | java-sources/al/aldi/sprova4j/0.2.1/al/aldi/sprova4j/models | java-sources/al/aldi/sprova4j/0.2.1/al/aldi/sprova4j/models/aux/MongoDbInsertManyResponse.java | package al.aldi.sprova4j.models.aux;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.util.HashMap;
public class MongoDbInsertManyResponse {
public int insertedCount;
public Nok result;
public HashMap<Integer, String> insertedIds;
public static MongoDbInsertManyResponse toObject(String json) {
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
return gson.fromJson(json, MongoDbInsertManyResponse.class);
}
static class Nok {
public int n;
public int ok;
}
}
|
0 | java-sources/al/aldi/sprova4j/0.2.1/al/aldi/sprova4j/models | java-sources/al/aldi/sprova4j/0.2.1/al/aldi/sprova4j/models/aux/MongoDbInsertResponse.java | package al.aldi.sprova4j.models.aux;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class MongoDbInsertResponse {
public int n;
public int ok;
public String _id;
public boolean isSuccessful() {
return n == 1 && ok == 1 && _id != null && !_id.isEmpty();
}
public static MongoDbInsertResponse toObject(String json) {
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
return gson.fromJson(json, MongoDbInsertResponse.class);
}
}
|
0 | java-sources/al/aldi/sprova4j/0.2.1/al/aldi/sprova4j/models | java-sources/al/aldi/sprova4j/0.2.1/al/aldi/sprova4j/models/aux/StatusResponse.java | package al.aldi.sprova4j.models.aux;
import al.aldi.sprova4j.models.SprovaObject;
public class StatusResponse extends SprovaObject {
public Boolean success;
public String name;
public String version;
public String serverTime;
public static StatusResponse toObject(String json) {
return gson.fromJson(json, StatusResponse.class);
}
}
|
0 | java-sources/al/aldi/sprova4j/0.2.1/al/aldi/sprova4j/models | java-sources/al/aldi/sprova4j/0.2.1/al/aldi/sprova4j/models/aux/TestSetExecutionResponse.java | package al.aldi.sprova4j.models.aux;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class TestSetExecutionResponse extends MongoDbInsertResponse {
public MongoDbInsertManyResponse executions;
public static TestSetExecutionResponse toObject(String json) {
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
return gson.fromJson(json, TestSetExecutionResponse.class);
}
}
|
0 | java-sources/al/aldi/sprova4j/0.2.1/al/aldi/sprova4j/models | java-sources/al/aldi/sprova4j/0.2.1/al/aldi/sprova4j/models/enums/ExecutionStatus.java | package al.aldi.sprova4j.models.enums;
public enum ExecutionStatus {
SUCCESSFUL("SUCCESSFUL"),
FAILED("FAILED"),
WARNING("WARNING"),
PENDING("PENDING"),
WORKING("WORKING");
private final String text;
ExecutionStatus(String value) {
this.text = value;
}
@Override
public String toString() {
return text;
}
public String toJsonObjectString() {
return String.format("{\"status\":\"%s\"}", this.text);
}
}
|
0 | java-sources/al/aldi/sprova4j/0.2.1/al/aldi/sprova4j/models | java-sources/al/aldi/sprova4j/0.2.1/al/aldi/sprova4j/models/enums/ExecutionStepStatus.java | package al.aldi.sprova4j.models.enums;
public enum ExecutionStepStatus {
SUCCESSFUL("SUCCESSFUL"),
FAILED("FAILED");
private final String text;
ExecutionStepStatus(String value) {
this.text = value;
}
@Override
public String toString() {
return text;
}
public String toJsonObjectString() {
return String.format("{\"status\":\"%s\"}", this.text);
}
}
|
0 | java-sources/al/aldi/sprova4j/0.2.1/al/aldi/sprova4j/models | java-sources/al/aldi/sprova4j/0.2.1/al/aldi/sprova4j/models/enums/TestSetExecutionStatus.java | package al.aldi.sprova4j.models.enums;
public class TestSetExecutionStatus {
public final static String RUNNING = "Running";
public final static String ABANDONED = "Abandoned";
public final static String FINISHED = "Finished";
public final static String PLANNED = "Planned";
}
|
0 | java-sources/al/aldi/sprova4j/0.2.1/al/aldi/sprova4j | java-sources/al/aldi/sprova4j/0.2.1/al/aldi/sprova4j/utils/ApiUtils.java | package al.aldi.sprova4j.utils;
import okhttp3.*;
import java.io.IOException;
import static al.aldi.sprova4j.SprovaApiClient.JSON;
public class ApiUtils {
public static final String API = "/api";
public static final String AUTHENTICATE = "/authenticate";
public static final String STATUS = "/status";
public static final String PROJECTS = "projects";
public static final String CYCLES = "cycles";
public static final String TESTSETS = "testsets";
public static final String TESTCASES = "testcases";
public static final String TESTSET_EXECUTIONS = "testset-executions";
public static final String EXECUTIONS = "executions";
public static final String STEPS = "steps";
public static final String FIND = "find";
public static final String FIND_ONE = "findOne";
public static final String NEXT_PENDING = "next-pending";
public static final String API_PROJECTS = API + "/" + PROJECTS;
public static final String API_CYCLES = API + "/" + CYCLES;
public static final String API_TESTSETS = API + "/" + TESTSETS;
public static final String API_TESTCASES = API + "/" + TESTCASES;
public static final String API_EXECUTIONS = API + "/" + EXECUTIONS;
public static final String API_TESTSET_EXECUTIONS = API + "/" + TESTSET_EXECUTIONS;
public static final String API_SEARCH = API + "/search";
private final static Request.Builder builder = new Request.Builder();
private final static OkHttpClient client = new OkHttpClient();
/**
* Generic post request
* @param url
* @param json
* @return
* @throws IOException
*/
public static Response POST(final String url, String json) throws IOException {
RequestBody body = RequestBody.create(JSON, json);
Request request = builder.url(url).post(body).build();
return client.newCall(request).execute();
}
/**
* Generic get request
* @param url
* @return
* @throws IOException
*/
public static Response GET(final String url) throws IOException {
Request request = builder.url(url).get().build();
return client.newCall(request).execute();
}
/**
* Generic put request
* @param url
* @param json
* @return
* @throws IOException
*/
public Response PUT(final String url, String json) throws IOException {
RequestBody body = RequestBody.create(JSON, json);
Request request = builder.url(url).put(body).build();
return client.newCall(request).execute();
}
/**
* Generic delete request
* @param url
* @return
* @throws IOException
*/
public static Response DEL(final String url) throws IOException {
Request request = builder.url(url).delete().build();
return client.newCall(request).execute();
}
/**
* Sanitize url in order for it to be used in API calls
*
* @param url
* @return
* @throws Exception
*/
public static String sanitizeUrl(final String url) throws Exception {
String result = url;
if (url.endsWith("/")) {
result = result.substring(0, result.length() - 1);
}
if (!url.startsWith("http://") && !url.startsWith("https://")) {
throw new Exception("Url is missing protocol. HTTPS is suggested.");
}
return result;
}
}
|
0 | java-sources/al/aldi/sprova4j/0.2.1/al/aldi/sprova4j | java-sources/al/aldi/sprova4j/0.2.1/al/aldi/sprova4j/utils/AuthorizationInterceptor.java | package al.aldi.sprova4j.utils;
import javax.validation.constraints.NotNull;;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
public class AuthorizationInterceptor implements Interceptor {
private static final Logger logger = LoggerFactory.getLogger(AuthorizationInterceptor.class);
private final String jwtToken;
private final String bearer;
public AuthorizationInterceptor(@NotNull final String jwtToken) {
this.jwtToken = jwtToken;
this.bearer = "Bearer " + jwtToken;
}
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
request = request.newBuilder().addHeader("Authorization", bearer).build();
Response response = chain.proceed(request);
return response;
}
} |
0 | java-sources/al/aldi/sprova4j/0.2.1/al/aldi/sprova4j | java-sources/al/aldi/sprova4j/0.2.1/al/aldi/sprova4j/utils/LoggingInterceptor.java | package al.aldi.sprova4j.utils;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okio.Buffer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
public class LoggingInterceptor implements Interceptor {
private static final Logger logger = LoggerFactory.getLogger(LoggingInterceptor.class);
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request request = chain.request();
String body = null;
// not all requests have body.
try {
final Request copy = request.newBuilder().build();
final Buffer buffer = new Buffer();
copy.body().writeTo(buffer);
body = buffer.readUtf8();
} catch (final Exception e) {
body = "{}";
}
long t1 = System.nanoTime();
logger.debug(String.format("REQ [%s] %s on %n%s %s", request.method(), request.url(), request.headers(), body));
Response response = chain.proceed(request);
long t2 = System.nanoTime();
logger.debug(String.format("RES %s in %.1fms%n%s", response.request().url(), (t2 - t1) / 1e6d, response.headers()));
return response;
}
} |
0 | java-sources/al/aldi/sprova4j/0.2.1/al/aldi/sprova4j | java-sources/al/aldi/sprova4j/0.2.1/al/aldi/sprova4j/utils/SprovaObjectFilter.java | package al.aldi.sprova4j.utils;
import al.aldi.sprova4j.models.SprovaObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import javax.json.Json;
import javax.json.JsonBuilderFactory;
import javax.json.JsonObjectBuilder;
import javax.json.JsonWriter;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
public class SprovaObjectFilter {
private ObjectMapper mapper;
private ObjectNode rootNode;
private ObjectNode filterNode;
public SprovaObjectFilter() {
mapper = new ObjectMapper();
rootNode = mapper.createObjectNode();
filterNode = mapper.createObjectNode();
rootNode.set("query", filterNode);
}
public SprovaObjectFilter add(String key, String value) {
filterNode.put(key, value);
return this;
}
public SprovaObjectFilter add(String key, boolean value) {
filterNode.put(key, value);
return this;
}
public SprovaObjectFilter add(String key, int value) {
filterNode.put(key, value);
return this;
}
public SprovaObjectFilter add(String key, double value) {
filterNode.put(key, value);
return this;
}
public String getString(String key) {
return filterNode.get(key).asText();
}
public boolean getBoolean(String key) {
return filterNode.get(key).asBoolean();
}
public int getInt(String key) {
return filterNode.get(key).asInt();
}
public double getDouble(String key) {
return filterNode.get(key).asDouble();
}
public String toJson() {
String result = null;
try {
result = mapper.writeValueAsString(rootNode);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return result;
}
public static SprovaObjectFilter empty() {
return new SprovaObjectFilter();
}
}
|
0 | java-sources/al/aldi/sprova4j/0.2.1/al/aldi/sprova4j | java-sources/al/aldi/sprova4j/0.2.1/al/aldi/sprova4j/utils/Utils.java | package al.aldi.sprova4j.utils;
public class Utils {
}
|
0 | java-sources/al/bluecryst/bluecrystal/2.3.4/bluecrystal/bcdeps | java-sources/al/bluecryst/bluecrystal/2.3.4/bluecrystal/bcdeps/helper/DerEncoder.java | /*
Blue Crystal: Document Digital Signature Tool
Copyright (C) 2007-2015 Sergio Leal
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package bluecrystal.bcdeps.helper;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.cert.CRLException;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateParsingException;
import java.security.cert.X509Certificate;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.bouncycastle.asn1.ASN1Encodable;
import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.ASN1Encoding;
import org.bouncycastle.asn1.ASN1Enumerated;
import org.bouncycastle.asn1.ASN1GeneralizedTime;
import org.bouncycastle.asn1.ASN1InputStream;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.ASN1OctetString;
import org.bouncycastle.asn1.ASN1OutputStream;
import org.bouncycastle.asn1.ASN1Primitive;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.ASN1Set;
import org.bouncycastle.asn1.ASN1UTCTime;
import org.bouncycastle.asn1.DERBitString;
import org.bouncycastle.asn1.DERIA5String;
import org.bouncycastle.asn1.DERInteger;
import org.bouncycastle.asn1.DERNull;
import org.bouncycastle.asn1.DERObjectIdentifier;
import org.bouncycastle.asn1.DEROctetString;
import org.bouncycastle.asn1.DERPrintableString;
import org.bouncycastle.asn1.DERSequence;
import org.bouncycastle.asn1.DERSet;
import org.bouncycastle.asn1.DERTaggedObject;
import org.bouncycastle.asn1.DERUTCTime;
import org.bouncycastle.asn1.DERUTF8String;
import org.bouncycastle.asn1.DLSequence;
import org.bouncycastle.asn1.cms.Attribute;
import org.bouncycastle.asn1.ocsp.OCSPObjectIdentifiers;
import org.bouncycastle.asn1.x509.AccessDescription;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.asn1.x509.AuthorityInformationAccess;
import org.bouncycastle.asn1.x509.CRLDistPoint;
import org.bouncycastle.asn1.x509.DigestInfo;
import org.bouncycastle.asn1.x509.DistributionPoint;
import org.bouncycastle.asn1.x509.DistributionPointName;
import org.bouncycastle.asn1.x509.Extension;
import org.bouncycastle.asn1.x509.Extensions;
import org.bouncycastle.asn1.x509.GeneralName;
import org.bouncycastle.asn1.x509.GeneralNames;
import org.bouncycastle.asn1.x509.X509Extensions;
import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.cert.ocsp.CertificateID;
import org.bouncycastle.cert.ocsp.OCSPException;
import org.bouncycastle.cert.ocsp.OCSPReq;
import org.bouncycastle.cert.ocsp.OCSPReqBuilder;
import org.bouncycastle.operator.DigestCalculatorProvider;
import org.bouncycastle.operator.OperatorCreationException;
import org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder;
import org.bouncycastle.util.encoders.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import bluecrystal.domain.AppSignedInfoEx;
import bluecrystal.domain.CertConstants;
import bluecrystal.domain.SignCompare;
import bluecrystal.domain.SignCompare2;
import bluecrystal.domain.SignPolicy;
import bluecrystal.domain.SignPolicyRef;
public class DerEncoder {
static final Logger LOG = LoggerFactory.getLogger(DerEncoder.class);
private static final int DETACHED = -1;
private static final int SI_VERSION = 1;
private static final String CMS_SIGNED_ID = "1.2.840.113549.1.7.2";
private static final String ID_PKCS7_SIGNED_DATA = "1.2.840.113549.1.7.2"; // o
// mesmo
// de
// cima
private static final String ID_PKCS7_DATA = "1.2.840.113549.1.7.1";
private static final String ID_RSA = "1.2.840.113549.1.1.1";
private static final String ID_SHA1_RSA = "1.2.840.113549.1.1.5";
private static final String ID_SHA256_RSA = "1.2.840.113549.1.1.11";
private static final String ID_SHA384_RSA = "1.2.840.113549.1.1.12";
private static final String ID_SHA512_RSA = "1.2.840.113549.1.1.13";
private static final String ID_CONTENT_TYPE = "1.2.840.113549.1.9.3";
private static final String ID_MESSAGE_DIGEST = "1.2.840.113549.1.9.4";
public static final String ID_SIGNING_TIME = "1.2.840.113549.1.9.5";
private static final String ID_SIGNING_CERT = "1.2.840.113549.1.9.16.2.12";
private static final String ID_SIGNING_CERT2 = "1.2.840.113549.1.9.16.2.47";
public static final String ID_SIG_POLICY = "1.2.840.113549.1.9.16.2.15";
private static final String ID_SIG_POLICY_URI = "1.2.840.113549.1.9.16.5.1";
private static final String ID_ADBE_REVOCATION = "1.2.840.113583.1.1.8";
private static final String ID_SHA1 = "1.3.14.3.2.26";
private static final String ID_SHA224 = "2.16.840.1.101.3.4.2.4";
private static final String ID_SHA256 = "2.16.840.1.101.3.4.2.1";
private static final String ID_SHA384 = "2.16.840.1.101.3.4.2.2";
private static final String ID_SHA512 = "2.16.840.1.101.3.4.2.3";
public static final int NDX_SHA1 = 0;
public static final int NDX_SHA224 = 1;
public static final int NDX_SHA256 = 2;
public static final int NDX_SHA384 = 3;
public static final int NDX_SHA512 = 4;
private static final String PF_PF_ID = "2.16.76.1.3.1";
private static final int BIRTH_DATE_INI = 0;
private static final int BIRTH_DATE_LEN = 8;
private static final int CPF_INI = BIRTH_DATE_LEN;
private static final int CPF_LEN = CPF_INI + 11;
private static final int PIS_INI = CPF_LEN;
private static final int PIS_LEN = PIS_INI + 11;
private static final int RG_INI = PIS_LEN;
private static final int RG_LEN = RG_INI + 15;
private static final int RG_ORG_UF_INI = RG_LEN;
private static final int RG_ORG_UF_LEN = RG_ORG_UF_INI + 6;
private static final int RG_UF_LEN = 2;
private static final String ICP_BRASIL_PF = "ICP-Brasil PF";
private static final String ICP_BRASIL_PJ = "ICP-Brasil PJ";
private static final String CERT_TYPE_FMT = "cert_type%d";
private static final String CNPJ_OID = "2.16.76.1.3.3";
private static final String ICP_BRASIL_PC_PREFIX_OID = "2.16.76.1.2";
private static final String EKU_OCSP_SIGN_OID = "1.3.6.1.5.5.7.3.9";
private static final String EKU_TIMESTAMP_OID = "1.3.6.1.5.5.7.3.8";
private static final String EKU_IPSEC_USER_OID = "1.3.6.1.5.5.7.3.7";
private static final String EKU_IPSEC_TUNNEL_OID = "1.3.6.1.5.5.7.3.6";
private static final String EKU_IPSEC_END_OID = "1.3.6.1.5.5.7.3.5";
private static final String EKU_EMAIL_PROT_OID = "1.3.6.1.5.5.7.3.4";
private static final String EKU_CODE_SIGN_OID = "1.3.6.1.5.5.7.3.3";
private static final String EKU_CLIENT_AUTH_OID = "1.3.6.1.5.5.7.3.2";
private static final String EKU_SERVER_AUTH_OID = "1.3.6.1.5.5.7.3.1";
private static final String UPN = "1.3.6.1.4.1.311.20.2.3";
private static final String PROFESSIONAL_OID = "2.16.76.1.4.";
private static final String OAB_OID = "2.16.76.1.4.2.1.1";
private static final String PJ_PF_INSS_OID = "2.16.76.1.3.7";
private static final String PERSON_NAME_OID = "2.16.76.1.3.2";
private static final String PF_PF_INSS_OID = "2.16.76.1.3.6";
private static final String ELEITOR_OID = "2.16.76.1.3.5";
private static final String PJ_PF_ID = "2.16.76.1.3.4";
// PF 2.16.76.1.3.5 - Titulo de eleitor(12), Zona Eleitoral (3), Secao (4)
private static final int ELEITOR_INI = 0;
private static final int ELEITOR_LEN = 12;
private static final int ZONA_INI = ELEITOR_LEN;
private static final int ZONA_LEN = 3;
private static final int SECAO_INI = ZONA_INI + ZONA_LEN;
private static final int SECAO_LEN = 4;
// PJ 2.16.76.1.3.7 - INSS (12)
private static final int INSS_INI = 0;
private static final int INSS_LEN = 12;
// 2.16.76.1.4.2.1.1- = nas primeiras 07 (sete) posicoes os digitos
// alfanumericos do Numero de Inscricao junto a Seccional, e nas 2 (duas)
// posicoes subsequentes a sigla do Estado da Seccional.
private static final int OAB_REG_INI = 0;
private static final int OAB_REG_LEN = 12;
private static final int OAB_UF_INI = OAB_REG_LEN;
private static final int OAB_UF_LEN = 3;
private static final String CERT_POL_OID = "certPolOid%d";
private static final String CERT_POL_QUALIFIER = "certPolQualifier%d";
public byte[] buildCmsBody(String signedHashId,
X509Certificate certContent, byte[] content, String hashId,
int version) throws CertificateEncodingException, IOException {
final ASN1EncodableVector whole = new ASN1EncodableVector();
whole.add(new DERObjectIdentifier(CMS_SIGNED_ID));
final ASN1EncodableVector body = new ASN1EncodableVector();
// ----- versao -------
// final int version = 1;
body.add(new DERInteger(version));
buildDigestAlg(body, hashId);
// buildContentInfo(body, content);
buildCerts(body, certContent);
buildSignerInfo(body, signedHashId, certContent, hashId);
whole.add(new DERTaggedObject(0, new DERSequence(body)));
return genOutput(new DERSequence(whole));
}
public byte[] buildCmsBody(byte[] signedHashId,
X509Certificate certContent, List<X509Certificate> chain,
int hashId, int version, int attachSize) throws Exception {
final ASN1EncodableVector whole = new ASN1EncodableVector(); // 0 SEQ
whole.add(new DERObjectIdentifier(CMS_SIGNED_ID)); // 1 SEQ
final ASN1EncodableVector body = new ASN1EncodableVector();
// ----- versao -------
// final int version = 1;
body.add(new DERInteger(version)); // 3 INT
buildDigestAlg(body, getHashAlg(hashId)); // 3 SET
buildContentInfo(body, attachSize); // 3 SEQ
buildCerts(body, chain); // 3 CS
buildSignerInfo(body, signedHashId, certContent, hashId); // 3 SET
whole.add(new DERTaggedObject(0, new DERSequence( // 2 SEQ
body))); // 1 CS
return genOutput(new DERSequence(whole));
}
// cmsOut = de.buildADRBBody(asiEx.getSignedHash(), asiEx.getX509(),
// addChain?chain:null,
// asiEx.getOrigHash(),
// policyHash, asiEx.getCertHash(), asiEx.getSigningTime(),
// asiEx.getIdSha(), policyUri, policyId,
// version, signingCertFallback);
public byte[] buildADRBBody(List<AppSignedInfoEx> listAsiEx,
SignPolicy signPol, List<X509Certificate> chain, int version,
boolean signingCertFallback, int attachSize) throws Exception {
// AppSignedInfoEx asiEx = listAsiEx.get(0);
final ASN1EncodableVector whole = new ASN1EncodableVector(); // 0 SEQ
whole.add(new DERObjectIdentifier(CMS_SIGNED_ID)); // 1 SEQ
final ASN1EncodableVector body = new ASN1EncodableVector();
// ----- versao -------
// final int version = 1;
body.add(new DERInteger(version)); // 3 INT
List<String> listHashId = createHashList(listAsiEx);
buildDigestAlg(body, listHashId); // 3 SET
buildContentInfo(body, attachSize); // 3 SEQ
if (chain != null) {
buildCerts(body, chain); // 3 CS
} else {
buildCertsASIE(body, listAsiEx); // 3 CS
}
// buildADRBSignerInfo(body, asiEx.getSignedHash(), asiEx.getX509(),
// asiEx.getOrigHash(), signPol.getPolicyHash(),
// asiEx.getCertHash(), asiEx.getSigningTime(),
// asiEx.getIdSha(), signPol.getPolicyUri(),
// signPol.getPolicyId(),
// signingCertFallback); // 3 SET
buildADRBSignerInfo(body, listAsiEx, signPol, signingCertFallback); // 3
// SET
whole.add(new DERTaggedObject(0, new DERSequence( // 2 SEQ
body))); // 1 CS
return genOutput(new DERSequence(whole));
}
private List<String> createHashList(List<AppSignedInfoEx> listAsiEx)
throws Exception {
List<String> ret = new ArrayList<String>();
for (AppSignedInfoEx next : listAsiEx) {
ret.add(getHashAlg(next.getIdSha()));
}
dedup(ret);
return ret;
}
private void dedup(List<String> list) {
Map<String, String> map = new HashMap<String, String>();
Iterator<String> it = list.iterator();
while (it.hasNext()) {
String next = it.next();
map.put(next, next);
}
list.clear();
for (String next : map.values()) {
list.add(next);
}
}
private byte[] genOutput(DERSequence whole) throws IOException {
final ByteArrayOutputStream bOut = new ByteArrayOutputStream();
final ASN1OutputStream dout = new ASN1OutputStream(bOut);
dout.writeObject(whole);
dout.close();
return bOut.toByteArray();
}
private void buildSignerInfo(ASN1EncodableVector body,
byte[] signedHashContent, X509Certificate certContent, int hashId)
throws Exception {
// ----- Signers Info --------
final ASN1EncodableVector vec = new ASN1EncodableVector();
final ASN1EncodableVector signerinfoVector = new ASN1EncodableVector();
signerinfoVector.add(new DERInteger(SI_VERSION));
signerinfoVector.add(siAddCert(certContent));
signerinfoVector.add(siAddDigestAlgorithm(getHashAlg(hashId)));
signerinfoVector
.add(siAddDigestEncryptionAlgorithm(getHashSignAlg(hashId)));
// Add the digest
signerinfoVector.add(new DEROctetString(signedHashContent));
final DERSequence siSeq = new DERSequence(signerinfoVector);
vec.add(siSeq);
DERSet siSet = new DERSet(vec);
body.add(siSet);
}
private void buildADRBSignerInfo(ASN1EncodableVector body,
List<AppSignedInfoEx> listAsiEx, SignPolicy signPol,
boolean signingCertFallback) throws Exception {
final ASN1EncodableVector vec = new ASN1EncodableVector();
// DERSequence siSeq = null;
// ----- Signers Info --------
for (AppSignedInfoEx next : listAsiEx) {
final ASN1EncodableVector signerinfoVector = new ASN1EncodableVector();
String hashId = getHashAlg(next.getIdSha());
String hashSignId = getHashSignAlg(next.getIdSha());
signerinfoVector.add(new DERInteger(SI_VERSION));
signerinfoVector.add(siAddCert(next.getX509()));
signerinfoVector.add(siAddDigestAlgorithm(hashId));
// der encoded structure
DERTaggedObject derEncStruct = adrbSiCreateDerEncSigned(
next.getOrigHash(), signPol.getPolicyHash(),
next.getCertHash(), next.getX509(), next.getSigningTime(),
next.getIdSha(), signPol.getPolicyUri(),
signPol.getPolicyId(), signingCertFallback);
signerinfoVector.add(derEncStruct);
signerinfoVector.add(siAddDigestEncryptionAlgorithm(hashSignId));
// Add the digest
signerinfoVector.add(new DEROctetString(next.getSignedHash()));
final DERSequence siSeq = new DERSequence(signerinfoVector);
vec.add(siSeq);
}
// ----- Signers Info --------
DERSet siSet = new DERSet(vec);
body.add(siSet);
}
// private void buildADRBSignerInfo(ASN1EncodableVector body,
// byte[] signedHashContent, X509Certificate certContent,
// byte[] origHash, byte[] polHash, byte[] certHash, Date now,
// int hashOption, String sigPolicyUri, String sigPolicyId,
// boolean signingCertFallback) throws Exception {
// String hashId = getHashAlg(hashOption);
// String hashSignId = getHashSignAlg(hashOption);
// // ----- Signers Info --------
//
// final ASN1EncodableVector vec = new ASN1EncodableVector();
// final ASN1EncodableVector signerinfoVector = new ASN1EncodableVector();
// signerinfoVector.add(new DERInteger(SI_VERSION));
//
// signerinfoVector.add(siAddCert(certContent));
// signerinfoVector.add(siAddDigestAlgorithm(hashId));
// // der encoded structure
// DERTaggedObject derEncStruct = adrbSiCreateDerEncSigned(origHash,
// polHash, certHash, certContent, now, hashOption, sigPolicyUri,
// sigPolicyId, signingCertFallback);
// signerinfoVector.add(derEncStruct);
//
// signerinfoVector.add(siAddDigestEncryptionAlgorithm(hashSignId));
// // Add the digest
// signerinfoVector.add(new DEROctetString(signedHashContent));
//
// final DERSequence siSeq = new DERSequence(signerinfoVector);
// vec.add(siSeq);
// DERSet siSet = new DERSet(vec);
// body.add(siSet);
//
// }
public DERTaggedObject adrbSiCreateDerEncSigned(byte[] origHash,
byte[] polHash, byte[] certHash, X509Certificate cert, Date now,
int hashId, String sigPolicyUri, String sigPolicyId,
boolean signingCertFallback) throws Exception {
DERSequence seq00 = siCreateDerEncSeqADRB(origHash, polHash, certHash,
cert, now, hashId, sigPolicyUri, sigPolicyId,
signingCertFallback);
DERTaggedObject derEncStruct = new DERTaggedObject(false, 0, seq00);
return derEncStruct;
}
public ASN1Set siCreateDerEncSignedADRB(byte[] origHash, byte[] polHash,
byte[] certHash, X509Certificate cert, Date now, int hashId,
String sigPolicyUri, String sigPolicyId, boolean signingCertFallback)
throws Exception {
DERSequence seq00 = siCreateDerEncSeqADRB(origHash, polHash, certHash,
cert, now, hashId, sigPolicyUri, sigPolicyId,
signingCertFallback);
ASN1Set retSet = new DERSet(seq00);
return retSet;
}
public ASN1Set siCreateDerEncSignedCMS3(byte[] origHash, byte[] certHash,
X509Certificate cert, Date now, String hashId)
throws CertificateEncodingException {
return null;
}
private DERSequence siCreateDerEncSeqADRB(byte[] origHash, byte[] polHash,
byte[] certHash, X509Certificate cert, Date now, int hashNdx,
String sigPolicyUri, String sigPolicyId, boolean signingCertFallback)
throws Exception {
String hashId = getHashAlg(hashNdx);
final ASN1EncodableVector desSeq = new ASN1EncodableVector();
// As assinaturas feitas segundo esta PA definem como obrigatorios as
// seguintes atributos
// assinados:
// a) id-contentType;
// b) id-messageDigest;
// c.1) Para as versoes 1.0, 1.1 e 2.0, id-aa-signingCertificate;
// c.2) A partir da versao 2.1, inclusive, id-aa-signingCertificateV2;
// d) id-aa-ets-sigPolicyId.
// A
// private static final String ID_CONTENT_TYPE = "1.2.840.113549.1.9.3";
Attribute seq5 = createContentType();
desSeq.add(seq5);
// OPTIONAL
// private static final String ID_SIGNING_TIME = "1.2.840.113549.1.9.5";
if (now != null) {
Attribute seq3 = createSigningTime(now);
desSeq.add(seq3);
}
// B
// private static final String ID_MESSAGE_DIGEST =
// "1.2.840.113549.1.9.4";
if (origHash != null) {
Attribute seq4 = createMessageDigest(origHash);
desSeq.add(seq4);
}
// D
// private static final String ID_SIG_POLICY =
// "1.2.840.113549.1.9.16.2.15";
if (polHash != null && sigPolicyUri != null && sigPolicyId != null) {
Attribute seq2 = createPolicyId(polHash, hashId, sigPolicyUri,
sigPolicyId);
desSeq.add(seq2);
}
// C
// private static final String ID_SIGNING_CERT2 =
// "1.2.840.113549.1.9.16.2.47";
if (certHash != null && cert != null) {
Attribute seq1 = createCertRef(certHash, cert, signingCertFallback,
hashNdx);
desSeq.add(seq1);
}
DERSequence seq00 = new DERSequence(desSeq);
return seq00;
}
private Attribute createContentType() {
// // final ASN1EncodableVector desSeq = new ASN1EncodableVector();
// // desSeq.add(new DERObjectIdentifier(ID_CONTENT_TYPE));
final ASN1EncodableVector setEV = new ASN1EncodableVector();
setEV.add(new DERObjectIdentifier(ID_PKCS7_DATA));
DERSet set = new DERSet(setEV);
// // desSeq.add(set);
// // DERSequence seq = new DERSequence(desSeq);
Attribute seq1 = new Attribute(
new ASN1ObjectIdentifier(ID_CONTENT_TYPE), set);
return seq1;
}
private Attribute createMessageDigest(byte[] origHash) {
final ASN1EncodableVector setEV = new ASN1EncodableVector();
setEV.add(new DEROctetString(origHash));
DERSet set = new DERSet(setEV);
Attribute seq1 = new Attribute(new ASN1ObjectIdentifier(
ID_MESSAGE_DIGEST), set);
return seq1;
}
private Attribute createSigningTime(Date now) {
final ASN1EncodableVector setEV = new ASN1EncodableVector();
setEV.add(new DERUTCTime(now));
DERSet set = new DERSet(setEV);
Attribute seq1 = new Attribute(
new ASN1ObjectIdentifier(ID_SIGNING_TIME), set);
return seq1;
}
private Attribute createPolicyId(byte[] polHash, String polHashAlg,
String sigPolicyUri, String sigPolicyId) {
final ASN1EncodableVector desSeq12 = new ASN1EncodableVector();
desSeq12.add(new DERObjectIdentifier(polHashAlg));
DERSequence seq12 = new DERSequence(desSeq12);
final ASN1EncodableVector desSeq1 = new ASN1EncodableVector();
desSeq1.add(seq12);
desSeq1.add(new DEROctetString(polHash));
DERSequence seq1 = new DERSequence(desSeq1);
// // end seq 1
// IGUALAR AO ITAU
final ASN1EncodableVector desSeq22 = new ASN1EncodableVector();
desSeq22.add(new DERObjectIdentifier(ID_SIG_POLICY_URI));
desSeq22.add(new DERIA5String(sigPolicyUri));
DERSequence seq22 = new DERSequence(desSeq22);
final ASN1EncodableVector desSeq2 = new ASN1EncodableVector();
desSeq2.add(seq22);
DERSequence seq2 = new DERSequence(desSeq2);
final ASN1EncodableVector aevDSet1 = new ASN1EncodableVector();
final ASN1EncodableVector aevDSeq1 = new ASN1EncodableVector();
aevDSeq1.add(new DERObjectIdentifier(sigPolicyId));
aevDSeq1.add(seq1);
aevDSeq1.add(seq2);
DERSequence dsq1 = new DERSequence(aevDSeq1);
aevDSet1.add(dsq1);
DERSet ds1 = new DERSet(aevDSet1);
Attribute ret = new Attribute(new ASN1ObjectIdentifier(ID_SIG_POLICY),
ds1);
return ret;
}
private Attribute createCertRef(byte[] certHash,
X509Certificate certContent, boolean signingCertFallback, int hashId)
throws Exception {
// *** BEGIN ***
// 5.2.1.1.3 Certificados Obrigatoriamente Referenciados
// O atributo signingCertificate deve conter referencia apenas ao
// certificado do signatario.
// 5.2.1.1.4 Certificados Obrigatorios do Caminho de Certificacao
// Para a versao 1.0: nenhum certificado
// Para as versoes 1.1, 2.0 e 2.1: o certificado do signatario.
// ESSCertIDv2 ::= SEQUENCE {
// hashAlgorithm AlgorithmIdentifier
// DEFAULT {algorithm id-sha256},
// certHash Hash,
// issuerSerial IssuerSerial OPTIONAL
// }
//
// Hash ::= OCTET STRING
//
// IssuerSerial ::= SEQUENCE {
// issuer GeneralNames,
// serialNumber CertificateSerialNumber
// }
final ASN1EncodableVector issuerSerialaev = new ASN1EncodableVector();
final ASN1EncodableVector issuerCertaev = new ASN1EncodableVector();
DERTaggedObject issuerName = new DERTaggedObject(true, 4, // issuer
// GeneralNames,
getEncodedIssuer(certContent.getTBSCertificate()));
// DERTaggedObject issuerName = new DERTaggedObject(false, 0, // issuer
// GeneralNames,
// getEncodedIssuer(certContent.getTBSCertificate()));
issuerCertaev.add(issuerName);
DERSequence issuerCertseq = new DERSequence(issuerCertaev); // IssuerSerial
// ::=
// SEQUENCE
// {
issuerSerialaev.add(issuerCertseq);
// serialNumber CertificateSerialNumber
BigInteger serialNumber = certContent.getSerialNumber();
issuerSerialaev.add(new DERInteger(serialNumber));
DERSequence issuerSerial = new DERSequence(issuerSerialaev);
// *** END ***
final ASN1EncodableVector essCertIDv2aev = new ASN1EncodableVector();
essCertIDv2aev.add(new DEROctetString(certHash)); // Hash ::= OCTET
// STRING
essCertIDv2aev.add(issuerSerial); // ESSCertIDv2 ::= SEQUENCE {
// hashAlgorithm AlgorithmIdentifier
if (!((signingCertFallback && hashId == NDX_SHA1) || (!signingCertFallback && hashId == NDX_SHA256))) {
DERObjectIdentifier hashAlgorithm = new DERObjectIdentifier(
getHashAlg(hashId));
essCertIDv2aev.add(hashAlgorithm);
}
// Nota 4: Para o atributo ESSCertIDv2, utilizada nas versoes 2.1 das
// politicas de assinatura
// baseadas em CAdES, as aplicacoes NaO DEVEM codificar o campo
// hashAlgorithm caso
// utilize o mesmo algoritmo definido como valor default (SHA-256),
// conforme ISO 8825-1.
DERSequence essCertIDv2seq = new DERSequence(essCertIDv2aev);
// ************************************************************************
//
final ASN1EncodableVector aevSeq3 = new ASN1EncodableVector();
aevSeq3.add(essCertIDv2seq);
DERSequence seq3 = new DERSequence(aevSeq3);
final ASN1EncodableVector aevSeq2 = new ASN1EncodableVector();
aevSeq2.add(seq3);
DERSequence seq2 = new DERSequence(aevSeq2);
final ASN1EncodableVector aevSet = new ASN1EncodableVector();
aevSet.add(seq2);
ASN1Set mainSet = new DERSet(aevSet);
Attribute seq1 = new Attribute(new ASN1ObjectIdentifier(
signingCertFallback ? ID_SIGNING_CERT : ID_SIGNING_CERT2),
mainSet);
return seq1;
}
private void buildSignerInfo(ASN1EncodableVector body,
String signedHashContent, X509Certificate certContent, String hashId)
throws CertificateEncodingException {
// ----- Signers Info --------
final ASN1EncodableVector vec = new ASN1EncodableVector();
final ASN1EncodableVector signerinfoVector = new ASN1EncodableVector();
signerinfoVector.add(new DERInteger(SI_VERSION)); // 5 INT
signerinfoVector.add(siAddCert(certContent));
signerinfoVector.add(siAddDigestAlgorithm(hashId));
signerinfoVector.add(siAddDigestEncryptionAlgorithm(ID_SHA1_RSA)); // 6
// OCT
// STR
// Add the digest
signerinfoVector.add(new DEROctetString(
getDerSignedDigest(signedHashContent)));
final DERSequence siSeq = new DERSequence(signerinfoVector); // 4 SEQ
vec.add(siSeq);
DERSet siSet = new DERSet(vec); // 3 SET
body.add(siSet);
}
private byte[] getDerSignedDigest(String signedHashContent) {
byte[] ret = Base64.decode(signedHashContent);
return ret;
}
private DERSequence siAddDigestEncryptionAlgorithm(String hashId) {
// Nota 3: Em atencao aa RFC 3370 (Cryptographic Message Syntax (CMS)
// Algorithms), item
// "2.1 SHA-1"; e RFC 5754 (Using SHA2 Algorithms with Cryptographic
// Message Syntax),
// item "2 - Message Digest Algorithms", recomenda-se a ausencia do
// campo "parameters" na
// estrutura "AlgorithmIdentifier", usada na indicacao do algoritmo de
// hash, presentes nas
// estruturas ASN.1 "SignedData.digestAlgorithms",
// "SignerInfo.digestAlgorithm" e
// "SignaturePolicyId.sigPolicyHash.hashAlgorithm".
// AlgorithmIdentifier ::= SEQUENCE {
// algorithm OBJECT IDENTIFIER,
// parameters ANY DEFINED BY algorithm OPTIONAL }
// Os processos para criacao e verificacao de assinaturas segundo esta
// PA devem utilizar o
// algoritmo :
// a) para a versao 1.0: sha1withRSAEncryption(1 2 840 113549 1 1 5),
// b) para a versao 1.1: sha1withRSAEncryption(1 2 840 113549 1 1 5) ou
// sha256WithRSAEncryption(1.2.840.113549.1.1.11)
// c) para as versoes 2.0 e 2.1:
// sha256WithRSAEncryption(1.2.840.113549.1.1.11).
ASN1EncodableVector digestEncVetor = new ASN1EncodableVector();
digestEncVetor.add(new DERObjectIdentifier(hashId));
// VER NOTA
// digestEncVetor.add(new DERNull());
return new DERSequence(digestEncVetor);
}
private DERSequence siAddDigestAlgorithm(String hashId) {
// Add the digestEncAlgorithm
ASN1EncodableVector digestVetor = new ASN1EncodableVector();
digestVetor.add(new DERObjectIdentifier(hashId)); // 6 OID
digestVetor.add(new DERNull()); // 6 NULL
return new DERSequence(digestVetor); // 5 SEQ
}
private DERSequence siAddCert(X509Certificate certContent)
throws CertificateEncodingException {
ASN1EncodableVector certVetor = new ASN1EncodableVector();
certVetor.add(getEncodedIssuer(certContent.getTBSCertificate())); // 6
// ISSUER
certVetor.add(new DERInteger(certContent.getSerialNumber())); // 6 INT -
// SERIAL
return (new DERSequence(certVetor)); // 5 SEQ
}
private static DLSequence getEncodedIssuer(final byte[] enc) {
try {
final ASN1InputStream in = new ASN1InputStream(
new ByteArrayInputStream(enc));
final ASN1Sequence seq = (ASN1Sequence) in.readObject();
return (DLSequence) seq
.getObjectAt(seq.getObjectAt(0) instanceof DERTaggedObject ? 3
: 2);
} catch (final IOException e) {
return null;
}
}
private void buildCertsASIE(ASN1EncodableVector body,
List<AppSignedInfoEx> listAsiEx)
throws CertificateEncodingException, IOException {
List<X509Certificate> chain = new ArrayList<X509Certificate>();
for (AppSignedInfoEx next : listAsiEx) {
chain.add(next.getX509());
}
buildCerts(body, chain);
}
private void buildCerts(ASN1EncodableVector body,
List<X509Certificate> chain) throws IOException,
CertificateEncodingException {
// -------- Certificados
ASN1EncodableVector certVector = new ASN1EncodableVector();
for (X509Certificate next : chain) {
ASN1InputStream tempstream = new ASN1InputStream(
new ByteArrayInputStream(next.getEncoded()));
certVector.add(tempstream.readObject()); // 5 CERT (SEQ)
}
final DERSet dercertificates = new DERSet(certVector); // 4 SET
body.add(new DERTaggedObject(false, 0, dercertificates)); // 3 CS
}
private void buildCerts(ASN1EncodableVector body,
X509Certificate certContent) throws IOException,
CertificateEncodingException {
// -------- Certificados
ASN1EncodableVector certVector = new ASN1EncodableVector();
ASN1InputStream tempstream = new ASN1InputStream(
new ByteArrayInputStream(certContent.getEncoded()));
certVector.add(tempstream.readObject()); // 5 CERT (SEQ)
final DERSet dercertificates = new DERSet(certVector); // 4 SET
body.add(new DERTaggedObject(false, 0, dercertificates)); // 3 CS
}
private void buildContentInfo(final ASN1EncodableVector body, int size) {
// ------ Content Info
ASN1EncodableVector contentInfoVector = new ASN1EncodableVector();
contentInfoVector.add(new DERObjectIdentifier(ID_PKCS7_DATA)); // 4 OID
if (size != DETACHED) {
byte[] content = new byte[size];
for (int i = 0; i < size; i++) {
content[i] = (byte) 0xba;
}
contentInfoVector.add(new DERTaggedObject(0, new DEROctetString(
content)));
}
// CONTENT INFO
final DERSequence contentinfo = new DERSequence(contentInfoVector); // 3
// SEQ
body.add(contentinfo);
}
private void buildDigestAlg(final ASN1EncodableVector body, String hashId) {
// ---------- algoritmos de digest
final ASN1EncodableVector algos = new ASN1EncodableVector();
algos.add(new DERObjectIdentifier(hashId)); // 4 OID
algos.add(new DERNull()); // 4 NULL
final ASN1EncodableVector algoSet = new ASN1EncodableVector();
algoSet.add(new DERSequence(algos));
final DERSet digestAlgorithms = new DERSet(algoSet); // 2
// SET
body.add(digestAlgorithms);
}
private void buildDigestAlg(final ASN1EncodableVector body,
List<String> listHashId) {
// ---------- algoritmos de digest
final ASN1EncodableVector algos = new ASN1EncodableVector();
for (String next : listHashId) {
algos.add(new DERObjectIdentifier(next)); // 4 OID
algos.add(new DERNull()); // 4 NULL
}
final ASN1EncodableVector algoSet = new ASN1EncodableVector();
algoSet.add(new DERSequence(algos));
final DERSet digestAlgorithms = new DERSet(algoSet); // 2
// SET
body.add(digestAlgorithms);
}
public static String getHashAlg(int hash) throws Exception {
String ret = "";
switch (hash) {
case NDX_SHA1:
ret = ID_SHA1;
break;
case NDX_SHA224:
ret = ID_SHA1;
break;
case NDX_SHA256:
ret = ID_SHA256;
break;
case NDX_SHA384:
ret = ID_SHA384;
break;
case NDX_SHA512:
ret = ID_SHA512;
break;
default:
throw new Exception("hash alg nao identificado:" + hash);
}
return ret;
}
private String getHashSignAlg(int hash) throws Exception {
String ret = "";
switch (hash) {
case NDX_SHA1:
ret = ID_SHA1_RSA;
break;
case NDX_SHA224:
ret = ID_SHA1_RSA;
break;
case NDX_SHA256:
ret = ID_SHA256_RSA;
break;
case NDX_SHA384:
ret = ID_SHA384_RSA;
break;
case NDX_SHA512:
ret = ID_SHA512_RSA;
break;
default:
throw new Exception("hash alg nao identificado:" + hash);
// break;
}
return ret;
}
// capicom service
public static String extractHashId(byte[] sign) throws Exception {
String ret = null;
ASN1InputStream is = new ASN1InputStream(new ByteArrayInputStream(sign));
ASN1Primitive topLevel = is.readObject();
LOG.trace("top level:" + topLevel.getClass().getName());
if (topLevel instanceof org.bouncycastle.asn1.DLSequence) {
DLSequence topLevelDLS = (DLSequence) topLevel;
if (topLevelDLS.size() == 2) {
ASN1Encodable level1 = topLevelDLS.getObjectAt(1);
LOG.trace("level1:"
+ level1.getClass().getName());
if (level1 instanceof org.bouncycastle.asn1.DERTaggedObject) {
DERTaggedObject level1TO = (DERTaggedObject) level1;
ASN1Primitive level2 = level1TO.getObject();
LOG.trace("level2:"
+ level2.getClass().getName());
if (level2 instanceof org.bouncycastle.asn1.DERSequence) {
DERSequence level2DS = (DERSequence) level2;
LOG.trace("level2 len:"
+ level2DS.size());
ASN1Encodable level3_1 = level2DS.getObjectAt(1);
LOG.trace("level3_1:"
+ level3_1.getClass().getName());
if (level3_1 instanceof org.bouncycastle.asn1.DERSet) {
DERSet level3_1Set = (DERSet) level3_1;
ASN1Encodable level4_1 = level3_1Set.getObjectAt(0);
LOG.trace("level4_1:"
+ level4_1.getClass().getName());
if (level4_1 instanceof org.bouncycastle.asn1.DERSequence) {
DERSequence level4_1Seq = (DERSequence) level4_1;
ASN1Encodable level5_0 = level4_1Seq.getObjectAt(0);
LOG.trace("level5_0:"
+ level5_0.getClass().getName());
if (level5_0 instanceof org.bouncycastle.asn1.ASN1ObjectIdentifier) {
ASN1ObjectIdentifier level5_0Seq = (ASN1ObjectIdentifier) level5_0;
LOG.trace(level5_0Seq.toString());
ret = level5_0Seq.toString();
} else {
throw new Exception("DER enconding error");
}
} else {
throw new Exception("DER enconding error");
}
} else {
throw new Exception("DER enconding error");
}
} else {
throw new Exception("DER enconding error");
}
} else {
throw new Exception("DER enconding error");
}
} else {
throw new Exception("DER enconding error");
}
} else {
throw new Exception("DER enconding error");
}
return ret;
}
public static byte[] extractSignature(byte[] sign) throws Exception {
byte[] ret = null;
ASN1InputStream is = new ASN1InputStream(new ByteArrayInputStream(sign));
ASN1Primitive topLevel = is.readObject();
LOG.trace("top level:"
+ topLevel.getClass().getName());
if (topLevel instanceof org.bouncycastle.asn1.DLSequence) {
DLSequence topLevelDLS = (DLSequence) topLevel;
if (topLevelDLS.size() == 2) {
ASN1Encodable level1 = topLevelDLS.getObjectAt(1);
LOG.trace("level1:"
+ level1.getClass().getName());
if (level1 instanceof org.bouncycastle.asn1.DERTaggedObject) {
DERTaggedObject level1TO = (DERTaggedObject) level1;
ASN1Primitive level2 = level1TO.getObject();
LOG.trace("level2:"
+ level2.getClass().getName());
if (level2 instanceof org.bouncycastle.asn1.DERSequence) {
DERSequence level2DS = (DERSequence) level2;
LOG.trace("level2 len:"
+ level2DS.size());
ASN1Encodable level3_4 = level2DS.getObjectAt(level2DS
.size() - 1);
LOG.trace("level3_4:"
+ level3_4.getClass().getName());
if (level3_4 instanceof org.bouncycastle.asn1.DERSet) {
DERSet level3_4DS = (DERSet) level3_4;
ASN1Encodable level3_4_0 = level3_4DS
.getObjectAt(0);
LOG.trace("level3_4_0:"
+ level3_4_0.getClass().getName());
if (level3_4_0 instanceof org.bouncycastle.asn1.DERSequence) {
DERSequence level3_4_0DS = (DERSequence) level3_4_0;
LOG.trace("level3_4_0DS len:"
+ level3_4_0DS.size());
ASN1Encodable signature = level3_4_0DS
.getObjectAt(level3_4_0DS.size() - 1);
LOG.trace("signature:"
+ signature.getClass().getName());
if (signature instanceof org.bouncycastle.asn1.DEROctetString) {
DEROctetString signDOS = (DEROctetString) signature;
ret = signDOS.getOctets();
}
} else {
throw new Exception("DER enconding error");
}
} else {
throw new Exception("DER enconding error");
}
} else {
throw new Exception("DER enconding error");
}
} else {
throw new Exception("DER enconding error");
}
} else {
throw new Exception("DER enconding error");
}
} else {
throw new Exception("DER enconding error");
}
return ret;
}
public static DERTaggedObject extractDTOSignPolicyOid(byte[] sign,
SignCompare signCompare) throws Exception {
DERTaggedObject ret = null;
ASN1InputStream is = new ASN1InputStream(new ByteArrayInputStream(sign));
ASN1Primitive topLevel = is.readObject();
LOG.trace("top level:"
+ topLevel.getClass().getName());
if (topLevel instanceof org.bouncycastle.asn1.DLSequence) {
DLSequence topLevelDLS = (DLSequence) topLevel;
if (topLevelDLS.size() == 2) {
ASN1Encodable level1 = topLevelDLS.getObjectAt(1);
LOG.trace("level1:"
+ level1.getClass().getName());
if (level1 instanceof org.bouncycastle.asn1.DERTaggedObject) {
DERTaggedObject level1TO = (DERTaggedObject) level1;
ASN1Primitive level2 = level1TO.getObject();
LOG.trace("level2:"
+ level2.getClass().getName());
if (level2 instanceof org.bouncycastle.asn1.DERSequence) {
DERSequence level2DS = (DERSequence) level2;
LOG.trace("level2 len:"
+ level2DS.size());
signCompare.setNumCerts(extractCertCount(level2DS));
ret = extractSignedAttributes(level2DS);
} else {
throw new Exception("DER enconding error");
}
} else {
throw new Exception("DER enconding error");
}
} else {
throw new Exception("DER enconding error");
}
} else {
throw new Exception("DER enconding error");
}
return ret;
}
private static void saveDebug(byte[] sign) {
String x = "C:\\Users\\sergio.fonseca\\iniciativas\\bluecrystal\\temp\\sign.bin";
try {
OutputStream os = new FileOutputStream(x);
os.write(sign);
os.close();
} catch (Exception e) {
// TODO: handle exception
}
}
public static void extractSignCompare2(byte[] sign,
SignCompare2 signCompare) throws Exception {
saveDebug(sign);
DERTaggedObject ret = null;
ASN1InputStream is = new ASN1InputStream(new ByteArrayInputStream(sign));
ASN1Primitive topLevel = is.readObject();
LOG.trace("top level:"
+ topLevel.getClass().getName());
if (topLevel instanceof org.bouncycastle.asn1.DLSequence) {
DLSequence topLevelDLS = (DLSequence) topLevel;
if (topLevelDLS.size() == 2) {
ASN1Encodable level1 = topLevelDLS.getObjectAt(1);
LOG.trace("level1:"
+ level1.getClass().getName());
if (level1 instanceof org.bouncycastle.asn1.DERTaggedObject) {
DERTaggedObject level1TO = (DERTaggedObject) level1;
ASN1Primitive level2 = level1TO.getObject();
LOG.trace("level2:"
+ level2.getClass().getName());
if (level2 instanceof org.bouncycastle.asn1.DERSequence) {
DERSequence level2DS = (DERSequence) level2;
LOG.trace("level2 len:"
+ level2DS.size());
signCompare.setNumCerts(extractCertCount(level2DS));
ret = extractSignedAttributes(level2DS);
} else {
throw new Exception("DER enconding error");
}
} else {
throw new Exception("DER enconding error");
}
} else {
throw new Exception("DER enconding error");
}
} else {
throw new Exception("DER enconding error");
}
// return ret;
}
public static List<byte[]> extractCertList(byte[] sign) throws Exception {
List<byte[]> ret = null;
ASN1InputStream is = new ASN1InputStream(new ByteArrayInputStream(sign));
ASN1Primitive topLevel = is.readObject();
LOG.trace("top level:"
+ topLevel.getClass().getName());
if (topLevel instanceof org.bouncycastle.asn1.DLSequence) {
DLSequence topLevelDLS = (DLSequence) topLevel;
if (topLevelDLS.size() == 2) {
ASN1Encodable level1 = topLevelDLS.getObjectAt(1);
LOG.trace("level1:"
+ level1.getClass().getName());
if (level1 instanceof org.bouncycastle.asn1.DERTaggedObject) {
DERTaggedObject level1TO = (DERTaggedObject) level1;
ASN1Primitive level2 = level1TO.getObject();
LOG.trace("level2:"
+ level2.getClass().getName());
if (level2 instanceof org.bouncycastle.asn1.DERSequence) {
DERSequence level2DS = (DERSequence) level2;
LOG.trace("level2 len:"
+ level2DS.size());
ret = extractCertArray(level2DS);
} else {
throw new Exception("DER enconding error");
}
} else {
throw new Exception("DER enconding error");
}
} else {
throw new Exception("DER enconding error");
}
} else {
throw new Exception("DER enconding error");
}
return ret;
}
public static int extractCertCount(DERSequence certTree) {
ASN1Encodable level0 = getAt(certTree, 3);
if (level0 instanceof DERTaggedObject) {
DERTaggedObject level0Tag = (DERTaggedObject) level0;
ASN1Encodable level0Obj = level0Tag.getObject();
if (level0Obj instanceof DERSequence) {
DERSequence level0Seq = (DERSequence) level0Obj;
return 1;
} else if (level0Obj instanceof DLSequence) {
DLSequence level0Seq = (DLSequence) level0Obj;
return level0Seq.size();
}
}
return certTree.size();
}
public static List<byte[]> extractCertArray(DERSequence certTree) {
List<byte[]> ret = new ArrayList<byte[]>();
ASN1Encodable level0 = getAt(certTree, 3);
if (level0 instanceof DERTaggedObject) {
DERTaggedObject level0Tag = (DERTaggedObject) level0;
ASN1Encodable level0Obj = level0Tag.getObject();
if (level0Obj instanceof DERSequence) {
try {
DERSequence level0Seq = (DERSequence) level0Obj;
if (level0Seq.getObjectAt(2) instanceof DERBitString) {
// achei o certificado
byte[] b = level0Seq.getEncoded();
ret.add(b);
} else {
for (int i = 0; i < level0Seq.size(); i++) {
ASN1Encodable objNdx = level0Seq.getObjectAt(i);
if (objNdx instanceof DERSequence) {
try {
DERSequence objNdx2 = (DERSequence) objNdx;
byte[] b = objNdx2.getEncoded();
ret.add(b);
} catch (IOException e) {
LOG.error("DER decoding error", e);
}
}
}
}
} catch (IOException e) {
LOG.error("DER decoding error", e);
}
} else if (level0Obj instanceof ASN1Sequence) {
ASN1Sequence level0Seq = (ASN1Sequence) level0Obj;
for (int i = 0; i < level0Seq.size(); i++) {
ASN1Encodable objNdx = level0Seq.getObjectAt(i);
if (objNdx instanceof DERSequence) {
try {
DERSequence objNdx2 = (DERSequence) objNdx;
byte[] b = objNdx2.getEncoded();
ret.add(b);
} catch (IOException e) {
LOG.error("DER decoding error", e);
}
}
}
}
}
return ret;
}
public static DERTaggedObject extractSignedAttributes(DERSequence level2DS)
throws Exception {
DERTaggedObject ret = null;
ASN1Encodable level3_4 = level2DS.getObjectAt(level2DS.size() - 1);
LOG.trace("level3_4:"
+ level3_4.getClass().getName());
if (level3_4 instanceof org.bouncycastle.asn1.DERSet) {
DERSet level3_4DS = (DERSet) level3_4;
ASN1Encodable level3_4_0 = level3_4DS.getObjectAt(0);
LOG.trace("level3_4_0:"
+ level3_4_0.getClass().getName());
if (level3_4_0 instanceof org.bouncycastle.asn1.DERSequence) {
DERSequence level3_4_0DS = (DERSequence) level3_4_0;
LOG.trace("level3_4_0DS len:"
+ level3_4_0DS.size());
ASN1Encodable signedAttribs = level3_4_0DS.getObjectAt(3);
LOG.trace("signature:"
+ signedAttribs.getClass().getName());
if (signedAttribs instanceof org.bouncycastle.asn1.DERTaggedObject) {
DERTaggedObject signedAttribsDTO = (DERTaggedObject) signedAttribs;
ret = signedAttribsDTO;
// trata busca da Policy OID
} else if (signedAttribs instanceof org.bouncycastle.asn1.DERSequence) {
ret = null;
} else {
throw new Exception("DER enconding error");
}
} else {
throw new Exception("DER enconding error");
}
} else {
throw new Exception("DER enconding error");
}
return ret;
}
public static void extractSignPolicyRefFromSignedAttrib(
DERTaggedObject signedAttribsDTO, SignCompare signCompare)
throws Exception {
// String SignCompare = null;
ASN1Primitive dtoObj = signedAttribsDTO.getObject();
if (dtoObj instanceof DLSequence) {
DLSequence topSeq = (DLSequence) dtoObj;
List<String> signedAttribOid = new ArrayList<String>();
signCompare.setSignedAttribs(signedAttribOid);
for (int i = 0; i < topSeq.size(); i++) {
// treat each SIGNED ATTRIBUTE
ASN1Encodable objL1 = topSeq.getObjectAt(i);
if (objL1 instanceof DERSequence) {
DERSequence seqL1 = (DERSequence) objL1;
ASN1Encodable objL2 = seqL1.getObjectAt(0);
if (objL2 instanceof ASN1ObjectIdentifier) {
ASN1ObjectIdentifier saOid = (ASN1ObjectIdentifier) objL2;
String saOIdStr = saOid.toString();
// System.out.println(saOIdStr);
signedAttribOid.add(saOIdStr);
if (saOIdStr.compareTo(DerEncoder.ID_SIG_POLICY) == 0) {
ASN1Encodable objL21 = seqL1.getObjectAt(1);
if (objL21 instanceof DERSet) {
DERSet objL21Set = (DERSet) objL21;
ASN1Encodable objL3 = objL21Set.getObjectAt(0);
if (objL3 instanceof DERSequence) {
DERSequence objL3Seq = (DERSequence) objL3;
ASN1Encodable objL4 = objL3Seq
.getObjectAt(0);
if (objL4 instanceof ASN1ObjectIdentifier) {
ASN1ObjectIdentifier objL4Oid = (ASN1ObjectIdentifier) objL4;
signCompare.setPsOid(objL4Oid
.toString());
}
ASN1Encodable objL42 = getAt(objL3Seq, 2);
if (objL42 instanceof DERSequence) {
DERSequence objL42DerSeq = (DERSequence) objL42;
ASN1Encodable objL420 = getAt(
objL42DerSeq, 0);
if (objL420 instanceof DERSequence) {
DERSequence objL420DerSeq = (DERSequence) objL420;
ASN1Encodable psUrl = getAt(
objL420DerSeq, 1);
if (psUrl instanceof DERIA5String) {
DERIA5String psUrlIA5 = (DERIA5String) psUrl;
signCompare.setPsUrl(psUrlIA5
.getString());
}
}
}
}
}
} else if (saOIdStr
.compareTo(DerEncoder.ID_SIGNING_TIME) == 0) {
ASN1Encodable objL2SetTime = seqL1.getObjectAt(1);
if (objL2SetTime instanceof DERSet) {
DERSet objL2SetTimeDer = (DERSet) objL2SetTime;
ASN1Encodable objL2SignTime = objL2SetTimeDer
.getObjectAt(0);
if (objL2SignTime instanceof ASN1UTCTime) {
ASN1UTCTime objL2SignTimeUTC = (ASN1UTCTime) objL2SignTime;
signCompare.setSigningTime(objL2SignTimeUTC
.getDate());
}
}
}
}
}
}
}
}
public static SignPolicyRef extractVerifyRefence(byte[] policy)
throws IOException, ParseException {
SignPolicyRef ret = new SignPolicyRef();
ASN1InputStream is = new ASN1InputStream(new ByteArrayInputStream(
policy));
ASN1Primitive topLevel = is.readObject();
// SignaturePolicy ::= SEQUENCE {
// signPolicyHashAlg AlgorithmIdentifier,
// signPolicyInfo SignPolicyInfo,
// signPolicyHash SignPolicyHash OPTIONAL }
if (topLevel instanceof DLSequence) {
DLSequence topLevelDLS = (DLSequence) topLevel;
ASN1Encodable dseqL10 = topLevelDLS.getObjectAt(0);
ASN1Encodable psHashAlg = null;
if (dseqL10 instanceof DLSequence) {
DLSequence dseqL10DLS = (DLSequence) dseqL10;
psHashAlg = dseqL10DLS.getObjectAt(0);
} else if (dseqL10 instanceof ASN1ObjectIdentifier){
psHashAlg = (ASN1ObjectIdentifier) dseqL10;
} else return null;
if (psHashAlg instanceof ASN1ObjectIdentifier) {
ASN1ObjectIdentifier psHashAlgOid = (ASN1ObjectIdentifier) psHashAlg;
ret.setPsHashAlg(psHashAlgOid.toString());
}
ASN1Encodable dseqL11 = topLevelDLS.getObjectAt(1);
if (dseqL11 instanceof DLSequence) {
// SignPolicyInfo ::= SEQUENCE {
DLSequence dseqL11DLS = (DLSequence) dseqL11;
ASN1Encodable psOid = dseqL11DLS.getObjectAt(0);
// signPolicyIdentifier SignPolicyId,
// 2.16.76.1.7.1.6.2.1
if (psOid instanceof ASN1ObjectIdentifier) {
ASN1ObjectIdentifier psOidOid = (ASN1ObjectIdentifier) psOid;
ret.setPsOid(psOidOid.toString());
}
ASN1Encodable dateOfIssue = dseqL11DLS.getObjectAt(1);
// dateOfIssue GeneralizedTime,
// 2012-03-22
if (dateOfIssue instanceof ASN1GeneralizedTime) {
ASN1GeneralizedTime dateOfIssueGT = (ASN1GeneralizedTime) dateOfIssue;
ret.setDateOfIssue(dateOfIssueGT.getDate());
}
ASN1Encodable policyIssuerName = dseqL11DLS.getObjectAt(2);
// policyIssuerName PolicyIssuerName,
// C=BR, O=ICP-Brasil, OU=Instituto Nacional de Tecnologia da
// Informacao
// - ITI
if (policyIssuerName instanceof DLSequence) {
DLSequence policyIssuerNameDLSeq = (DLSequence) policyIssuerName;
ASN1Encodable policyIssuerName2 = policyIssuerNameDLSeq
.getObjectAt(0);
if (policyIssuerName2 instanceof DERTaggedObject) {
DERTaggedObject policyIssuerName2DTO = (DERTaggedObject) policyIssuerName2;
ASN1Primitive polIssuerNameObj = policyIssuerName2DTO
.getObject();
if (polIssuerNameObj instanceof DEROctetString) {
String polIssuerNameStr = new String(
((DEROctetString) polIssuerNameObj)
.getOctets());
ret.setPolIssuerName(polIssuerNameStr);
}
}
}
ASN1Encodable fieldOfApplication = dseqL11DLS.getObjectAt(3);
// fieldOfApplication FieldOfApplication,
// Este tipo de assinatura deve ser utilizado em aplicacoes ou
// processos
// de negocio nos quais a assinatura digital agrega seguranca a
// autenticacao de entidades e verificacao de integridade,
// permitindo
// sua validacao durante o prazo de, validade dos certificados
// dos
// signatarios. Uma vez que nao sao usados carimbos do tempo, a
// validacao posterior so sera possivel se existirem referencias
// temporais que identifiquem o momento em que ocorreu a
// assinatura
// digital. Nessas situacoes, deve existir legislacao especifica
// ou um
// acordo previo entre as partes definindo as referencias a
// serem
// utilizadas. Segundo esta PA, e permitido o emprego de
// multiplas
// assinaturas.
if (fieldOfApplication instanceof DEROctetString) {
DERUTF8String fieldOfApplicationDUS = (DERUTF8String) fieldOfApplication;
ret.setFieldOfApplication(fieldOfApplicationDUS.getString());
}
// signatureValidationPolicy SignatureValidationPolicy,
// signPolExtensions SignPolExtensions OPTIONAL
// SignatureValidationPolicy ::= SEQUENCE {
ASN1Encodable signatureValidationPolicy = dseqL11DLS
.getObjectAt(4);
if (signatureValidationPolicy instanceof DLSequence) {
DLSequence signatureValidationPolicyDLS = (DLSequence) signatureValidationPolicy;
// signingPeriod SigningPeriod,
// NotBefore 2012-03-22
// NotAfter 2023-06-21
ASN1Encodable signingPeriod = signatureValidationPolicyDLS
.getObjectAt(0);
if (signingPeriod instanceof DLSequence) {
DLSequence signingPeriodDLS = (DLSequence) signingPeriod;
ASN1Encodable notBefore = signingPeriodDLS
.getObjectAt(0);
if (notBefore instanceof ASN1GeneralizedTime) {
ASN1GeneralizedTime notBeforeAGT = (ASN1GeneralizedTime) notBefore;
ret.setNotBefore(notBeforeAGT.getDate());
}
ASN1Encodable notAfter = signingPeriodDLS
.getObjectAt(1);
if (notAfter instanceof ASN1GeneralizedTime) {
ASN1GeneralizedTime notAfterAGT = (ASN1GeneralizedTime) notAfter;
ret.setNotAfter(notAfterAGT.getDate());
}
}
//
// commonRules CommonRules,
ASN1Encodable commonRules = getAt(
signatureValidationPolicyDLS, 1);
if (commonRules instanceof DLSequence) {
DLSequence commonRulesDLS = (DLSequence) commonRules;
// CommonRules ::= SEQUENCE {
// signerAndVeriferRules [0] SignerAndVerifierRules
// OPTIONAL,
// signingCertTrustCondition [1]
// SigningCertTrustCondition OPTIONAL,
// timeStampTrustCondition [2] TimestampTrustCondition
// OPTIONAL,
// attributeTrustCondition [3] AttributeTrustCondition
// OPTIONAL,
// algorithmConstraintSet [4] AlgorithmConstraintSet
// OPTIONAL,
// signPolExtensions [5] SignPolExtensions OPTIONAL
// }
ASN1Encodable signerAndVeriferRules = getAt(
commonRulesDLS, 0);
// SignerAndVerifierRules ::= SEQUENCE {
// signerRules SignerRules,
// verifierRules VerifierRules }
if (signerAndVeriferRules instanceof DERTaggedObject) {
DERTaggedObject signerAndVeriferRulesDTO = (DERTaggedObject) signerAndVeriferRules;
ASN1Encodable signerAndVeriferRulesTmp = signerAndVeriferRulesDTO
.getObject();
if (signerAndVeriferRulesTmp instanceof DERSequence) {
DERSequence signerAndVeriferRulesDERSeq = (DERSequence) signerAndVeriferRulesTmp;
ASN1Encodable signerRules = getAt(
signerAndVeriferRulesDERSeq, 0);
if (signerRules instanceof DERSequence) {
DERSequence signerRulesDERSeq = (DERSequence) signerRules;
// SignerRules ::= SEQUENCE {
// externalSignedData BOOLEAN OPTIONAL,
// -- True if signed data is external to CMS
// structure
// -- False if signed data part of CMS
// structure
// -- not present if either allowed
// mandatedSignedAttr CMSAttrs,
// -- Mandated CMS signed attributes
// 1.2.840.113549.1.9.3
// 1.2.840.113549.1.9.4
// 1.2.840.113549.1.9.16.2.15
// 1.2.840.113549.1.9.16.2.47
// mandatedUnsignedAttr CMSAttrs,
// <empty sequence>
// -- Mandated CMS unsigned attributed
// mandatedCertificateRef [0] CertRefReq
// DEFAULT signerOnly,
// (1)
// -- Mandated Certificate Reference
// mandatedCertificateInfo [1] CertInfoReq
// DEFAULT none,
// -- Mandated Certificate Info
// signPolExtensions [2] SignPolExtensions
// OPTIONAL}
// CMSAttrs ::= SEQUENCE OF OBJECT
// IDENTIFIER
ASN1Encodable mandatedSignedAttr = getAt(
signerRulesDERSeq, 0);
if (mandatedSignedAttr instanceof DERSequence) {
DERSequence mandatedSignedAttrDERSeq = (DERSequence) mandatedSignedAttr;
for (int i = 0; i < mandatedSignedAttrDERSeq
.size(); i++) {
ASN1Encodable at = getAt(
mandatedSignedAttrDERSeq, i);
ret.addMandatedSignedAttr(at
.toString());
}
}
ASN1Encodable mandatedUnsignedAttr = getAt(
signerRulesDERSeq, 1);
if (mandatedUnsignedAttr instanceof DERSequence) {
DERSequence mandatedUnsignedAttrDERSeq = (DERSequence) mandatedUnsignedAttr;
}
ASN1Encodable mandatedCertificateRef = getAt(
signerRulesDERSeq, 2);
if (mandatedCertificateRef instanceof DERTaggedObject) {
DERTaggedObject mandatedCertificateRefDERSeq = (DERTaggedObject) mandatedCertificateRef;
// CertRefReq ::= ENUMERATED {
// signerOnly (1),
// -- Only reference to signer cert
// mandated
// fullpath (2)
//
// -- References for full cert path up
// to a trust point required
// }
ASN1Encodable mandatedCertificateRefTmp = mandatedCertificateRefDERSeq
.getObject();
ASN1Enumerated mandatedCertificateRefEnum = (ASN1Enumerated) mandatedCertificateRefTmp;
BigInteger valEnum = mandatedCertificateRefEnum
.getValue();
int mandatedCertificateRefInt = valEnum
.intValue();
ret.setMandatedCertificateRef(mandatedCertificateRefInt);
int x = 0;
}
}
ASN1Encodable verifierRules = getAt(
signerAndVeriferRulesDERSeq, 1);
if (verifierRules instanceof DERSequence) {
DERSequence verifierRulesDERSeq = (DERSequence) verifierRules;
}
}
}
ASN1Encodable signingCertTrustCondition = getAt(
commonRulesDLS, 1);
if (signingCertTrustCondition instanceof DERTaggedObject) {
DERTaggedObject signingCertTrustConditionDTO = (DERTaggedObject) signingCertTrustCondition;
ASN1Encodable signingCertTrustConditionTmp = signingCertTrustConditionDTO
.getObject();
if (signingCertTrustConditionTmp instanceof DERSequence) {
DERSequence signingCertTrustConditionDERSeq = (DERSequence) signingCertTrustConditionTmp;
}
}
ASN1Encodable timeStampTrustCondition = getAt(
commonRulesDLS, 2);
if (timeStampTrustCondition instanceof DERTaggedObject) {
DERTaggedObject timeStampTrustConditionDTO = (DERTaggedObject) timeStampTrustCondition;
ASN1Encodable timeStampTrustConditionTmp = timeStampTrustConditionDTO
.getObject();
if (timeStampTrustConditionTmp instanceof DERSequence) {
DERSequence timeStampTrustConditionDERSeq = (DERSequence) timeStampTrustConditionTmp;
}
}
ASN1Encodable attributeTrustCondition = getAt(
commonRulesDLS, 3);
if (attributeTrustCondition instanceof DERTaggedObject) {
DERTaggedObject attributeTrustConditionDTO = (DERTaggedObject) attributeTrustCondition;
ASN1Encodable attributeTrustConditionTmp = attributeTrustConditionDTO
.getObject();
if (attributeTrustConditionTmp instanceof DERSequence) {
DERSequence attributeTrustConditionDERSeq = (DERSequence) attributeTrustConditionTmp;
}
}
// *****************************
ASN1Encodable algorithmConstraintSet = getAt(
commonRulesDLS, 4);
ASN1Encodable signPolExtensions = getAt(commonRulesDLS,
5);
}
// commitmentRules CommitmentRules,
ASN1Encodable commitmentRules = getAt(
signatureValidationPolicyDLS, 2);
if (commitmentRules instanceof DLSequence) {
}
// signPolExtensions SignPolExtensions
// OPTIONAL
ASN1Encodable signPolExtensions = getAt(
signatureValidationPolicyDLS, 3);
if (signPolExtensions instanceof DLSequence) {
}
// }
}
}
}
// CertInfoReq ::= ENUMERATED {
// none (0) ,
// -- No mandatory requirements
// signerOnly (1) ,
// -- Only reference to signer cert mandated
// fullpath (2)
// -- References for full cert path up to a
// -- trust point mandated
// }
is.close();
return ret;
}
// ********************
// certificate Service
// *******************
public static Map<String, String> createSanMap(byte[] extensionValue,
int index) {
Map<String, String> ret = new HashMap<String, String>();
try {
if (extensionValue == null) {
return null;
}
ASN1InputStream oAsnInStream = new ASN1InputStream(
new ByteArrayInputStream(extensionValue));
ASN1Primitive derObjCP = oAsnInStream.readObject();
DLSequence derSeq = (DLSequence) derObjCP;
// int seqLen = derSeq.size();
ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) derSeq
.getObjectAt(0);
String sanOid = oid.getId();
DERTaggedObject derTO = (DERTaggedObject) derSeq.getObjectAt(1);
// int tag = derTO.getTagNo();
ASN1Primitive derObjA = derTO.getObject();
DERTaggedObject derTO2 = (DERTaggedObject) derObjA;
// int tag2 = derTO2.getTagNo();
ASN1Primitive derObjB = derTO2.getObject();
String contentStr = "";
if (derObjB instanceof DEROctetString) {
DEROctetString derOCStr = (DEROctetString) derObjB;
contentStr = new String(derOCStr.getOctets(), "UTF8");
} else if (derObjB instanceof DERPrintableString) {
DERPrintableString derOCStr = (DERPrintableString) derObjB;
contentStr = new String(derOCStr.getOctets(), "UTF8");
} else {
LOG.info("FORMAT OF SAN: UNRECOGNIZED -> "
+ derObjB.getClass().getCanonicalName());
}
LOG.trace(sanOid + " -> " + contentStr);
String value = "";
String name = "";
if (sanOid.compareTo(PF_PF_ID) == 0
|| sanOid.compareTo(PJ_PF_ID) == 0) {
value = contentStr.substring(BIRTH_DATE_INI, BIRTH_DATE_LEN);
if (isValidValue(value)) {
name = String.format(CertConstants.BIRTH_DATE_D, index);
ret.put(name, value);
}
value = contentStr.substring(CPF_INI, CPF_LEN);
if (isValidValue(value)) {
name = String.format(CertConstants.CPF_D, index);
ret.put(name, value);
}
value = contentStr.substring(PIS_INI, PIS_LEN);
if (isValidValue(value)) {
name = String.format(CertConstants.PIS_D, index);
ret.put(name, value);
}
value = contentStr.substring(RG_INI, RG_LEN);
if (isValidValue(value)) {
name = String.format(CertConstants.RG_D, index);
ret.put(name, value);
}
int rgOrgUfLen = RG_ORG_UF_LEN > contentStr.length() ? contentStr
.length() : RG_ORG_UF_LEN;
if (rgOrgUfLen > RG_ORG_UF_INI) {
value = contentStr.substring(RG_ORG_UF_INI, rgOrgUfLen);
String rgOrg = value.substring(0, value.length() - 2);
String rgUf = value.substring(value.length() - 2,
value.length());
if (isValidValue(rgOrg)) {
name = String.format(CertConstants.RG_ORG_D, index);
ret.put(name, rgOrg);
}
if (isValidValue(rgUf)) {
name = String.format(CertConstants.RG_UF_D, index);
ret.put(name, rgUf);
}
}
} else if (sanOid.compareTo(PERSON_NAME_OID) == 0) {
value = contentStr;
if (isValidValue(value)) {
name = String.format(CertConstants.PERSON_NAME_D, index);
ret.put(name, value);
}
} else if (sanOid.compareTo(CNPJ_OID) == 0) {
name = String.format(CERT_TYPE_FMT, index);
ret.put(name, ICP_BRASIL_PJ);
value = contentStr;
if (isValidValue(value)) {
name = String.format(CertConstants.CNPJ_D, index);
ret.put(name, value);
}
} else if (sanOid.compareTo(ELEITOR_OID) == 0) {
name = String.format(CERT_TYPE_FMT, index);
ret.put(name, ICP_BRASIL_PF);
value = contentStr.substring(ELEITOR_INI, ELEITOR_LEN);
if (isValidValue(value)) {
name = String.format(CertConstants.ELEITOR_D, index);
ret.put(name, value);
}
int zonaLen = ZONA_LEN > contentStr.length() ? contentStr
.length() : ZONA_LEN;
if (zonaLen > ZONA_LEN) {
value = contentStr.substring(ZONA_INI, zonaLen);
if (isValidValue(value)) {
name = String.format(CertConstants.ZONA_D, index);
ret.put(name, value);
}
}
int secaoLen = SECAO_LEN > contentStr.length() ? contentStr
.length() : SECAO_LEN;
if (secaoLen > SECAO_LEN) {
value = contentStr.substring(SECAO_INI, SECAO_LEN);
if (isValidValue(value)) {
name = String.format(CertConstants.SECAO_D, index);
ret.put(name, value);
}
}
} else if (sanOid.compareTo(PF_PF_INSS_OID) == 0
|| sanOid.compareTo(PJ_PF_INSS_OID) == 0) {
value = contentStr.substring(INSS_INI, INSS_LEN);
if (isValidValue(value)) {
name = String.format(CertConstants.INSS_D, index);
ret.put(name, value);
}
} else if (sanOid.compareTo(OAB_OID) == 0) {
value = contentStr.substring(OAB_REG_INI, OAB_REG_LEN);
if (isValidValue(value)) {
name = String.format(CertConstants.OAB_REG_D, index);
ret.put(name, value);
}
value = contentStr.substring(OAB_UF_INI, OAB_UF_LEN);
if (isValidValue(value)) {
name = String.format(CertConstants.OAB_UF_D, index);
ret.put(name, value);
}
} else if (sanOid.startsWith(PROFESSIONAL_OID)) {
value = contentStr;
if (isValidValue(value)) {
name = String.format(CertConstants.PROFESSIONAL_D, index);
ret.put(name, value);
}
} else if (sanOid.startsWith(UPN)) {
value = contentStr;
if (isValidValue(value)) {
name = String.format(CertConstants.UPN_D, index);
ret.put(name, value);
}
} else {
LOG.error("SAN:OTHER NAME NOT RECOGNIZED");
}
} catch (Exception e) {
e.printStackTrace();
}
return ret;
}
public static byte[] getAKI(byte[] extensionValue, int index) {
byte[] ret = null;
try {
if (extensionValue == null) {
return null;
}
ASN1InputStream oAsnInStream = new ASN1InputStream(
new ByteArrayInputStream(extensionValue));
ASN1Primitive derObjCP = oAsnInStream.readObject();
DEROctetString dosCP = (DEROctetString) derObjCP;
byte[] cpOctets = dosCP.getOctets();
ASN1InputStream oAsnInStream2 = new ASN1InputStream(
new ByteArrayInputStream(cpOctets));
ASN1Primitive derObj2 = oAsnInStream2.readObject();
// derObj2 = oAsnInStream2.readObject();
DLSequence derSeq = (DLSequence) derObj2;
int seqLen = derSeq.size();
// for(int i = 0; i < seqLen; i++){
ASN1Encodable derObj3 = derSeq.getObjectAt(0);
DERTaggedObject derTO = (DERTaggedObject) derObj3;
int tag = derTO.getTagNo();
boolean empty = derTO.isEmpty();
ASN1Primitive derObj4 = derTO.getObject();
DEROctetString ocStr4 = (DEROctetString) derObj4;
ret = ocStr4.getOctets();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ret;
}
public static Map<String, String> getAIAComplete(byte[] ext)
throws UnsupportedEncodingException {
Map<String, String> ret = new HashMap<String, String>();
try {
if (ext == null)
return null;
ASN1InputStream oAsnInStream = new ASN1InputStream(
new ByteArrayInputStream(ext));
ASN1Primitive derObjAIA = oAsnInStream.readObject();
DEROctetString dosAia = (DEROctetString) derObjAIA;
byte[] aiaExtOctets = dosAia.getOctets();
// ------------ level 2
ASN1InputStream oAsnInStream2 = new ASN1InputStream(
new ByteArrayInputStream(aiaExtOctets));
ASN1Primitive derObj2 = oAsnInStream2.readObject();
DLSequence aiaDLSeq = (DLSequence) derObj2;
ASN1Encodable[] aiaAsArray = aiaDLSeq.toArray();
for (ASN1Encodable next : aiaAsArray) {
DLSequence aiaDLSeq2 = (DLSequence) next;
ASN1Encodable[] aiaAsArray2 = aiaDLSeq2.toArray();
// oid = 0 / content = 1
ASN1Encodable aiaOidEnc = aiaAsArray2[0];
ASN1ObjectIdentifier aiaOid = (ASN1ObjectIdentifier) aiaOidEnc;
String idStr = aiaOid.getId();
// if (idStr.compareTo("1.3.6.1.5.5.7.48.2") == 0) {
ASN1Encodable aiaContent = aiaAsArray2[1];
DERTaggedObject aiaDTO = (DERTaggedObject) aiaContent;
ASN1Primitive aiaObj = aiaDTO.getObject();
DEROctetString aiaDOS = (DEROctetString) aiaObj;
byte[] aiaOC = aiaDOS.getOctets();
ret.put(idStr, new String(aiaOC));
// break;
// }
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ret;
}
public static AlgorithmIdentifier createAlgorithm(int hashId)
throws Exception {
return new AlgorithmIdentifier(new ASN1ObjectIdentifier(
DerEncoder.getHashAlg(hashId)), new DERNull());
}
public static Map<String, String> getCertPolicies(byte[] certPols, int index)
throws CertificateParsingException, IOException {
Map<String, String> ret = new HashMap<String, String>();
if (certPols == null) {
return null;
}
ASN1InputStream oAsnInStream = new ASN1InputStream(
new ByteArrayInputStream(certPols));
ASN1Primitive derObjCP = oAsnInStream.readObject();
DEROctetString dosCP = (DEROctetString) derObjCP;
byte[] cpOctets = dosCP.getOctets();
ASN1InputStream oAsnInStream2 = new ASN1InputStream(
new ByteArrayInputStream(cpOctets));
ASN1Primitive derObj2 = oAsnInStream2.readObject();
DLSequence dlCP = (DLSequence) derObj2;
int seqLen = dlCP.size();
for (int i = 0; i < seqLen; i++) {
ASN1Encodable nextObj = dlCP.getObjectAt(i);
DLSequence dlCP2 = (DLSequence) nextObj;
// for(int j = 0; j < dlCP2.size(); j++){
ASN1Encodable nextObj2 = dlCP2.getObjectAt(0);
ASN1ObjectIdentifier pcOID = (ASN1ObjectIdentifier) nextObj2;
ret.put(String.format(CERT_POL_OID, index), pcOID.toString());
if (pcOID.toString().startsWith(ICP_BRASIL_PC_PREFIX_OID)) {
ret.put(String.format(CertConstants.CERT_USAGE_D, index),
getCertUsage(pcOID.toString()));
}
if (dlCP2.size() == 2) {
nextObj2 = dlCP2.getObjectAt(1);
ASN1Encodable nextObj3 = null;
if (nextObj2 instanceof DLSequence) {
DLSequence dlCP3 = (DLSequence) nextObj2;
nextObj3 = dlCP3.getObjectAt(0);
} else if (nextObj2 instanceof DERSequence) {
DERSequence dlCP3 = (DERSequence) nextObj2;
if (dlCP3.size() > 1) {
nextObj3 = dlCP3.getObjectAt(0);
}
}
if (nextObj3 != null) {
DLSequence dlCP4 = (DLSequence) nextObj3;
ASN1Encodable nextObj4a = dlCP4.getObjectAt(0);
ASN1Encodable nextObj4b = dlCP4.getObjectAt(1);
ret.put(String.format(CERT_POL_QUALIFIER, index),
nextObj4b.toString());
}
}
}
return ret;
}
public static List<String> getCrlDistributionPoints(byte[] crldpExt)
throws CertificateParsingException, IOException {
if (crldpExt == null) {
return new ArrayList<String>();
}
ASN1InputStream oAsnInStream = new ASN1InputStream(
new ByteArrayInputStream(crldpExt));
ASN1Primitive derObjCrlDP = oAsnInStream.readObject();
DEROctetString dosCrlDP = (DEROctetString) derObjCrlDP;
byte[] crldpExtOctets = dosCrlDP.getOctets();
ASN1InputStream oAsnInStream2 = new ASN1InputStream(
new ByteArrayInputStream(crldpExtOctets));
ASN1Primitive derObj2 = oAsnInStream2.readObject();
CRLDistPoint distPoint = CRLDistPoint.getInstance(derObj2);
List<String> crlUrls = new ArrayList<String>();
for (DistributionPoint dp : distPoint.getDistributionPoints()) {
DistributionPointName dpn = dp.getDistributionPoint();
// Look for URIs in fullName
if (dpn != null && dpn.getType() == DistributionPointName.FULL_NAME) {
GeneralName[] genNames = GeneralNames
.getInstance(dpn.getName()).getNames();
// Look for an URI
for (int j = 0; j < genNames.length; j++) {
if (genNames[j].getTagNo() == GeneralName.uniformResourceIdentifier) {
String url = DERIA5String.getInstance(
genNames[j].getName()).getString();
crlUrls.add(url);
}
}
}
}
return crlUrls;
}
public static byte[] encodeDigest(DigestInfo dInfo) throws IOException {
return dInfo.getEncoded(ASN1Encoding.DER);
}
public static ASN1Encodable getAt(DLSequence seq, int index) {
return seq.size() > index ? seq.getObjectAt(index) : null;
}
public static ASN1Encodable getAt(DERSequence seq, int index) {
return seq.size() > index ? seq.getObjectAt(index) : null;
}
public static boolean isValidValue(String value) {
boolean ret = true;
if (value == null || value.length() == 0) {
ret = false;
} else {
String regex = "^0*$";
Pattern datePatt = Pattern.compile(regex);
Matcher m = datePatt.matcher(value);
if (m.matches()) {
ret = false;
}
}
return ret;
}
// 2.16.76.1.2.1.n Identificacao de campos associados a Politicas de
// Certificados
// do tipo A1
// 2.16.76.1.2.2.n Identificacao de campos associados a Politicas de
// Certificados
// do tipo A2
// 2.16.76.1.2.3.n Identificacao de campos associados a Politicas de
// Certificados
// do tipo A3
// 2.16.76.1.2.4.n Identificacao de campos associados a Politicas de
// Certificados
// do tipo A4
// 2.16.76.1.2.101.n Identificacao de campos associados a Politicas de
// Certificados
// do tipo S1
// 2.16.76.1.2 2.16.76.1.2....102.n... Identificacao de campos associados a
// Politicas de Certificados
// do tipo 2
// 2.16.76.1.2 2.16.76.1.2....103.n... Identificacao de campos associados a
// Politicas de Certificados
// do tipo S3
// 2.16.76.1.2 2.16.76.1.2....104.n... Identificacao de campos associados a
// Politicas de Certificados
// do tipo S4
private static String getCertUsage(String pcOid) {
String ret = "";
if (pcOid.startsWith("2.16.76.1.2.1")) {
ret = "ICP-Brasil A1";
} else if (pcOid.startsWith("2.16.76.1.2.2")) {
ret = "ICP-Brasil A2";
} else if (pcOid.startsWith("2.16.76.1.2.3")) {
ret = "ICP-Brasil A3";
} else if (pcOid.startsWith("2.16.76.1.2.4")) {
ret = "ICP-Brasil A4";
} else if (pcOid.startsWith("2.16.76.1.2.101")) {
ret = "ICP-Brasil S1";
} else if (pcOid.startsWith("2.16.76.1.2.102")) {
ret = "ICP-Brasil S2";
} else if (pcOid.startsWith("2.16.76.1.2.103")) {
ret = "ICP-Brasil S3";
} else if (pcOid.startsWith("2.16.76.1.2.104")) {
ret = "ICP-Brasil S4";
}
return ret;
}
public static OCSPReq GenOcspReq(X509Certificate nextCert,
X509Certificate nextIssuer) throws OCSPException, OperatorCreationException, CertificateEncodingException, IOException {
OCSPReqBuilder ocspRequestGenerator = new OCSPReqBuilder();
DigestCalculatorProvider digCalcProv = new JcaDigestCalculatorProviderBuilder().setProvider("BC").build();
// CertificateID certId = new CertificateID(
// CertificateID.HASH_SHA1,
// nextIssuer, nextCert.getSerialNumber()
// );
CertificateID certId = new CertificateID(digCalcProv.get(CertificateID.HASH_SHA1),
new X509CertificateHolder (nextIssuer.getEncoded()), nextCert.getSerialNumber());
// CertificateID id = new CertificateID(digCalcProv.get(CertificateID.HASH_SHA1), testCert, BigInteger.valueOf(1));
ocspRequestGenerator.addRequest(certId);
BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis());
Extension ext = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false, new DEROctetString(nonce.toByteArray()));
ocspRequestGenerator.setRequestExtensions(new Extensions(new Extension[]{ext}));
return ocspRequestGenerator.build();
// Vector<DERObjectIdentifier> oids = new Vector<DERObjectIdentifier>();
// Vector<X509Extension> values = new Vector<X509Extension>();
//
// oids.add(OCSPObjectIdentifiers.id_pkix_ocsp_nonce);
// values.add(new X509Extension(false, new DEROctetString(nonce
// .toByteArray())));
//
// ocspRequestGenerator.setRequestExtensions(new X509Extensions(oids,
// values));
// return ocspRequestGenerator.generate();
}
// public static OCSPReq GenOcspReq(X509Certificate nextCert,
// X509Certificate nextIssuer) throws OCSPException {
//
// OCSPReqGenerator ocspRequestGenerator = new OCSPReqGenerator();
// CertificateID certId = new CertificateID(CertificateID.HASH_SHA1,
// nextIssuer, nextCert.getSerialNumber());
// ocspRequestGenerator.addRequest(certId);
//
// BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis());
// Vector<DERObjectIdentifier> oids = new Vector<DERObjectIdentifier>();
// Vector<X509Extension> values = new Vector<X509Extension>();
//
// oids.add(OCSPObjectIdentifiers.id_pkix_ocsp_nonce);
// values.add(new X509Extension(false, new DEROctetString(nonce
// .toByteArray())));
//
// ocspRequestGenerator.setRequestExtensions(new X509Extensions(oids,
// values));
// return ocspRequestGenerator.generate();
// }
public static List<String> extractOCSPUrl(X509Certificate nextCert)
throws CRLException {
List<String> OCSPUrl = new ArrayList<String>();
// LOG.trace("MISSING!!");
ASN1Primitive aiaExt = getExtensionValue(nextCert,
X509Extensions.AuthorityInfoAccess.getId());
if (aiaExt != null) {
extractAuthorityInformationAccess(OCSPUrl, aiaExt);
}
return OCSPUrl;
}
public static void extractAuthorityInformationAccess(List<String> OCSPUrl,
ASN1Primitive aiaExt) {
AuthorityInformationAccess aia = AuthorityInformationAccess.getInstance(aiaExt);
AccessDescription[] accessDescriptions = aia.getAccessDescriptions();
DERObjectIdentifier OCSPOid = new DERObjectIdentifier(
"1.3.6.1.5.5.7.48.1"); //$NON-NLS-1$
for (AccessDescription accessDescription : accessDescriptions) {
GeneralName generalName = accessDescription.getAccessLocation();
String nextName = generalName.getName().toString();
ASN1ObjectIdentifier acessMethod = accessDescription.getAccessMethod();
if (acessMethod.equals(OCSPOid)) {
OCSPUrl.add(nextName);
}
}
}
protected static ASN1Primitive getExtensionValue(
java.security.cert.X509Extension ext, String oid)
throws CRLException {
byte[] bytes = ext.getExtensionValue(oid);
if (bytes == null) {
return null;
}
return getObject(oid, bytes);
}
private static ASN1Primitive getObject(String oid, byte[] ext)
throws CRLException {
try {
ASN1InputStream aIn = new ASN1InputStream(ext);
ASN1OctetString octs = (ASN1OctetString) aIn.readObject();
aIn = new ASN1InputStream(octs.getOctets());
return aIn.readObject();
} catch (Exception e) {
throw new CRLException("exception processing extension " + oid, e); //$NON-NLS-1$
}
}
public static byte[] convSiToByte(ASN1Set newSi) throws IOException {
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
ASN1OutputStream aOut = new ASN1OutputStream(bOut);
aOut.writeObject(newSi);
aOut.close();
byte[] saAsBytes = bOut.toByteArray();
return saAsBytes;
}
}
|
0 | java-sources/al/bluecryst/bluecrystal/2.3.4/bluecrystal | java-sources/al/bluecryst/bluecrystal/2.3.4/bluecrystal/domain/OperationStatus.java | /*
Blue Crystal: Document Digital Signature Tool
Copyright (C) 2007-2015 Sergio Leal
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package bluecrystal.domain;
import java.io.InputStream;
import java.util.Date;
import java.util.Properties;
public class OperationStatus {
@Override
public String toString() {
return "CertStatus [status=" + status + ", goodUntil=" + goodUntil + "]";
}
private int status;
private Date goodUntil;
private Exception exception;
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public Date getGoodUntil() {
return goodUntil;
}
public void setGoodUntil(Date goodUntil) {
this.goodUntil = goodUntil;
}
public OperationStatus(int status, Date goodUntil) {
super();
this.status = status;
this.goodUntil = goodUntil;
}
public OperationStatus(int status, Date goodUntil, Exception exception) {
super();
this.status = status;
this.goodUntil = goodUntil;
this.exception = exception;
}
public String getBestExplanation() {
if (this.exception != null)
return getMessageByStatus(getStatus()) + " - " + this.exception.getMessage();
return getMessageByStatus(getStatus());
}
public String getMessageByStatus() {
return getMessageByStatus(getStatus());
}
public String getMessageByStatus(int i) {
Properties prop = getMessagens();
String msg = null;
if (prop != null)
msg = prop.getProperty("StatusConst." + i);
if (msg == null)
msg = "code " + i;
return msg;
}
private Properties getMessagens() {
Properties prop = new Properties();
try (InputStream in = getClass().getResourceAsStream("/bluc.messages.properties")) {
prop.load(in);
return prop;
} catch (Exception e) {
return null;
}
}
}
|
0 | java-sources/al/bluecryst/bluecrystal/2.3.4/bluecrystal/service | java-sources/al/bluecryst/bluecrystal/2.3.4/bluecrystal/service/api/BlucApi.java | package bluecrystal.service.api;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.interfaces.RSAPublicKey;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
import org.bouncycastle.cms.CMSProcessableByteArray;
import org.bouncycastle.cms.CMSSignedData;
import org.bouncycastle.cms.SignerInformation;
import org.bouncycastle.cms.SignerInformationStore;
import org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoVerifierBuilder;
import org.bouncycastle.util.Store;
import org.bouncycastle.util.encoders.Base64;
import bluecrystal.domain.AppSignedInfoEx;
import bluecrystal.domain.NameValue;
import bluecrystal.domain.OperationStatus;
import bluecrystal.domain.SignCompare;
import bluecrystal.domain.StatusConst;
import bluecrystal.service.exception.InvalidSigntureException;
import bluecrystal.service.service.ADRBService_23;
import bluecrystal.service.service.CertificateService;
import bluecrystal.service.service.CmsWithChainService;
import bluecrystal.service.service.CryptoService;
import bluecrystal.service.service.CryptoServiceImpl;
import bluecrystal.service.service.SignVerifyService;
import bluecrystal.service.service.Validator;
import bluecrystal.service.service.ValidatorSrv;
import sun.security.pkcs.ContentInfo;
import sun.security.pkcs.PKCS7;
import sun.security.pkcs.SignerInfo;
import sun.security.util.DerOutputStream;
import sun.security.x509.AlgorithmId;
import sun.security.x509.X500Name;
public class BlucApi {
private CryptoService ccServ = null;
private SignVerifyService verify = null;
private CertificateService certServ = null;
private ValidatorSrv validatorServ = null;
public static final int NDX_SHA1 = 0;
public static final int NDX_SHA224 = 1;
public static final int NDX_SHA256 = 2;
public static final int NDX_SHA384 = 3;
public static final int NDX_SHA512 = 4;
private static final int FALLBACK_LIMIT = 2048;
private static CmsWithChainService serv1024;
private static ADRBService_23 serv2048;
public BlucApi() {
super();
setCcServ(new CryptoServiceImpl());
verify = new SignVerifyService();
certServ = new CertificateService();
validatorServ = new Validator();
serv1024 = new CmsWithChainService();
serv2048 = new ADRBService_23();
}
public boolean certificate(byte[] certificado, CertificateResponse resp) throws Exception {
X509Certificate c = loadCert(certificado);
String cn = getCN(certificado);
resp.setCn(cn);
resp.setName(obterNomeExibicao(cn));
setDetails(certificado, resp.getCertdetails());
resp.setCpf(resp.getCertdetails().get("cpf0"));
resp.setSubject(resp.getCertdetails().get("subject0"));
return true;
}
public boolean envelope(byte[] certificado, byte[] sha1, byte[] sha256, byte[] assinatura, boolean politica,
Date dtAssinatura, EnvelopeResponse resp) throws Exception {
X509Certificate c = loadCert(certificado);
RSAPublicKey pubKey = (RSAPublicKey) c.getPublicKey();
byte[] sign = assinatura;
resp.setCn(obterNomeExibicao(getCN(certificado)));
setDetails(certificado, resp.getCertdetails());
if (!politica) {
resp.setEnvelope(composeEnvolopePKCS7(sign, c.getEncoded(), sha256, dtAssinatura));
resp.setPolicy("PKCS#7");
resp.setPolicyversion("1.0");
resp.setPolicyoid("1.2.840.113549.1.7");
} else if (pubKey.getModulus().bitLength() == FALLBACK_LIMIT) {
resp.setEnvelope(composeEnvelopeADRB(sign, c.getEncoded(), sha256, dtAssinatura));
resp.setPolicy("AD-RB");
resp.setPolicyversion("2.3");
resp.setPolicyoid("2.16.76.1.7.1.1.2.3");
} else {
resp.setEnvelope(composeEnvelopeADRB10(sign, c.getEncoded(), sha1, dtAssinatura));
resp.setPolicy("AD-RB");
resp.setPolicyversion("1.0");
resp.setPolicyoid("2.16.76.1.7.1.1.1");
}
return true;
}
public boolean signedAttributes(byte[] certificado, byte[] sha1, byte[] sha256, boolean politica, Date dtAssinatura,
HashResponse resp) throws Exception {
X509Certificate c = loadCert(certificado);
resp.setCn(obterNomeExibicao(getCN(certificado)));
setDetails(certificado, resp.getCertdetails());
RSAPublicKey pubKey = (RSAPublicKey) c.getPublicKey();
if (!politica) {
resp.setHash(new String(Base64.encode(sha1)));
resp.setPolicy("PKCS#7");
return true;
}
if (pubKey.getModulus().bitLength() >= FALLBACK_LIMIT) {
resp.setHash(hashSignedAttribADRB(sha256, dtAssinatura, c.getEncoded()));
resp.setPolicy("AD-RB");
resp.setPolicyversion("2.3");
resp.setPolicyoid("2.16.76.1.7.1.1.2.3");
} else {
resp.setHash(hashSignedAttribADRB10(sha1, dtAssinatura, c.getEncoded()));
resp.setPolicy("AD-RB");
resp.setPolicyversion("1.0");
resp.setPolicyoid("2.16.76.1.7.1.1.1");
}
return true;
}
private String getCN(byte[] certificate) throws Exception {
String sCert = new String(Base64.encode(certificate));
return getCertSubjectCn(sCert);
}
private void setDetails(byte[] certificate, Map<String, String> map) throws Exception {
String sCert = new String(Base64.encode(certificate));
NameValue[] l = parseCertificate(sCert);
for (NameValue nv : l) {
map.put(nv.getName(), nv.getValue());
}
}
private String hashSignedAttribADRB10(byte[] origHash, Date signingTime, byte[] x509) throws Exception {
X509Certificate cert = loadCert(x509);
byte[] ret = getCcServ().hashSignedAttribSha1(origHash, signingTime, cert);
return new String(Base64.encode(ret));
}
private String hashSignedAttribADRB(byte[] origHash, Date signingTime, byte[] x509) throws Exception {
X509Certificate cert = loadCert(x509);
byte[] ret = getCcServ().hashSignedAttribSha256(origHash, signingTime, cert);
return new String(Base64.encode(ret));
}
private String extractSignature(String signB64) throws Exception {
byte[] sign = Base64.decode(signB64);
byte[] ret = getCcServ().extractSignature(sign);
return new String(Base64.encode(ret));
}
public X509Certificate extractCert(byte[] assinatura) throws Exception {
ByteArrayInputStream bais = new ByteArrayInputStream(assinatura);
CertificateFactory cf = CertificateFactory.getInstance("X509");
Certificate cert = cf.generateCertificate(bais);
return (X509Certificate) cert;
}
@SuppressWarnings("restriction")
private String composeEnvolopePKCS7(byte[] sign, byte[] x509, byte[] origHash, Date signingTime) throws Exception {
X509Certificate cert = loadCert(x509);
// load X500Name
X500Name xName = X500Name.asX500Name(cert.getSubjectX500Principal());
// load serial number
BigInteger serial = cert.getSerialNumber();
// laod digest algorithm
AlgorithmId digestAlgorithmId = new AlgorithmId(AlgorithmId.SHA_oid);
// load signing algorithm
AlgorithmId signAlgorithmId = new AlgorithmId(AlgorithmId.RSAEncryption_oid);
// Create SignerInfo:
SignerInfo sInfo = new SignerInfo(xName, serial, digestAlgorithmId, signAlgorithmId, sign);
// Create ContentInfo:
// ContentInfo cInfo = new ContentInfo(ContentInfo.DIGESTED_DATA_OID,
// new DerValue(DerValue.tag_OctetString, dataToSign));
ContentInfo cInfo = new ContentInfo(ContentInfo.DIGESTED_DATA_OID, null);
// Create PKCS7 Signed data
PKCS7 p7 = new PKCS7(new AlgorithmId[] { digestAlgorithmId }, cInfo, new X509Certificate[] { cert },
new SignerInfo[] { sInfo });
// Write PKCS7 to bYteArray
ByteArrayOutputStream bOut = new DerOutputStream();
p7.encodeSignedData(bOut);
byte[] encodedPKCS7 = bOut.toByteArray();
return new String(Base64.encode(encodedPKCS7));
}
private String composeEnvelopeADRB10(byte[] sign, byte[] x509, byte[] origHash, Date signingTime) throws Exception {
X509Certificate cert = loadCert(x509);
byte[] ret = getCcServ().composeBodySha1(sign, cert, origHash, signingTime);
byte[] hashSa = getCcServ().hashSignedAttribSha1(origHash, signingTime, cert);
if (!verifySign(NDX_SHA1, cert, getCcServ().calcSha1(hashSa), sign)) {
throw new InvalidSigntureException();
}
return new String(Base64.encode(ret));
}
private String composeEnvelopeADRB(byte[] sign, byte[] x509, byte[] origHash, Date signingTime) throws Exception {
X509Certificate cert = loadCert(x509);
byte[] ret = getCcServ().composeBodySha256(sign, cert, origHash, signingTime);
byte[] hashSa = getCcServ().hashSignedAttribSha256(origHash, signingTime, cert);
if (!verifySign(NDX_SHA256, cert, getCcServ().calcSha256(hashSa), sign)) {
throw new InvalidSigntureException();
}
return new String(Base64.encode(ret));
}
private SignCompare extractSignCompare(String sign) throws Exception {
return getCcServ().extractSignCompare(Base64.decode(sign));
}
private String obtemPolitica(byte[] assinatura) {
String politica = null;
try {
SignCompare sc = getCcServ().extractSignCompare(assinatura);
politica = sc.getPsOid();
} catch (Exception e) {
}
return politica;
}
private static String obterNomeExibicao(String s) {
s = s.split(",")[0];
// Retira o CPF, se houver
String[] splitted = s.split(":");
if (splitted.length == 2)
return splitted[0];
return s;
}
private String recuperarNomePolitica(String politica) {
switch (politica) {
case "2.16.76.1.7.1.1.1":
return "AD-RB v1.0";
case "2.16.76.1.7.1.2.1":
return "AD-RT v1.0";
case "2.16.76.1.7.1.3.1":
return "AD-RV v1.0";
case "2.16.76.1.7.1.4.1":
return "AD-RC v1.0";
case "2.16.76.1.7.1.5.1":
return "AD-RA v1.0";
case "2.16.76.1.7.1.1.2.1":
return "AD-RB v2.1";
case "2.16.76.1.7.1.2.2.1":
return "AD-RT v2.1";
case "2.16.76.1.7.1.3.2.1":
return "AD-RV v2.1";
case "2.16.76.1.7.1.4.2.1":
return "AD-RC v2.1";
case "2.16.76.1.7.1.5.2.1":
return "AD-RA v2.1";
case "2.16.76.1.7.1.1.2.3":
return "AD-RB v2.3";
case "2.16.76.1.7.1.2.2.3":
return "AD-RT v2.3";
case "2.16.76.1.7.1.3.2.3":
return "AD-RV v2.3";
case "2.16.76.1.7.1.4.2.3":
return "AD-RC v2.3";
case "2.16.76.1.7.1.5.2.3":
return "AD-RA v2.3";
}
return politica;
}
private boolean validateSignatureByPolicy(byte[] sign, byte[] ps) throws Exception {
return ccServ.validateSignatureByPolicy(sign, ps);
}
private X509Certificate loadCert(byte[] certEnc) throws FileNotFoundException, CertificateException, IOException {
InputStream is = new ByteArrayInputStream(certEnc);
CertificateFactory cf = CertificateFactory.getInstance("X509");
X509Certificate c = (X509Certificate) cf.generateCertificate(is);
is.close();
return c;
}
protected boolean verifySign(int hashId, X509Certificate cert, byte[] contentHash, byte[] sigBytes)
throws Exception {
return verify.verify(hashId, contentHash, sigBytes, cert);
}
public String extractSignerCert(String signb64) throws Exception {
byte[] sign = Base64.decode(signb64);
X509Certificate certEE = certServ.decodeEE(sign);
return new String(Base64.encode(certEE.getEncoded()));
}
public String getCertSubject(String cert) throws Exception {
Map<String, String> certEE = validatorServ.parseCertificateAsMap(cert);
return certEE.get("subject0");
}
public String getCertSubjectCn(String cert) throws Exception {
Map<String, String> certEE = validatorServ.parseCertificateAsMap(cert);
String[] rdnList = certEE.get("subject0").split(",");
for (String nextRdn : rdnList) {
if (nextRdn.startsWith("CN")) {
String[] cnRdn = (nextRdn.trim()).split("=");
if (cnRdn.length == 2) {
return cnRdn[1];
}
}
}
return null;
}
public NameValue[] parseCertificate(String certificate) throws Exception {
return validatorServ.parseCertificate(certificate);
}
public int validateSign(byte[] assinatura, byte[] sha1, byte[] sha256, Date dtAssinatura, boolean verificarLCRs,
ValidateResponse resp) throws Exception {
String politica = obtemPolitica(assinatura);
X509Certificate certEE = certServ.decodeEE(assinatura);
byte[] certificate = certEE.getEncoded();
resp.setCertificate(new String(Base64.encode(certificate)));
resp.setCn(obterNomeExibicao(getCN(certificate)));
setDetails(certificate, resp.getCertdetails());
if (politica == null) {
OperationStatus signOk = getCcServ().validateSign(assinatura, sha1, dtAssinatura, verificarLCRs);
resp.setStatus(signOk.getMessageByStatus());
if (signOk.getStatus() != StatusConst.GOOD && signOk.getStatus() != StatusConst.UNKNOWN) {
resp.setError("Não foi possível validar a assinatura digital: " + signOk.getBestExplanation());
}
return signOk.getStatus();
} else {
int keyLength = 1024;
if (resp.getCertdetails().containsKey("key_length0"))
keyLength = Integer.parseInt(resp.getCertdetails().get("key_length0"));
byte[] origHash;
if (keyLength < 2048)
origHash = sha1;
else
origHash = sha256;
OperationStatus signOk = getCcServ().validateSign(assinatura, origHash, dtAssinatura, verificarLCRs);
resp.setStatus(signOk.getMessageByStatus());
if (signOk.getStatus() != StatusConst.GOOD && signOk.getStatus() != StatusConst.UNKNOWN) {
resp.setError("Não foi possível validar a assinatura digital: " + signOk.getBestExplanation());
return signOk.getStatus();
}
boolean f = validateSignatureByPolicy(assinatura, null);
if (!f) {
resp.setError("Não foi possíel validar a assinatura com política");
return signOk.getStatus();
}
String policyName = recuperarNomePolitica(politica);
if (policyName != null) {
String pol[] = policyName.split(" v");
resp.setPolicy(pol[0]);
resp.setPolicyversion(pol[1]);
}
resp.setPolicyoid(politica);
return StatusConst.GOOD;
}
}
public byte[] attachContentsToPKCS7(byte[] content, byte[] detached, Date dtSign, boolean verifyCLR)
throws Exception {
String policy = obtemPolitica(detached);
byte[] origHash = null;
byte[] res = null;
if (policy == null) {
byte[] contentSha1 = getCcServ().calcSha1(content);
OperationStatus sts = getCcServ().validateSign(detached, contentSha1, dtSign, verifyCLR);
if (StatusConst.GOOD != sts.getStatus() && StatusConst.UNKNOWN != sts.getStatus())
throw new Exception("invalid signature: " + sts.getBestExplanation());
CMSSignedData s = new CMSSignedData(new CMSProcessableByteArray(content), detached);
Store certStore = s.getCertificates();
Collection certList = certStore.getMatches(null);
// for (Object next : certList) {
// X509CertificateHolder holder = (X509CertificateHolder) next;
// System.out.println(holder.getSubject().toString());
// }
SignerInformationStore signers = s.getSignerInfos();
Collection c = signers.getSigners();
Iterator it = c.iterator();
int verified = 0;
it.hasNext();
SignerInformation signer = (SignerInformation) it.next();
Collection certCollection = certStore.getMatches(signer.getSID());
Iterator certIt = certCollection.iterator();
X509CertificateHolder certificateHolder = (X509CertificateHolder) certIt.next();
X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC")
.getCertificate(certificateHolder);
signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(certificateHolder));
origHash = signer.getContentDigest();
if (!Arrays.equals(origHash, contentSha1))
throw new Exception("hashes doesn't match");
Date signingTime = null;
byte[] sign = signer.getSignature();
res = composeBodySha1(sign, cert, certList, origHash, signingTime, content.length);
} else {
byte[] contentSha256 = getCcServ().calcSha256(content);
// int sts = getCcServ().validateSign(detached, contentSha256, null,
// false);
// if (StatusConst.GOOD != sts && StatusConst.UNKNOWN != sts)
// throw new Exception("invalid signature with policy: "
// + getMessageByStatus(sts));
CMSSignedData s = new CMSSignedData(new CMSProcessableByteArray(content), detached);
Store certStore = s.getCertificates();
Collection certList = certStore.getMatches(null);
// for (Object next : certList) {
// X509CertificateHolder holder = (X509CertificateHolder) next;
// //System.out.println(holder.getSubject().toString());
// }
SignerInformationStore signers = s.getSignerInfos();
Collection c = signers.getSigners();
Iterator it = c.iterator();
int verified = 0;
it.hasNext();
SignerInformation signer = (SignerInformation) it.next();
Collection certCollection = certStore.getMatches(signer.getSID());
Iterator certIt = certCollection.iterator();
X509CertificateHolder certificateHolder = (X509CertificateHolder) certIt.next();
X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC")
.getCertificate(certificateHolder);
signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(certificateHolder));
origHash = signer.getContentDigest();
// int t = signer.getSignedAttributes();
if (!Arrays.equals(origHash, contentSha256))
throw new Exception("hashes doesn't match");
SignCompare signCompare = ccServ.extractSignCompare(detached);
Date signingTime = signCompare.getSigningTime();
byte[] sign = signer.getSignature();
res = composeBodySha256(sign, cert, certList, origHash, signingTime, content.length);
}
byte[] attached = null;
Exception savedException = null;
OperationStatus signOk = new OperationStatus(StatusConst.INVALID_SIGN, null);
for (int delta = 0; delta < 4; delta++) {
try {
Map<String, String> map = createBodyMap(res, content.length, delta);
byte[] envelope_1 = Base64.decode(map.get("envelope_1"));
byte[] envelope_2 = Base64.decode(map.get("envelope_2"));
attached = new byte[envelope_1.length + content.length + envelope_2.length];
System.arraycopy(envelope_1, 0, attached, 0, envelope_1.length);
System.arraycopy(content, 0, attached, envelope_1.length, content.length);
System.arraycopy(envelope_2, 0, attached, envelope_1.length + content.length, envelope_2.length);
signOk = getCcServ().validateSign(attached, origHash, dtSign, verifyCLR);
savedException = null;
break;
} catch (Exception ioe) {
if (savedException == null)
savedException = ioe;
}
}
if (savedException != null)
throw savedException;
if (StatusConst.GOOD != signOk.getStatus() && StatusConst.UNKNOWN != signOk.getStatus())
throw new Exception("invalid attached signature: " + signOk.getBestExplanation());
return attached;
}
public byte[] composeBodySha1(byte[] sign, X509Certificate c, Collection certCollection, byte[] origHash,
Date signingTime, int attachSize) throws Exception {
byte[] ret = null;
int idSha = NDX_SHA1;
List<AppSignedInfoEx> listAsiEx = new ArrayList<AppSignedInfoEx>();
List<X509Certificate> chain = new ArrayList<X509Certificate>();
byte[] certHash = getCcServ().calcSha1(c.getEncoded());
AppSignedInfoEx asiEx = new AppSignedInfoEx(sign, origHash, signingTime, c, certHash, idSha);
listAsiEx.add(asiEx);
ret = serv1024.buildCms(listAsiEx, attachSize);
// ret = buildCms(listAsiEx, certCollection, attachSize);
return ret;
}
/*
* (non-Javadoc)
*
* @see com.ittru.service.CCService#composeBodySha256(byte[],
* java.security.cert.X509Certificate, byte[], java.util.Date)
*/
public byte[] composeBodySha256(byte[] sign, X509Certificate c, Collection certCollection, byte[] origHash,
Date signingTime, int attachSize) throws Exception {
byte[] ret = null;
int idSha = NDX_SHA256;
List<AppSignedInfoEx> listAsiEx = new ArrayList<AppSignedInfoEx>();
byte[] certHash = getCcServ().calcSha256(c.getEncoded());
AppSignedInfoEx asiEx = new AppSignedInfoEx(sign, origHash, signingTime, c, certHash, idSha);
listAsiEx.add(asiEx);
ret = serv2048.buildCms(listAsiEx, attachSize);
return ret;
}
private Map<String, String> createBodyMap(byte[] res, int contentSize, int delta) {
Map<String, String> certMap = new HashMap<String, String>();
int i = 0;
for (; i < res.length; i++) {
if (res[i] == (byte) 0xba) {
boolean foundContent = true;
for (int j = 0; j < contentSize; j++) {
if (res[j + i] != (byte) 0xba) {
foundContent = false;
break;
}
}
if (foundContent) {
break;
}
}
}
i += delta;
int begin = 0;
int end = i;
byte[] record = new byte[end - begin];
for (int z = 0; z < record.length; z++) {
record[z] = res[begin + z];
}
String value = new String(Base64.encode(record));
certMap.put("envelope_1", value);
begin = i + contentSize;
end = res.length;
record = new byte[end - begin];
for (int z = 0; z < record.length; z++) {
record[z] = res[begin + z];
}
value = new String(Base64.encode(record));
certMap.put("envelope_2", value);
return certMap;
}
public CryptoService getCcServ() {
return ccServ;
}
public void setCcServ(CryptoService ccServ) {
this.ccServ = ccServ;
}
}
|
0 | java-sources/al/bluecryst/bluecrystal/2.3.4/bluecrystal/service | java-sources/al/bluecryst/bluecrystal/2.3.4/bluecrystal/service/api/CertificateResponse.java | package bluecrystal.service.api;
import java.util.Map;
import java.util.TreeMap;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class CertificateResponse {
private String subject;
private String cn;
private String name;
private String cpf;
private String error;
private Map<String, String> certdetails = new TreeMap<>();
public String getCn() {
return cn;
}
public void setCn(String cn) {
this.cn = cn;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getCpf() {
return cpf;
}
public void setCpf(String cpf) {
this.cpf = cpf;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
public Map<String, String> getCertdetails() {
return certdetails;
}
public void setCertdetails(Map<String, String> certdetails) {
this.certdetails = certdetails;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
} |
0 | java-sources/al/bluecryst/bluecrystal/2.3.4/bluecrystal/service | java-sources/al/bluecryst/bluecrystal/2.3.4/bluecrystal/service/api/EnvelopeResponse.java | package bluecrystal.service.api;
import java.util.Map;
import java.util.TreeMap;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class EnvelopeResponse {
private String cn;
private String policy;
private String policyversion;
private String policyoid;
private String envelope;
private String error;
private Map<String, String> certdetails = new TreeMap<>();
public String getCn() {
return cn;
}
public void setCn(String cn) {
this.cn = cn;
}
public String getPolicy() {
return policy;
}
public void setPolicy(String policy) {
this.policy = policy;
}
public String getPolicyversion() {
return policyversion;
}
public void setPolicyversion(String policyversion) {
this.policyversion = policyversion;
}
public String getPolicyoid() {
return policyoid;
}
public void setPolicyoid(String policyoid) {
this.policyoid = policyoid;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
public String getEnvelope() {
return envelope;
}
public void setEnvelope(String envelope) {
this.envelope = envelope;
}
public Map<String, String> getCertdetails() {
return certdetails;
}
public void setCertdetails(Map<String, String> certdetails) {
this.certdetails = certdetails;
}
} |
0 | java-sources/al/bluecryst/bluecrystal/2.3.4/bluecrystal/service | java-sources/al/bluecryst/bluecrystal/2.3.4/bluecrystal/service/api/HashResponse.java | package bluecrystal.service.api;
import java.util.Map;
import java.util.TreeMap;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class HashResponse {
private String hash;
private String cn;
private String policy;
private String policyversion;
private String policyoid;
private String error;
private Map<String, String> certdetails = new TreeMap<>();
public String getHash() {
return hash;
}
public void setHash(String hash) {
this.hash = hash;
}
public String getCn() {
return cn;
}
public void setCn(String cn) {
this.cn = cn;
}
public String getPolicy() {
return policy;
}
public void setPolicy(String policy) {
this.policy = policy;
}
public String getPolicyversion() {
return policyversion;
}
public void setPolicyversion(String policyversion) {
this.policyversion = policyversion;
}
public String getPolicyoid() {
return policyoid;
}
public void setPolicyoid(String policyoid) {
this.policyoid = policyoid;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
public Map<String, String> getCertdetails() {
return certdetails;
}
public void setCertdetails(Map<String, String> certdetails) {
this.certdetails = certdetails;
}
} |
0 | java-sources/al/bluecryst/bluecrystal/2.3.4/bluecrystal/service | java-sources/al/bluecryst/bluecrystal/2.3.4/bluecrystal/service/api/ValidateResponse.java | package bluecrystal.service.api;
import java.util.Map;
import java.util.TreeMap;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class ValidateResponse {
private String certificate;
private String status;
private String cn;
private String policy;
private String error;
private Map<String, String> certdetails = new TreeMap<>();
public String getPolicyoid() {
return policyoid;
}
public void setPolicyoid(String policyoid) {
this.policyoid = policyoid;
}
public String getPolicyversion() {
return policyversion;
}
public void setPolicyversion(String policyversion) {
this.policyversion = policyversion;
}
private String policyoid;
private String policyversion;
public ValidateResponse() {
}
public String getCn() {
return cn;
}
public String getError() {
return error;
}
public String getPolicy() {
return policy;
}
public void setCn(String cn) {
this.cn = cn;
}
public void setError(String error) {
this.error = error;
}
public void setPolicy(String policy) {
this.policy = policy;
}
public Map<String, String> getCertdetails() {
return certdetails;
}
public void setCertdetails(Map<String, String> certdetails) {
this.certdetails = certdetails;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getCertificate() {
return certificate;
}
public void setCertificate(String certificate) {
this.certificate = certificate;
}
} |
0 | java-sources/al/bluecryst/bluecrystal/2.3.4/bluecrystal/service | java-sources/al/bluecryst/bluecrystal/2.3.4/bluecrystal/service/exception/EmptyCertPathException.java | /*
Blue Crystal: Document Digital Signature Tool
Copyright (C) 2007-2015 Sergio Leal
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package bluecrystal.service.exception;
@SuppressWarnings("serial")
public class EmptyCertPathException extends Exception {
@Override
public String getMessage() {
return "Caminho de certificação vazio";
}
}
|
0 | java-sources/al/bluecryst/bluecrystal/2.3.4/bluecrystal/service | java-sources/al/bluecryst/bluecrystal/2.3.4/bluecrystal/service/exception/NotAfterException.java | /*
Blue Crystal: Document Digital Signature Tool
Copyright (C) 2007-2015 Sergio Leal
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package bluecrystal.service.exception;
import java.security.cert.X509Certificate;
import java.util.Date;
@SuppressWarnings("serial")
public class NotAfterException extends Exception {
private X509Certificate cert;
private Date dt;
public NotAfterException(X509Certificate cert, Date dt) {
this.cert = cert;
this.dt = dt;
}
@Override
public String getMessage() {
return "Cerfiticado " + cert.getSubjectX500Principal().getName() + " não pode ser usado depois da data " + dt;
}
}
|
0 | java-sources/al/bluecryst/bluecrystal/2.3.4/bluecrystal/service | java-sources/al/bluecryst/bluecrystal/2.3.4/bluecrystal/service/exception/NotBeforeException.java | /*
Blue Crystal: Document Digital Signature Tool
Copyright (C) 2007-2015 Sergio Leal
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package bluecrystal.service.exception;
import java.security.cert.X509Certificate;
import java.util.Date;
@SuppressWarnings("serial")
public class NotBeforeException extends Exception {
private X509Certificate cert;
private Date dt;
public NotBeforeException(X509Certificate cert, Date dt) {
this.cert = cert;
this.dt = dt;
}
@Override
public String getMessage() {
return "Cerfiticado " + cert.getSubjectX500Principal().getName() + " não pode ser usado antes da data " + dt;
}
}
|
0 | java-sources/al/bluecryst/bluecrystal/2.3.4/bluecrystal/service | java-sources/al/bluecryst/bluecrystal/2.3.4/bluecrystal/service/exception/UndefStateException.java | /*
Blue Crystal: Document Digital Signature Tool
Copyright (C) 2007-2015 Sergio Leal
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package bluecrystal.service.exception;
public class UndefStateException extends Exception {
}
|
0 | java-sources/al/bluecryst/bluecrystal/2.3.4/bluecrystal/service | java-sources/al/bluecryst/bluecrystal/2.3.4/bluecrystal/service/helper/UtilsLocal.java | /*
Blue Crystal: Document Digital Signature Tool
Copyright (C) 2007-2015 Sergio Leal
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package bluecrystal.service.helper;
import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.bouncycastle.util.encoders.Base64;
import bluecrystal.service.exception.LicenseNotFoundExeception;
import bluecrystal.service.interfaces.RepoLoader;
import bluecrystal.service.loader.Messages;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class UtilsLocal {
static final Logger LOG = LoggerFactory.getLogger(UtilsLocal.class);
protected static final String ID_SHA1 = "1.3.14.3.2.26";
protected static final int ALG_SHA1 = 0;
protected static final int ALG_SHA224 = 1;
protected static final int ALG_SHA256 = 2;
protected static final int ALG_SHA384 = 3;
protected static final int ALG_SHA512 = 4;
public static String conv(byte[] byteArray){
StringBuffer result = new StringBuffer();
for (byte b:byteArray) {
result.append(String.format("%02X", b));
}
return result.toString();
}
public static byte[] convHexToByte(String content) {
byte[] signbyte;
content = content.trim();
String[] signList = splitHex(content);
signbyte = conv(signList);
return signbyte;
}
private static String[] splitHex(String content) {
String[] ret = null;
int len = content.length();
if(len % 2 == 0){
ret = new String[len/2];
for(int i = 0; i < len/2; i++){
ret[i] = content.substring(i*2, (i+1)*2);
}
}
return ret;
}
private static byte[] conv(String[] certList) {
byte[] certbyte = new byte[certList.length];
for (int i = 0; i < certbyte.length; i++) {
certbyte[i] = conv(certList[i]);
}
return certbyte;
}
private static byte conv(String hex) {
int i = Integer.parseInt(hex, 16);
byte c = (byte) i;
return c;
}
public static int hashAlgToId(String hashAlg){
int hashId = 0;
if(hashAlg.compareToIgnoreCase("SHA1")==0){
hashId = ALG_SHA1;
} else if(hashAlg.compareToIgnoreCase("SHA224")==0){
hashId = ALG_SHA224;
} else if(hashAlg.compareToIgnoreCase("SHA256")==0){
hashId = ALG_SHA256;
} else if(hashAlg.compareToIgnoreCase("SHA384")==0){
hashId = ALG_SHA384;
} else if(hashAlg.compareToIgnoreCase("SHA512")==0){
hashId = ALG_SHA512;
}
return hashId;
}
public static X509Certificate createCert(String b64Enc) throws Exception {
ByteArrayInputStream bais = new ByteArrayInputStream(Base64.decode(b64Enc.getBytes()));
CertificateFactory cf = CertificateFactory.getInstance("X509");
Certificate cert =
cf.generateCertificate(bais);
return (X509Certificate) cert;
}
public static X509Certificate createCert(byte [] b) throws Exception {
ByteArrayInputStream bais = new ByteArrayInputStream(b);
CertificateFactory cf = CertificateFactory.getInstance("X509");
Certificate cert =
cf.generateCertificate(bais);
return (X509Certificate) cert;
}
// public static String getHashAlg(int hash) throws Exception{
// String ret = "";
// switch (hash) {
// case ALG_SHA1:
// ret = ID_SHA1;
// break;
//
// case ALG_SHA224:
// ret = ID_SHA1;
// break;
//
// case ALG_SHA256:
// ret = ID_SHA256;
// break;
//
// case ALG_SHA384:
// ret = ID_SHA384;
// break;
//
// case ALG_SHA512:
// ret = ID_SHA512;
// break;
//
// default:
// throw new Exception("hash alg não identificado:" + hash);
//
// }
// return ret;
// }
// public static List<X509Certificate> listCertFromS3(String string) {
// // TODO Auto-generated method stub
// return null;
// }
// public static X509Certificate loadCertFromS3(String certName) {
// // TODO Auto-generated method stub
// return null;
// }
}
|
0 | java-sources/al/bluecryst/bluecrystal/2.3.4/bluecrystal/service | java-sources/al/bluecryst/bluecrystal/2.3.4/bluecrystal/service/helper/UtilsRepo.java | /*
Blue Crystal: Document Digital Signature Tool
Copyright (C) 2007-2015 Sergio Leal
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package bluecrystal.service.helper;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.bouncycastle.util.encoders.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import bluecrystal.service.exception.LicenseNotFoundExeception;
import bluecrystal.service.interfaces.RepoLoader;
import bluecrystal.service.util.PrefsFactory;
public class UtilsRepo {
static final Logger LOG = LoggerFactory.getLogger(UtilsRepo.class);
static private RepoLoader repoLoader;
static {
repoLoader = PrefsFactory.getRepoLoader();
// try {
// repoLoader = (RepoLoader) Class
// .forName(loaderType)
// .newInstance();
// if(repoLoader==null){
// LOG.error("Could not load Repoloader ");
// loadDefault();
// }
// } catch (Exception e) {
// LOG.error("Could not load Repoloader ", e);
// loadDefault();
// }
}
// private static void loadDefault() {
// repoLoader = new bluecrystal.service.loader.FSRepoLoader();
// }
protected static final String ID_SHA1 = "1.3.14.3.2.26";
protected static final int ALG_SHA1 = 0;
protected static final int ALG_SHA224 = 1;
protected static final int ALG_SHA256 = 2;
protected static final int ALG_SHA384 = 3;
protected static final int ALG_SHA512 = 4;
public static X509Certificate loadCertFromRepo(String certFilePath)
throws Exception {
List<X509Certificate> certList = listCertFromRepo(certFilePath);
return certList.get(0);
}
public static List<X509Certificate> listCertFromRepo(String certFilePath)
throws Exception {
String[] fileList = null;
if(!getRepoLoader().exists(certFilePath)){
if(!getRepoLoader().exists(certFilePath+".txt")){
if(!getRepoLoader().exists(certFilePath+".cer")){
throw new FileNotFoundException(getRepoLoader().getFullPath(certFilePath));
} else {
certFilePath = certFilePath+".cer";
}
} else {
certFilePath = certFilePath+".txt";
}
}
if(getRepoLoader().isDir(certFilePath) ){
fileList = getRepoLoader().list(certFilePath);
} else {
fileList = new String[1];
fileList[0] = certFilePath;
}
List<X509Certificate> retList = new ArrayList<X509Certificate>();
for(String next : fileList){
try {
retList.addAll(listCertFromFile(next));
} catch (Exception e) {
LOG.error("Could not add certs from Repo "+next, e);
}
}
return retList;
}
public static List<X509Certificate> listCertFromFile(String certFilePath)
throws Exception {
InputStream is = null;
List<X509Certificate> retList = new ArrayList<X509Certificate>();
try {
is = getRepoLoader().load(certFilePath);
} catch (LicenseNotFoundExeception e) {
}
CertificateFactory cf = CertificateFactory.getInstance("X509");
Collection<? extends Certificate> c =
cf.generateCertificates(is);
for(Certificate next: c){
retList.add((X509Certificate)next);
}
return retList;
}
public static X509Certificate loadCertFromFile(String certFilePath)
throws Exception {
InputStream is = new FileInputStream(certFilePath);
List<X509Certificate> retList = new ArrayList<X509Certificate>();
CertificateFactory cf = CertificateFactory.getInstance("X509");
Collection<? extends Certificate> c =
cf.generateCertificates(is);
ArrayList<Certificate> alCert = (ArrayList<Certificate>)c;
X509Certificate certx509 = (X509Certificate) alCert.get(0);
return certx509;
}
public static List<X509Certificate> loadMultiCertFromFile(String certFilePath)
throws Exception {
InputStream is = null;
List<X509Certificate> retList = new ArrayList<X509Certificate>();
is = new FileInputStream(certFilePath);
CertificateFactory cf = CertificateFactory.getInstance("X509");
Collection<? extends Certificate> c =
cf.generateCertificates(is);
for(Certificate next: c){
retList.add((X509Certificate)next);
}
return retList;
}
public static String conv(byte[] byteArray){
StringBuffer result = new StringBuffer();
for (byte b:byteArray) {
result.append(String.format("%02X", b));
}
return result.toString();
}
public static byte[] convHexToByte(String content) {
byte[] signbyte;
content = content.trim();
String[] signList = splitHex(content);
signbyte = conv(signList);
return signbyte;
}
private static String[] splitHex(String content) {
String[] ret = null;
int len = content.length();
if(len % 2 == 0){
ret = new String[len/2];
for(int i = 0; i < len/2; i++){
ret[i] = content.substring(i*2, (i+1)*2);
}
}
return ret;
}
private static byte[] conv(String[] certList) {
byte[] certbyte = new byte[certList.length];
for (int i = 0; i < certbyte.length; i++) {
certbyte[i] = conv(certList[i]);
}
return certbyte;
}
private static byte conv(String hex) {
int i = Integer.parseInt(hex, 16);
byte c = (byte) i;
return c;
}
public static int hashAlgToId(String hashAlg){
int hashId = 0;
if(hashAlg.compareToIgnoreCase("SHA1")==0){
hashId = ALG_SHA1;
} else if(hashAlg.compareToIgnoreCase("SHA224")==0){
hashId = ALG_SHA224;
} else if(hashAlg.compareToIgnoreCase("SHA256")==0){
hashId = ALG_SHA256;
} else if(hashAlg.compareToIgnoreCase("SHA384")==0){
hashId = ALG_SHA384;
} else if(hashAlg.compareToIgnoreCase("SHA512")==0){
hashId = ALG_SHA512;
}
return hashId;
}
public static X509Certificate createCert(String b64Enc) throws Exception {
ByteArrayInputStream bais = new ByteArrayInputStream(Base64.decode(b64Enc.getBytes()));
CertificateFactory cf = CertificateFactory.getInstance("X509");
Certificate cert =
cf.generateCertificate(bais);
return (X509Certificate) cert;
}
public static X509Certificate createCert(byte [] b) throws Exception {
ByteArrayInputStream bais = new ByteArrayInputStream(b);
CertificateFactory cf = CertificateFactory.getInstance("X509");
Certificate cert =
cf.generateCertificate(bais);
return (X509Certificate) cert;
}
// public static String getHashAlg(int hash) throws Exception{
// String ret = "";
// switch (hash) {
// case ALG_SHA1:
// ret = ID_SHA1;
// break;
//
// case ALG_SHA224:
// ret = ID_SHA1;
// break;
//
// case ALG_SHA256:
// ret = ID_SHA256;
// break;
//
// case ALG_SHA384:
// ret = ID_SHA384;
// break;
//
// case ALG_SHA512:
// ret = ID_SHA512;
// break;
//
// default:
// throw new Exception("hash alg não identificado:" + hash);
//
// }
// return ret;
// }
public static RepoLoader getRepoLoader() {
if(repoLoader == null){
repoLoader = PrefsFactory.getRepoLoader();
}
return repoLoader;
}
// public static List<X509Certificate> listCertFromS3(String string) {
// // TODO Auto-generated method stub
// return null;
// }
// public static X509Certificate loadCertFromS3(String certName) {
// // TODO Auto-generated method stub
// return null;
// }
}
|
0 | java-sources/al/bluecryst/bluecrystal/2.3.4/bluecrystal/service | java-sources/al/bluecryst/bluecrystal/2.3.4/bluecrystal/service/service/ADRBService_23.java | /*
Blue Crystal: Document Digital Signature Tool
Copyright (C) 2007-2015 Sergio Leal
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package bluecrystal.service.service;
import bluecrystal.service.helper.UtilsLocal;
public class ADRBService_23 extends BaseService {
public ADRBService_23() {
super();
minKeyLen = 2048;
signingCertFallback = false;
addChain = false;
signedAttr = true;
// version = 3; // CEF
version = 1;
policyHash = UtilsLocal.convHexToByte(SIG_POLICY_HASH_23);
policyId = SIG_POLICY_BES_ID_23;
policyUri = SIG_POLICY_URI_23;
}
}
|
0 | java-sources/al/bluecryst/bluecrystal/2.3.4/bluecrystal/service | java-sources/al/bluecryst/bluecrystal/2.3.4/bluecrystal/service/service/BaseService.java | /*
Blue Crystal: Document Digital Signature Tool
Copyright (C) 2007-2015 Sergio Leal
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package bluecrystal.service.service;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateEncodingException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.bouncycastle.asn1.ASN1Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import bluecrystal.bcdeps.helper.DerEncoder;
import bluecrystal.bcdeps.helper.PkiOps;
import bluecrystal.domain.AppSignedInfo;
import bluecrystal.domain.AppSignedInfoEx;
import bluecrystal.domain.SignPolicy;
import bluecrystal.service.helper.UtilsLocal;
import bluecrystal.service.helper.UtilsRepo;
public abstract class BaseService implements EnvelopeService {
static final Logger LOG = LoggerFactory.getLogger(BaseService.class);
public BaseService() {
super();
procHash = true;
LOG.debug("Constructed");
}
public boolean isProcHash() {
return procHash;
}
protected static final String SIG_POLICY_URI = "http://politicas.icpbrasil.gov.br/PA_AD_RB.der";
protected static final String SIG_POLICY_BES_ID = "2.16.76.1.7.1.1.1";
protected static final String SIG_POLICY_HASH = "20d6789325513bbc8c29624e1f40b61813ec5ce7";
protected static final String SIG_POLICY_URI_20 = "http://politicas.icpbrasil.gov.br/PA_AD_RB_v2_0.der";
protected static final String SIG_POLICY_BES_ID_20 = "2.16.76.1.7.1.1.2";
protected static final String SIG_POLICY_HASH_20 = "5311e6ce55665c877608"
+ "5ef11c82fa3fb1341cad" + "e7981ed9f51d3e56de5f" + "6aad";
protected static final String SIG_POLICY_URI_21 = "http://politicas.icpbrasil.gov.br/PA_AD_RB_v2_1.der";
protected static final String SIG_POLICY_BES_ID_21 = "2.16.76.1.7.1.1.2.1";
protected static final String SIG_POLICY_HASH_21 = "dd57c98a4313bc1398ce"
+ "6543d3802458957cf716" + "ae3294ec4d8c26251291" + "e6c1";
protected static final String SIG_POLICY_URI_23 = "http://politicas.icpbrasil.gov.br/PA_AD_RB_v2_3.der";
protected static final String SIG_POLICY_BES_ID_23 = "2.16.76.1.7.1.1.2.3";
protected static final String SIG_POLICY_HASH_23 = "b16e88bbf77322a67995b79078778ed3d0ea7c88587b6f6d518b715e8f76a3d5";
protected static final int NDX_SHA1 = 0;
protected static final int NDX_SHA224 = 1;
protected static final int NDX_SHA256 = 2;
protected static final int NDX_SHA384 = 3;
protected static final int NDX_SHA512 = 4;
protected int version;
protected int minKeyLen;
protected boolean signedAttr;
protected boolean signingCertFallback;
protected boolean addChain;
protected boolean procHash;
protected byte[] policyHash;
protected String policyUri;
protected String policyId;
protected static PkiOps pkiOps;
protected static CertificateService certServ;
static {
pkiOps = new PkiOps();
certServ = new CertificateService();
};
protected boolean isSigningCertFallback() {
return signingCertFallback;
}
protected boolean isSignedAttr() {
return signedAttr;
}
public byte[] rebuildEnvelope(byte[] envelopeb64) throws Exception{
throw new UnsupportedOperationException();
}
public byte[] calcSha1(byte[] content) throws NoSuchAlgorithmException {
return pkiOps.calcSha1(content);
}
public byte[] calcSha224(byte[] content) throws NoSuchAlgorithmException {
return pkiOps.calcSha224(content);
}
public byte[] calcSha256(byte[] content) throws NoSuchAlgorithmException {
return pkiOps.calcSha256(content);
}
public byte[] calcSha384(byte[] content) throws NoSuchAlgorithmException {
return pkiOps.calcSha384(content);
}
public byte[] calcSha512(byte[] content) throws NoSuchAlgorithmException {
return pkiOps.calcSha512(content);
}
// public byte[] hashSignedAttribSha1(String certId, byte[] origHash,
// Date signingTime) throws Exception {
// X509Certificate x509 = Utils.loadCertFromS3(certId);
// return hashSignedAttribSha1(origHash, signingTime, x509);
//
// }
public byte[] hashSignedAttribSha1(byte[] origHash, Date signingTime,
X509Certificate x509) throws NoSuchAlgorithmException,
CertificateEncodingException, Exception, IOException {
if (signedAttr) {
DerEncoder derEnc = new DerEncoder();
byte[] certHash = pkiOps.calcSha1(x509.getEncoded());
int idSha = NDX_SHA1;
ASN1Set newSi = siCreate(origHash, signingTime, x509, derEnc,
certHash, idSha);
byte[] saAsBytes = convSiToByte(newSi);
byte[] saAsBytes2 = hackSi(saAsBytes);
return saAsBytes2;
}
return origHash;
}
@Override
public byte[] buildFromS3Sha1(List<AppSignedInfo> listAsi, int attachSize) throws Exception {
int idSha = NDX_SHA1;
List<AppSignedInfoEx> listAsiEx = new ArrayList<AppSignedInfoEx>();
List<X509Certificate> chain = new ArrayList<X509Certificate>();
for (AppSignedInfo appSignedInfo : listAsi) {
// AppSignedInfo appSignedInfo = listAsi.get(0);
X509Certificate x509 = loadCert(appSignedInfo);
chain.addAll(certServ.buildPath(x509));
byte[] certHash = pkiOps.calcSha1(x509.getEncoded());
AppSignedInfoEx asiEx = new AppSignedInfoEx(appSignedInfo, x509,
certHash, idSha);
listAsiEx.add(asiEx);
}
dedup(chain);
byte[] cmsOut = buildBody(chain, listAsiEx, attachSize);
return cmsOut;
}
public byte[] buildCms(List<AppSignedInfoEx> listAsiEx, int attachSize) throws Exception {
LOG.debug("buildCms");
List<X509Certificate> chain = new ArrayList<X509Certificate>();
for (AppSignedInfoEx appSignedInfo : listAsiEx) {
// AppSignedInfo appSignedInfo = listAsi.get(0);
X509Certificate x509 = appSignedInfo.getX509();
// chain.addAll(certServ.buildPath(x509));
chain.addAll(certServ.buildPath(x509));
}
dedup(chain);
for(X509Certificate next : chain){
LOG.debug(next.getSubjectDN().toString());
}
byte[] cmsOut = buildBody(chain, listAsiEx, attachSize);
return cmsOut;
}
public byte[] buildSha256(List<AppSignedInfoEx> listAsiEx, int attachSize) throws Exception {
List<X509Certificate> chain = new ArrayList<X509Certificate>();
for (AppSignedInfoEx appSignedInfo : listAsiEx) {
// AppSignedInfo appSignedInfo = listAsi.get(0);
X509Certificate x509 = appSignedInfo.getX509();
chain.addAll(certServ.buildPath(x509));
byte[] certHash = signingCertFallback ? pkiOps.calcSha1(x509
.getEncoded()) : pkiOps.calcSha256(x509.getEncoded());
}
dedup(chain);
byte[] cmsOut = buildBody(chain, listAsiEx, attachSize);
return cmsOut;
}
private void dedup(List<X509Certificate> list) {
Map<String, X509Certificate> map = new HashMap<String, X509Certificate>();
Iterator<X509Certificate> it = list.iterator();
while (it.hasNext()) {
X509Certificate nextCert = it.next();
map.put(nextCert.getSubjectDN().getName(), nextCert);
}
list.clear();
for(X509Certificate next : map.values()){
list.add(next);
}
}
// public byte[] hashSignedAttribSha224(String certId, byte[] origHash,
// Date signingTime) throws Exception {
// X509Certificate x509 = Utils.loadCertFromRepo(certId);
// return hashSignedAttribSha224(origHash, signingTime, x509);
//
// }
public byte[] hashSignedAttribSha224(byte[] origHash, Date signingTime,
X509Certificate x509) throws NoSuchAlgorithmException,
CertificateEncodingException, Exception, IOException {
if (signedAttr) {
DerEncoder derEnc = new DerEncoder();
byte[] certHash = signingCertFallback ? pkiOps.calcSha1(x509
.getEncoded()) : pkiOps.calcSha224(x509.getEncoded());
int idSha = NDX_SHA224;
ASN1Set newSi = siCreate(origHash, signingTime, x509, derEnc,
certHash, idSha);
byte[] saAsBytes = convSiToByte(newSi);
byte[] saAsBytes2 = hackSi(saAsBytes);
return saAsBytes2;
}
return origHash;
}
// public byte[] buildFromS3Sha224(List<AppSignedInfo> listAsi)
// throws Exception {
// AppSignedInfo appSignedInfo = listAsi.get(0);
// X509Certificate x509 = Utils.loadCertFromRepo(appSignedInfo.getCertId());
// byte[] certHash = signingCertFallback ? pkiOps.calcSha1(x509
// .getEncoded()) : pkiOps.calcSha224(x509.getEncoded());
//
// int idSha = NDX_SHA224;
//
// List<X509Certificate> chain = certServ.buildPath(x509);
//
// AppSignedInfoEx asiEx = new AppSignedInfoEx(appSignedInfo, x509,
// certHash, idSha);
// List<AppSignedInfoEx> listAsiEx = new ArrayList<AppSignedInfoEx>();
// listAsiEx.add(asiEx);
//
// byte[] cmsOut = buildBody(chain, listAsiEx);
// return cmsOut;
// }
public byte[] buildFromS3Sha224(List<AppSignedInfo> listAsi, int attachSize) throws Exception {
int idSha = NDX_SHA224;
List<AppSignedInfoEx> listAsiEx = new ArrayList<AppSignedInfoEx>();
List<X509Certificate> chain = new ArrayList<X509Certificate>();
for (AppSignedInfo appSignedInfo : listAsi) {
// AppSignedInfo appSignedInfo = listAsi.get(0);
X509Certificate x509 = loadCert(appSignedInfo);
chain.addAll(certServ.buildPath(x509));
byte[] certHash = signingCertFallback ? pkiOps.calcSha1(x509
.getEncoded()) : pkiOps.calcSha224(x509.getEncoded());
AppSignedInfoEx asiEx = new AppSignedInfoEx(appSignedInfo, x509,
certHash, idSha);
listAsiEx.add(asiEx);
}
dedup(chain);
byte[] cmsOut = buildBody(chain, listAsiEx, attachSize );
return cmsOut;
}
// public byte[] hashSignedAttribSha256(String certId, byte[] origHash,
// Date signingTime) throws Exception {
// X509Certificate x509 = Utils.loadCertFromS3(certId);
// return hashSignedAttribSha256(origHash, signingTime, x509);
// }
public byte[] hashSignedAttribSha256(byte[] origHash, Date signingTime,
X509Certificate x509) throws NoSuchAlgorithmException,
CertificateEncodingException, Exception, IOException {
if (signedAttr) {
DerEncoder derEnc = new DerEncoder();
byte[] certHash = signingCertFallback ? pkiOps.calcSha1(x509
.getEncoded()) : pkiOps.calcSha256(x509.getEncoded());
int idSha = NDX_SHA256;
ASN1Set newSi = siCreate(origHash, signingTime, x509, derEnc,
certHash, idSha);
byte[] saAsBytes = convSiToByte(newSi);
byte[] saAsBytes2 = hackSi(saAsBytes);
return saAsBytes2;
}
return origHash;
}
// public byte[] buildFromS3Sha256(List<AppSignedInfo> listAsi)
// throws Exception {
// AppSignedInfo appSignedInfo = listAsi.get(0);
// X509Certificate x509 = Utils.loadCertFromS3(appSignedInfo.getCertId());
// byte[] certHash = signingCertFallback ? pkiOps.calcSha1(x509
// .getEncoded()) : pkiOps.calcSha256(x509.getEncoded());
//
// int idSha = NDX_SHA256;
//
// List<X509Certificate> chain = certServ.buildPath(x509);
//
// AppSignedInfoEx asiEx = new AppSignedInfoEx(appSignedInfo, x509,
// certHash, idSha);
// List<AppSignedInfoEx> listAsiEx = new ArrayList<AppSignedInfoEx>();
// listAsiEx.add(asiEx);
//
// byte[] cmsOut = buildBody(chain, listAsiEx);
// return cmsOut;
// }
public byte[] buildFromS3Sha256(List<AppSignedInfo> listAsi, int attachSize) throws Exception {
int idSha = NDX_SHA256;
List<AppSignedInfoEx> listAsiEx = new ArrayList<AppSignedInfoEx>();
List<X509Certificate> chain = new ArrayList<X509Certificate>();
for (AppSignedInfo appSignedInfo : listAsi) {
X509Certificate x509 = loadCert(appSignedInfo);
chain.addAll(certServ.buildPath(x509));
byte[] certHash = signingCertFallback ? pkiOps.calcSha1(x509
.getEncoded()) : pkiOps.calcSha256(x509.getEncoded());
AppSignedInfoEx asiEx = new AppSignedInfoEx(appSignedInfo, x509,
certHash, idSha);
listAsiEx.add(asiEx);
}
dedup(chain);
byte[] cmsOut = buildBody(chain, listAsiEx, attachSize);
return cmsOut;
}
private X509Certificate loadCert(AppSignedInfo appSignedInfo)
throws Exception {
X509Certificate x509;
try {
x509 = UtilsLocal.createCert(UtilsLocal.convHexToByte(appSignedInfo
.getCertId()));
} catch (Exception e) {
x509 = UtilsRepo.loadCertFromRepo(appSignedInfo
.getCertId());
}
return x509;
}
// public byte[] hashSignedAttribSha384(String certId, byte[] origHash,
// Date signingTime) throws Exception {
// X509Certificate x509 = Utils.loadCertFromS3(certId);
// return hashSignedAttribSha384(origHash, signingTime, x509);
//
// }
public byte[] hashSignedAttribSha384(byte[] origHash, Date signingTime,
X509Certificate x509) throws NoSuchAlgorithmException,
CertificateEncodingException, Exception, IOException {
if (signedAttr) {
DerEncoder derEnc = new DerEncoder();
byte[] certHash = signingCertFallback ? pkiOps.calcSha1(x509
.getEncoded()) : pkiOps.calcSha384(x509.getEncoded());
int idSha = NDX_SHA384;
ASN1Set newSi = siCreate(origHash, signingTime, x509, derEnc,
certHash, idSha);
byte[] saAsBytes = convSiToByte(newSi);
byte[] saAsBytes2 = hackSi(saAsBytes);
return saAsBytes2;
}
return origHash;
}
// public byte[] buildFromS3Sha384(List<AppSignedInfo> listAsi)
// throws Exception {
// AppSignedInfo appSignedInfo = listAsi.get(0);
// X509Certificate x509 = Utils.loadCertFromS3(appSignedInfo.getCertId());
// byte[] certHash = signingCertFallback ? pkiOps.calcSha1(x509
// .getEncoded()) : pkiOps.calcSha384(x509.getEncoded());
//
// int idSha = NDX_SHA384;
//
// List<X509Certificate> chain = certServ.buildPath(x509);
//
// AppSignedInfoEx asiEx = new AppSignedInfoEx(appSignedInfo, x509,
// certHash, idSha);
// List<AppSignedInfoEx> listAsiEx = new ArrayList<AppSignedInfoEx>();
// listAsiEx.add(asiEx);
//
// byte[] cmsOut = buildBody(chain, listAsiEx);
// return cmsOut;
// }
public byte[] buildFromS3Sha384(List<AppSignedInfo> listAsi, int attachSize) throws Exception {
int idSha = NDX_SHA384;
List<AppSignedInfoEx> listAsiEx = new ArrayList<AppSignedInfoEx>();
List<X509Certificate> chain = new ArrayList<X509Certificate>();
for (AppSignedInfo appSignedInfo : listAsi) {
// AppSignedInfo appSignedInfo = listAsi.get(0);
X509Certificate x509 = loadCert(appSignedInfo);
chain.addAll(certServ.buildPath(x509));
byte[] certHash = signingCertFallback ? pkiOps.calcSha1(x509
.getEncoded()) : pkiOps.calcSha384(x509.getEncoded());
AppSignedInfoEx asiEx = new AppSignedInfoEx(appSignedInfo, x509,
certHash, idSha);
listAsiEx.add(asiEx);
}
dedup(chain);
byte[] cmsOut = buildBody(chain, listAsiEx, attachSize);
return cmsOut;
}
// public byte[] hashSignedAttribSha512(String certId, byte[] origHash,
// Date signingTime) throws Exception {
// X509Certificate x509 = Utils.loadCertFromS3(certId);
// return hashSignedAttribSha512(origHash, signingTime, x509);
//
// }
public byte[] hashSignedAttribSha512(byte[] origHash, Date signingTime,
X509Certificate x509) throws NoSuchAlgorithmException,
CertificateEncodingException, Exception, IOException {
if (signedAttr) {
DerEncoder derEnc = new DerEncoder();
byte[] certHash = signingCertFallback ? pkiOps.calcSha1(x509
.getEncoded()) : pkiOps.calcSha512(x509.getEncoded());
int idSha = NDX_SHA512;
ASN1Set newSi = siCreate(origHash, signingTime, x509, derEnc,
certHash, idSha);
byte[] saAsBytes = convSiToByte(newSi);
byte[] saAsBytes2 = hackSi(saAsBytes);
return saAsBytes2;
}
return origHash;
}
// public byte[] buildFromS3Sha512(List<AppSignedInfo> listAsi)
// throws Exception {
// AppSignedInfo appSignedInfo = listAsi.get(0);
// X509Certificate x509 = Utils.loadCertFromS3(appSignedInfo.getCertId());
// byte[] certHash = signingCertFallback ? pkiOps.calcSha1(x509
// .getEncoded()) : pkiOps.calcSha512(x509.getEncoded());
//
// int idSha = NDX_SHA512;
//
// List<X509Certificate> chain = certServ.buildPath(x509);
//
// AppSignedInfoEx asiEx = new AppSignedInfoEx(appSignedInfo, x509,
// certHash, idSha);
// List<AppSignedInfoEx> listAsiEx = new ArrayList<AppSignedInfoEx>();
// listAsiEx.add(asiEx);
//
// byte[] cmsOut = buildBody(chain, listAsiEx);
// return cmsOut;
// }
public byte[] buildFromS3Sha512(List<AppSignedInfo> listAsi, int attachSize) throws Exception {
int idSha = NDX_SHA512;
List<AppSignedInfoEx> listAsiEx = new ArrayList<AppSignedInfoEx>();
List<X509Certificate> chain = new ArrayList<X509Certificate>();
for (AppSignedInfo appSignedInfo : listAsi) {
// AppSignedInfo appSignedInfo = listAsi.get(0);
X509Certificate x509 = loadCert(appSignedInfo);
chain.addAll(certServ.buildPath(x509));
byte[] certHash = signingCertFallback ? pkiOps.calcSha1(x509
.getEncoded()) : pkiOps.calcSha512(x509.getEncoded());
AppSignedInfoEx asiEx = new AppSignedInfoEx(appSignedInfo, x509,
certHash, idSha);
listAsiEx.add(asiEx);
}
dedup(chain);
byte[] cmsOut = buildBody(chain, listAsiEx, attachSize);
return cmsOut;
}
// TODO
// MOVER DER ENCODER :)
private byte[] hackSi(byte[] saAsBytes) throws IOException {
// LOG.debug(Utils.conv(saAsBytes));
byte[] saAsBytes2 = new byte[saAsBytes.length - 4];
saAsBytes2[0] = saAsBytes[0];
saAsBytes2[1] = saAsBytes[1];
for (int i = 2; i < saAsBytes2.length; i++) {
saAsBytes2[i] = saAsBytes[i + 4];
}
// LOG.debug(Utils.conv(saAsBytes2));
return saAsBytes2;
}
public ASN1Set siCreate(byte[] origHash, Date signingTime,
X509Certificate x509, DerEncoder derEnc, byte[] certHash, int idSha)
throws Exception {
return derEnc.siCreateDerEncSignedADRB(origHash, policyHash, certHash,
x509, signingTime, idSha, policyUri, policyId,
signingCertFallback);
}
private byte[] buildBody(List<X509Certificate> chain,
List<AppSignedInfoEx> listAsiEx, int attachSize) throws Exception {
byte[] cmsOut = null;
DerEncoder de = new DerEncoder();
SignPolicy signPol = new SignPolicy(policyHash, policyUri, policyId);
if (signedAttr) {
cmsOut = de.buildADRBBody(listAsiEx, signPol, addChain ? chain
: null, version, signingCertFallback, attachSize);
} else {
AppSignedInfoEx asiEx = listAsiEx.get(0);
cmsOut = de.buildCmsBody(asiEx.getSignedHash(), asiEx.getX509(),
addChain ? chain : null, asiEx.getIdSha(), version, attachSize);
}
return cmsOut;
}
private static byte[] convSiToByte(ASN1Set newSi) throws IOException {
return DerEncoder.convSiToByte(newSi);
}
}
|
0 | java-sources/al/bluecryst/bluecrystal/2.3.4/bluecrystal/service | java-sources/al/bluecryst/bluecrystal/2.3.4/bluecrystal/service/service/CertificateService.java | /*
Blue Crystal: Document Digital Signature Tool
Copyright (C) 2007-2015 Sergio Leal
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package bluecrystal.service.service;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.security.InvalidAlgorithmParameterException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.Security;
import java.security.cert.CRLException;
import java.security.cert.CertPath;
import java.security.cert.CertPathValidator;
import java.security.cert.CertPathValidatorException;
import java.security.cert.CertPathValidatorResult;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.CertificateParsingException;
import java.security.cert.PKIXCertPathValidatorResult;
import java.security.cert.PKIXParameters;
import java.security.cert.TrustAnchor;
import java.security.cert.X509Certificate;
import java.security.interfaces.RSAKey;
import java.security.interfaces.RSAPublicKey;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.bouncycastle.util.encoders.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import bluecrystal.bcdeps.helper.DerEncoder;
import bluecrystal.bcdeps.helper.PkiOps;
import bluecrystal.domain.CertConstants;
import bluecrystal.domain.CiKeyUsage;
import bluecrystal.domain.OperationStatus;
import bluecrystal.domain.StatusConst;
import bluecrystal.service.exception.EmptyCertPathException;
import bluecrystal.service.exception.NotAfterException;
import bluecrystal.service.exception.NotBeforeException;
import bluecrystal.service.exception.RevokedException;
import bluecrystal.service.exception.UndefStateException;
import bluecrystal.service.helper.UtilsLocal;
import bluecrystal.service.helper.UtilsRepo;
import bluecrystal.service.loader.LCRLoader;
import bluecrystal.service.loader.LCRLoaderImpl;
import bluecrystal.service.util.PrefsFactory;
import bluecrystal.service.validator.CrlValidatorImpl;
import bluecrystal.service.validator.OcspValidatorImpl;
import bluecrystal.service.validator.StatusValidator;
import bluecrystal.service.validator.StatusValidatorImpl;
public class CertificateService {
static final Logger logger = LoggerFactory.getLogger(CertificateService.class);
private static LCRLoader lcrLoader;
static {
lcrLoader = PrefsFactory.getLCRLoader();
}
// private static String loaderType = Messages.getString("LCRLoader.loaderType");
//
// static {
// try {
// lcrLoader = (LCRLoader) Class
// .forName(loaderType)
// .newInstance();
//// if(repoLoader==null){
//// LOG.error("Could not load Repoloader ");
//// }
// } catch (Exception e) {
//// LOG.error("Could not load Repoloader ", e);
// e.printStackTrace();
// }
// }
private static final String ICP_BRASIL_PF = "ICP-Brasil PF";
private static final String ICP_BRASIL_PJ = "ICP-Brasil PJ";
private static final String CERT_TYPE_FMT = "cert_type%d";
private static final String CNPJ_OID = "2.16.76.1.3.3";
private static final String ICP_BRASIL_PC_PREFIX_OID = "2.16.76.1.2";
private static final String EKU_OCSP_SIGN_OID = "1.3.6.1.5.5.7.3.9";
private static final String EKU_TIMESTAMP_OID = "1.3.6.1.5.5.7.3.8";
private static final String EKU_IPSEC_USER_OID = "1.3.6.1.5.5.7.3.7";
private static final String EKU_IPSEC_TUNNEL_OID = "1.3.6.1.5.5.7.3.6";
private static final String EKU_IPSEC_END_OID = "1.3.6.1.5.5.7.3.5";
private static final String EKU_EMAIL_PROT_OID = "1.3.6.1.5.5.7.3.4";
private static final String EKU_CODE_SIGN_OID = "1.3.6.1.5.5.7.3.3";
private static final String EKU_CLIENT_AUTH_OID = "1.3.6.1.5.5.7.3.2";
private static final String EKU_SERVER_AUTH_OID = "1.3.6.1.5.5.7.3.1";
private static final String UPN = "1.3.6.1.4.1.311.20.2.3";
private static final String PROFESSIONAL_OID = "2.16.76.1.4.";
private static final String OAB_OID = "2.16.76.1.4.2.1.1";
private static final String PJ_PF_INSS_OID = "2.16.76.1.3.7";
private static final String PERSON_NAME_OID = "2.16.76.1.3.2";
private static final String PF_PF_INSS_OID = "2.16.76.1.3.6";
private static final String ELEITOR_OID = "2.16.76.1.3.5";
private static final String PJ_PF_ID = "2.16.76.1.3.4";
// PF 2.16.76.1.3.1 - Data Nascimento(8) , CPF(11), NIS (PIS, PASEP ou CI)
// (11), RG (15), orgão e UF (6).
private static final String PF_PF_ID = "2.16.76.1.3.1";
private static final int BIRTH_DATE_INI = 0;
private static final int BIRTH_DATE_LEN = 8;
private static final int CPF_INI = BIRTH_DATE_LEN;
private static final int CPF_LEN = CPF_INI + 11;
private static final int PIS_INI = CPF_LEN;
private static final int PIS_LEN = PIS_INI + 11;
private static final int RG_INI = PIS_LEN;
private static final int RG_LEN = RG_INI + 15;
private static final int RG_ORG_UF_INI = RG_LEN;
private static final int RG_ORG_UF_LEN = RG_ORG_UF_INI + 6;
private static final int RG_UF_LEN = 2;
// PF 2.16.76.1.3.5 - Titulo de eleitor(12), Zona Eleitoral (3), Seção (4)
private static final int ELEITOR_INI = 0;
private static final int ELEITOR_LEN = 12;
private static final int ZONA_INI = ELEITOR_LEN;
private static final int ZONA_LEN = 3;
private static final int SECAO_INI = ZONA_INI + ZONA_LEN;
private static final int SECAO_LEN = 4;
// PJ 2.16.76.1.3.7 - INSS (12)
private static final int INSS_INI = 0;
private static final int INSS_LEN = 12;
// 2.16.76.1.4.2.1.1- = nas primeiras 07 (sete) posições os dígitos
// alfanuméricos do Número de Inscrição junto a Seccional, e nas 2 (duas)
// posições subseqüentes a sigla do Estado da Seccional.
// private static final int OAB_REG_INI = 0;
// private static final int OAB_REG_LEN = 12;
// private static final int OAB_UF_INI = OAB_REG_LEN;
// private static final int OAB_UF_LEN = 3;
private static final int SAN_OTHER_NAME = 0;
private static final int SAN_EMAIL = 1;
private static final String AKI_OID = "2.5.29.35";
// private static final String BASIC_CONSTRAINTS = "2.5.29.19";
// private static final String CERT_POL_QUALIFIER = "certPolQualifier%d";
// private static final String CERT_POL_OID = "certPolOid%d";
private static final String CERT_POLICIES = "2.5.29.32";
private static final String CRL_DIST_POINT = "2.5.29.31";
public static final String OCSP = "1.3.6.1.5.5.7.48.1";
private static final String CA_ISSUERS = "1.3.6.1.5.5.7.48.2";
private static final String AUTHORITY_INFO_ACCESS = "1.3.6.1.5.5.7.1.1";
private static final String NON_REPUDIATION = "nonRepudiation";
private static final String KEY_ENCIPHERMENT = "keyEncipherment";
private static final String KEY_CERT_SIGN = "keyCertSign";
private static final String KEY_AGREEMENT = "keyAgreement";
private static final String ENCIPHER_ONLY = "encipherOnly";
private static final String DECIPHER_ONLY = "decipherOnly";
private static final String DATA_ENCIPHERMENT = "dataEncipherment";
private static final String CRL_SIGN = "cRLSign";
private static final String LIST_FORMAT = "%s,";
private static final String DIGITAL_SIGNATURE = "digitalSignature";
private List<X509Certificate> intermCa;
private List<X509Certificate> trustAnchor;
Map<String, X509Certificate> mapInterm = null;
Map<String, X509Certificate> mapAnchor = null;
StatusValidator statusValidator;
boolean enforceKu;
int minKeyLen = 2048;
private String[] ignore = { "2.5.29.15", // key usage
"2.5.29.37", // extende key usage
"2.5.29.19", // basic constraints
"2.5.29.17" // san
};
// 5.2.3.1.1.2 Tamanho Mínimo de Chave
// O tamanho mínimo de chaves para criação de assinaturas segundo esta PA é
// de :
// a) para a versão 1.0: 1024 bits;
// b) para a versão 1.1: 1024 bits;
// b) para as versões 2.0 e 2.1: 2048 bits.
public CertificateService() {
super();
OcspValidatorImpl ocspValidator = new OcspValidatorImpl();
lcrLoader = new LCRLoaderImpl();
CrlValidatorImpl crlValidator = new CrlValidatorImpl(lcrLoader);
statusValidator = new StatusValidatorImpl(crlValidator, ocspValidator);
statusValidator.setUseOcsp(PrefsFactory.getUseOCSP());
org.bouncycastle.jce.provider.BouncyCastleProvider provider = new org.bouncycastle.jce.provider.BouncyCastleProvider();
Security.addProvider(provider);
enforceKu = false;
minKeyLen = 2048;
}
public X509Certificate createFromB64(byte[] certB64)
throws CertificateException {
ByteArrayInputStream is = new ByteArrayInputStream(certB64);
CertificateFactory cf = CertificateFactory.getInstance("X509");
Certificate c = cf.generateCertificate(is);
return (X509Certificate) c;
}
public List<X509Certificate> getIntermCaList() throws Exception {
if (intermCa == null) {
intermCa = UtilsRepo.listCertFromRepo("interm");
mapInterm = buildMap(intermCa);
}
return intermCa;
}
public List<X509Certificate> getTrustAnchorList() throws Exception {
if (trustAnchor == null) {
trustAnchor = UtilsRepo.listCertFromRepo("root");
mapAnchor = buildMap(trustAnchor);
}
return trustAnchor;
}
// public CertStatus isValidForSign(String certName, Date refDate)
// throws Exception {
// X509Certificate cert = Utils.loadCertFromS3(certName);
// return isValidForSign(refDate, cert);
//
// }
public OperationStatus isValidForSign(Date refDate, X509Certificate cert)
throws Exception, IOException, CertificateException, CRLException,
UndefStateException, RevokedException {
RSAKey rsaKey = (RSAKey) (cert.getPublicKey());
int keySize = rsaKey.getModulus().bitLength();
if (!forSign(cert) || keySize < minKeyLen) {
return new OperationStatus(StatusConst.UNSABLEKEY, null);
}
return isValid(refDate, cert);
}
public Map<String, String> parseChainAsMap(List<X509Certificate> chain) {
Map<String, String> ret = new HashMap<String, String>();
int i = 0;
for (X509Certificate next : chain) {
loggerTrace("CERT:" + next.getSubjectDN().getName());
try {
String name = "";
String value = "";
value = createThumbprintsha256(next.getEncoded());
name = String.format(CertConstants.THUMBPRINT_SHA256_D, i);
ret.put(name, value);
value = next.getSubjectDN().getName();
name = String.format(CertConstants.SUBJECT_D, i);
ret.put(name, value);
value = next.getIssuerDN().getName();
name = String.format(CertConstants.ISSUER_D, i);
ret.put(name, value);
value = String.valueOf(next.getNotAfter().getTime());
name = String.format(CertConstants.NOT_AFTER_D, i);
ret.put(name, value);
value = String.valueOf(next.getNotBefore().getTime());
name = String.format(CertConstants.NOT_BEFORE_D, i);
ret.put(name, value);
value = String.valueOf(next.getVersion());
name = String.format(CertConstants.VERSION_D, i);
ret.put(name, value);
value = String.valueOf(calcCertSha256(next));
name = String.format(CertConstants.CERT_SHA256_D, i);
ret.put(name, value);
value = next.getSerialNumber().toString();
name = String.format(CertConstants.SERIAL_D, i);
ret.put(name, value);
PublicKey pubKey = next.getPublicKey();
RSAPublicKey rsaPubKey = (RSAPublicKey) pubKey;
value = String.valueOf(rsaPubKey.getModulus().bitLength());
name = String.format(CertConstants.KEY_LENGTH_D, i);
ret.put(name, value);
int basicConstraint = next.getBasicConstraints();
value = String.valueOf(basicConstraint);
name = String.format(CertConstants.BASIC_CONSTRAINT_D, i);
ret.put(name, value);
// GeneralName ::= CHOICE {
// otherName [0] OtherName,
// rfc822Name [1] IA5String,
// dNSName [2] IA5String,
// x400Address [3] ORAddress,
// directoryName [4] Name,
// ediPartyName [5] EDIPartyName,
// uniformResourceIdentifier [6] IA5String,
// iPAddress [7] OCTET STRING,
// registeredID [8] OBJECT IDENTIFIER }
value = "standard";
name = String.format(CERT_TYPE_FMT, i);
ret.put(name, value);
Collection<List<?>> sanList = next.getSubjectAlternativeNames();
if (sanList != null) {
for (List<?> nextSan : sanList) {
try {
Integer san1 = (Integer) nextSan.get(0);
Object san2 = nextSan.get(1);
if (san1 == SAN_OTHER_NAME) {
if (san2 instanceof String) {
logger.error("UNSUPORTED OTHERNAME SAN FORMAT");
} else {
Map<String, String> otherNameMap = createSanMap(
(byte[]) san2, i);
ret.putAll(otherNameMap);
}
} else if (san1 == SAN_EMAIL) {
if (san2 instanceof String) {
name = String.format(
CertConstants.SAN_EMAIL_D, i);
ret.put(name, (String) san2);
} else {
logger.error("UNSUPORTED EMAIL SAN FORMAT");
}
} else {
logger.error("UNSUPORTED SAN");
}
} catch (Exception e) {
logger.error("Erroe decoding SAN", e);
}
}
}
List<String> extKU = next.getExtendedKeyUsage();
StringBuffer finalEKU = new StringBuffer();
if (extKU != null) {
for (String nextEKU : extKU) {
String translEKU = translateEKU(nextEKU);
finalEKU.append(String.format(LIST_FORMAT, translEKU));
}
value = finalEKU.substring(0, finalEKU.length() - 2); // remove
// last
// SPACE
// +
// comma
name = String.format(CertConstants.EKU_D, i);
ret.put(name, value);
}
StringBuffer finalKU = new StringBuffer();
boolean[] ku = next.getKeyUsage();
if (ku != null) {
finalKU.append(ku[CiKeyUsage.cRLSign] ? String.format(
LIST_FORMAT, CRL_SIGN) : "");
finalKU.append(ku[CiKeyUsage.dataEncipherment] ? String
.format(LIST_FORMAT, DATA_ENCIPHERMENT) : "");
finalKU.append(ku[CiKeyUsage.decipherOnly] ? String.format(
LIST_FORMAT, DECIPHER_ONLY) : "");
finalKU.append(ku[CiKeyUsage.digitalSignature] ? String
.format(LIST_FORMAT, DIGITAL_SIGNATURE) : "");
finalKU.append(ku[CiKeyUsage.encipherOnly] ? String.format(
LIST_FORMAT, ENCIPHER_ONLY) : "");
finalKU.append(ku[CiKeyUsage.keyAgreement] ? String.format(
LIST_FORMAT, KEY_AGREEMENT) : "");
finalKU.append(ku[CiKeyUsage.keyCertSign] ? String.format(
LIST_FORMAT, KEY_CERT_SIGN) : "");
finalKU.append(ku[CiKeyUsage.keyEncipherment] ? String
.format(LIST_FORMAT, KEY_ENCIPHERMENT) : "");
finalKU.append(ku[CiKeyUsage.nonRepudiation] ? String
.format(LIST_FORMAT, NON_REPUDIATION) : "");
value = finalKU.substring(0, finalKU.length() - 1); // remove
// last
} // comma
name = String.format(CertConstants.KU_D, i);
ret.put(name, value);
loggerTrace("** getCriticalExtensionOIDs");
Set<String> critOIDs = next.getCriticalExtensionOIDs();
if (critOIDs != null) {
for (String critOID : critOIDs) {
loggerTrace(String.format("%s -> %s", critOID,
next.getExtensionValue(critOID)));
if (!shouldIgnore(critOID)) {
loggerTrace(" + no extension beeing processed.");
} else {
loggerTrace(String.format("IGNORE: %s", critOID));
}
}
}
loggerTrace("** getNonCriticalExtensionOIDs");
Set<String> nonCritOIDs = next.getNonCriticalExtensionOIDs();
if (nonCritOIDs != null) {
for (String nonCritOID : nonCritOIDs) {
loggerTrace(String.format("%s -> %s", nonCritOID,
new String(next.getExtensionValue(nonCritOID))));
if (!shouldIgnore(nonCritOID)) {
loggerTrace("+ no extension beeing processed.");
Map<String, String> extensionMap = processExtension(
nonCritOID,
next.getExtensionValue(nonCritOID), i);
ret.putAll(extensionMap);
} else {
loggerTrace(String.format("IGNORE: %s", nonCritOID));
}
}
}
} catch (Exception e) {
logger.error("Error decoding X.509 field or exception", e);
}
i++;
}
return ret;
}
private String createThumbprintsha256(byte[] encoded) throws NoSuchAlgorithmException {
MessageDigest hashSum = MessageDigest.getInstance("SHA-256");
// logger.debug("Validar assinatura SHA-256");
hashSum.update(encoded);
byte[] digestResult = hashSum.digest();
String digestB64 = new String(Base64.encode(digestResult));
return digestB64;
}
private String calcCertSha256(X509Certificate next) {
String ret = "";
PkiOps pki = new PkiOps();
String certSha256;
try {
ret = UtilsLocal.conv(pki.calcSha256(next.getEncoded()));
} catch (Exception e) {
logger.error("Error calculating cert sha256 ", e);
}
return ret;
}
private String translateEKU(String nextEKU) {
String ret = "";
if (nextEKU.compareTo(EKU_OCSP_SIGN_OID) == 0) {
ret = "ekuOcspSign";
} else if (nextEKU.compareTo(EKU_TIMESTAMP_OID) == 0) {
ret = "ekuTimeStamp";
} else if (nextEKU.compareTo(EKU_IPSEC_USER_OID) == 0) {
ret = "ekuIpSecUser";
} else if (nextEKU.compareTo(EKU_IPSEC_TUNNEL_OID) == 0) {
ret = "ekuIpSecTunnel";
} else if (nextEKU.compareTo(EKU_IPSEC_END_OID) == 0) {
ret = "ekuIpSecEnd";
} else if (nextEKU.compareTo(EKU_EMAIL_PROT_OID) == 0) {
ret = "ekuEmailProt";
} else if (nextEKU.compareTo(EKU_CODE_SIGN_OID) == 0) {
ret = "ekuCodeSgin";
} else if (nextEKU.compareTo(EKU_CLIENT_AUTH_OID) == 0) {
ret = "ekuClientAuth";
} else if (nextEKU.compareTo(EKU_SERVER_AUTH_OID) == 0) {
ret = "ekuServerAuth";
}
return ret;
}
private Map<String, String> createSanMap(byte[] extensionValue, int index) {
return DerEncoder.createSanMap(extensionValue, index);
}
private Map<String, String> processExtension(String nonCritOID,
byte[] extensionValue, int index) {
Map<String, String> nvPair = new HashMap<String, String>();
try {
if (nonCritOID.compareTo(AUTHORITY_INFO_ACCESS) == 0) {
Map<String, String> aia = getAIAComplete(extensionValue);
nvPair.putAll(convertAiaOid(aia, index));
} else if (nonCritOID.compareTo(CRL_DIST_POINT) == 0) {
List<String> crlDP = getCrlDistributionPoints(extensionValue);
StringBuffer finalCDP = new StringBuffer();
for (String nextCDP : crlDP) {
finalCDP.append(String.format(LIST_FORMAT, nextCDP));
}
nvPair.put(String.format(CertConstants.CRL_DP, index),
finalCDP.substring(0, finalCDP.length() - 1));
} else if (nonCritOID.compareTo(CERT_POLICIES) == 0) {
Map<String, String> certPol = getCertPolicies(extensionValue,
index);
nvPair.putAll(certPol);
} else if (nonCritOID.compareTo(AKI_OID) == 0) {
byte[] aki = getAKI(extensionValue, index);
nvPair.put(String.format(CertConstants.AKI_FMT, index),
UtilsLocal.conv(aki));
}
} catch (Exception e) {
logger.error("Error processing extension " + nonCritOID, e);
}
return nvPair;
}
private byte[] getAKI(byte[] extensionValue, int index) {
return DerEncoder.getAKI(extensionValue, index);
}
private Map<String, String> convertAiaOid(Map<String, String> aia, int index) {
Map<String, String> nvPair = new HashMap<String, String>();
for (String next : aia.keySet()) {
if (next.compareTo(OCSP) == 0) {
nvPair.put(String.format(CertConstants.OCSP_STR, index),
aia.get(OCSP));
} else if (next.compareTo(CA_ISSUERS) == 0) {
nvPair.put(String.format(CertConstants.CA_ISSUERS_STR, index),
aia.get(CA_ISSUERS));
}
}
return nvPair;
}
private boolean shouldIgnore(String critOID) {
boolean ret = false;
for (String nextIgnore : ignore) {
if (nextIgnore.compareTo(critOID) == 0) {
ret = true;
break;
}
}
return ret;
}
private boolean forSign(X509Certificate cert) {
// KeyUsage ::= BIT STRING {
// digitalSignature (0),
// nonRepudiation (1),
// keyEncipherment (2),
// dataEncipherment (3),
// keyAgreement (4),
// keyCertSign (5),
// cRLSign (6),
// encipherOnly (7),
// decipherOnly (8) }
// The digitalSignature bit is asserted when the subject public key
// is used for verifying digital signatures, other than signatures on
// certificates (bit 5) and CRLs (bit 6), such as those used in an
// entity authentication service, a data origin authentication
// service, and/or an integrity service.
// The nonRepudiation bit is asserted when the subject public key is
// used to verify digital signatures, other than signatures on
// certificates (bit 5) and CRLs (bit 6), used to provide a non-
// repudiation service that protects against the signing entity
// falsely denying some action. In the case of later conflict, a
// reliable third party may determine the authenticity of the signed
// data. (Note that recent editions of X.509 have renamed the
// nonRepudiation bit to contentCommitment.)
boolean[] ku = cert.getKeyUsage();
return enforceKu ? ku[CiKeyUsage.digitalSignature]
&& ku[CiKeyUsage.nonRepudiation]
: ku[CiKeyUsage.digitalSignature]
|| ku[CiKeyUsage.nonRepudiation];
}
public OperationStatus isValid(Date refDate, X509Certificate cert)
throws Exception, IOException, CertificateException, CRLException,
UndefStateException, RevokedException {
return isValid(refDate, cert, true);
}
public OperationStatus isValid(Date refDate, X509Certificate cert,
boolean verifyRevoke) throws Exception, IOException,
CertificateException, CRLException, UndefStateException,
RevokedException {
OperationStatus ret = new OperationStatus(StatusConst.UNKNOWN, null);
logger.debug("Status inicial: "+StatusConst.UNKNOWN);
List<X509Certificate> certsOnPath = buildPath(cert);
if (certsOnPath != null) {
try {
verificaCertPath(certsOnPath, refDate);
if (verifyRevoke) {
ret = statusValidator.verifyStatusEE(certsOnPath, refDate,
this.getCrlDistributionPoints(cert));
}
} catch (Exception e) {
ret = new OperationStatus(StatusConst.UNTRUSTED, null, e);
}
} else {
logger.error("** ERROR:certsOnPath == null " + new Date());
ret = new OperationStatus(StatusConst.UNTRUSTED, null, new EmptyCertPathException());
}
logger.debug("Status retornado: "+ret);
return ret;
}
public List<X509Certificate> buildPath(X509Certificate signerCert)
throws Exception {
return buildPath(signerCert, getIntermCaList(), getTrustAnchorList());
}
public List<X509Certificate> decode(byte[] encoded)
throws CertificateException, IOException, CRLException {
List<X509Certificate> certs = new ArrayList<X509Certificate>();
try {
List<byte[]> bList = DerEncoder.extractCertList(encoded);
for (byte[] b : bList) {
// saveToFile(b);
InputStream inStream = new ByteArrayInputStream(b);
CertificateFactory cf = CertificateFactory.getInstance("X.509"); //$NON-NLS-1$
List<X509Certificate> certsTemp = (List<X509Certificate>) cf
.generateCertificates(inStream);
certs.addAll(certsTemp);
inStream.close();
}
} catch (Exception e) {
logger.error("Error decoding X.509 cert from bytes ", e);
}
return certs;
}
public X509Certificate decodeEE(byte[] encoded)
throws CertificateException, IOException, CRLException {
List<X509Certificate> ret = decode(encoded);
for (X509Certificate next : ret) {
if (isEE(next)) {
return next;
}
}
return null;
}
private static boolean isEE(X509Certificate nextCert) {
return nextCert.getBasicConstraints() == -1;
}
private static List<X509Certificate> buildPath(X509Certificate signer,
Collection<X509Certificate> intermCa,
Collection<X509Certificate> trustAnchor) throws Exception {
List<X509Certificate> certsOnPath = new ArrayList<X509Certificate>();
loggerTrace("****** Signer Issuer");
loggerTrace(signer.getIssuerDN().getName());
//
loggerTrace("****** intermCa");
Map<String, X509Certificate> mapInterm = buildMap(intermCa);
loggerTrace("****** rootCa");
Map<String, X509Certificate> mapAnchor = buildMap(trustAnchor);
certsOnPath.add(signer);
X509Certificate nextCert = signer;
while (mapInterm.containsKey((String) nextCert.getIssuerDN().getName())) {
certsOnPath.add(mapInterm.get((String) nextCert.getIssuerDN()
.getName()));
nextCert = mapInterm.get((String) nextCert.getIssuerDN().getName());
}
if (mapAnchor.containsKey((String) nextCert.getIssuerDN().getName())) {
certsOnPath.add(mapAnchor.get((String) nextCert.getIssuerDN()
.getName()));
} else {
List<X509Certificate> aiaPath = buildPathUsingAIA(signer);
Map<String, X509Certificate> mapAiaInterm = buildMap(aiaPath);
nextCert = signer;
while (mapAiaInterm.containsKey((String) nextCert.getIssuerDN()
.getName())) {
certsOnPath.add(mapAiaInterm.get((String) nextCert
.getIssuerDN().getName()));
nextCert = mapAiaInterm.get((String) nextCert.getIssuerDN()
.getName());
}
if (mapAnchor
.containsKey((String) nextCert.getIssuerDN().getName())) {
certsOnPath.add(mapAnchor.get((String) nextCert.getIssuerDN()
.getName()));
}
}
return certsOnPath;
}
public static List<X509Certificate> buildPathUsingAIA(X509Certificate signer)
throws Exception {
List<X509Certificate> certsInterm = new ArrayList<X509Certificate>();
String aiaUrlStr = getAIA(signer);
if (aiaUrlStr != null) {
List<X509Certificate> certs = loadCerts(new URL(aiaUrlStr));
for (X509Certificate nextCert : certs) {
if (!isRoot(nextCert)) {
certsInterm.add(nextCert);
}
}
}
return certsInterm;
}
public static boolean isRoot(X509Certificate cert) {
String subj = cert.getSubjectDN().toString();
String issuer = cert.getIssuerDN().toString();
return subj.compareTo(issuer) == 0;
}
private static List<X509Certificate> loadCerts(URL url) throws Exception {
InputStream is = url.openStream();
List<X509Certificate> retList = new ArrayList<X509Certificate>();
CertificateFactory cf = CertificateFactory.getInstance("X509");
Collection<? extends Certificate> c = cf.generateCertificates(is);
for (Certificate next : c) {
retList.add((X509Certificate) next);
}
return retList;
}
private static Map<String, X509Certificate> buildMap(
Collection<X509Certificate> list) {
Map<String, X509Certificate> map = new HashMap<String, X509Certificate>();
Iterator<X509Certificate> it = list.iterator();
while (it.hasNext()) {
X509Certificate nextCert = it.next();
loggerTrace(nextCert.getSubjectDN().getName());
map.put(nextCert.getSubjectDN().getName(), nextCert);
}
return map;
}
private static void loggerTrace(String name) {
// logger.trace(name);
}
private void verificaCertPath(Collection<X509Certificate> certsOnPath,
Date dtData) throws Exception {
CertPath certPath = createCertPathToValidate(certsOnPath);
PKIXParameters params = null;
params = createPKIXParms(trustAnchor, dtData);
// Validate expirations dates to produce a more detailed error result
for (Certificate cert : certPath.getCertificates()) {
if (cert instanceof X509Certificate) {
X509Certificate x509 = (X509Certificate) cert;
if (dtData.before(x509.getNotBefore()))
throw new NotBeforeException(x509, x509.getNotBefore());
if (dtData.after(x509.getNotAfter()))
throw new NotAfterException(x509, x509.getNotAfter());
}
}
params.setRevocationEnabled(false);
if (certPathReview(certPath, params) == null) {
throw new RuntimeException(""); //$NON-NLS-1$
}
}
private PKIXCertPathValidatorResult certPathReview(CertPath certPath,
PKIXParameters params) throws NoSuchAlgorithmException,
CertPathValidatorException, InvalidAlgorithmParameterException {
CertPathValidator certPathValidator = CertPathValidator
.getInstance(CertPathValidator.getDefaultType());
CertPathValidatorResult result = certPathValidator.validate(certPath,
params);
PKIXCertPathValidatorResult pkixResult = (PKIXCertPathValidatorResult) result;
return pkixResult;
}
private PKIXParameters createPKIXParms(
Collection<X509Certificate> trustAnchorColl, Date dtDate)
throws InvalidAlgorithmParameterException {
// TODO Auto-generated method stub
Set tmpTA = new HashSet();
Iterator<X509Certificate> itLast = trustAnchorColl.iterator();
while (itLast.hasNext()) {
X509Certificate certOnPath = itLast.next();
TrustAnchor trustAnchor = new TrustAnchor(certOnPath, null);
tmpTA.add(trustAnchor);
}
PKIXParameters params = new PKIXParameters(tmpTA);
params.setDate(dtDate);
return params;
}
private CertPath createCertPathToValidate(
Collection<X509Certificate> certsOnPath)
throws CertificateException {
X509Certificate[] certPathToValidate = null;
certPathToValidate = new X509Certificate[certsOnPath.size()];
Iterator<X509Certificate> itLast = certsOnPath.iterator();
int cnt = 0;
while (itLast.hasNext()) {
X509Certificate certOnPath = itLast.next();
certPathToValidate[cnt] = certOnPath;
cnt++;
}
CertificateFactory certFact = CertificateFactory.getInstance("X.509"); //$NON-NLS-1$
CertPath path = certFact.generateCertPath(Arrays
.asList(certPathToValidate));
return path;
}
public static String getAIA(X509Certificate cert)
throws UnsupportedEncodingException {
String ret = null;
byte[] ext = cert.getExtensionValue(AUTHORITY_INFO_ACCESS);
Map<String, String> aia = getAIAComplete(ext);
if (aia != null) {
ret = aia.get(CA_ISSUERS);
}
return ret;
}
public static Map<String, String> getAIAComplete(byte[] ext)
throws UnsupportedEncodingException {
return DerEncoder.getAIAComplete(ext);
}
public static List<String> getCrlDistributionPoints(X509Certificate cert)
throws CertificateParsingException, IOException {
// String extOid = X509Extensions.CRLDistributionPoints.getId();
String extOid = "2.5.29.31";
byte[] crldpExt = cert.getExtensionValue(extOid);
return getCrlDistributionPoints(crldpExt);
}
public static List<String> getCrlDistributionPoints(byte[] crldpExt)
throws CertificateParsingException, IOException {
return DerEncoder.getCrlDistributionPoints(crldpExt);
}
public static Map<String, String> getCertPolicies(byte[] certPols, int index)
throws CertificateParsingException, IOException {
return DerEncoder.getCertPolicies(certPols, index);
}
// 2.16.76.1.2.1.n Identificação de campos associados a Políticas de
// Certificados
// do tipo A1
// 2.16.76.1.2.2.n Identificação de campos associados a Políticas de
// Certificados c e r t i s i g n . c o m . b r
// do tipo A2
// 2.16.76.1.2.3.n Identificação de campos associados a Políticas de
// Certificados
// do tipo A3
// 2.16.76.1.2.4.n Identificação de campos associados a Políticas de
// Certificados
// do tipo A4
// 2.16.76.1.2.101.n Identificação de campos associados a Políticas de
// Certificados
// do tipo S1
// 2.16.76.1.2 2.16.76.1.2....102.n... Identificação de campos associados a
// Políticas de Certificados
// do tipo 2
// 2.16.76.1.2 2.16.76.1.2....103.n... Identificação de campos associados a
// Políticas de Certificados
// do tipo S3
// 2.16.76.1.2 2.16.76.1.2....104.n... Identificação de campos associados a
// Políticas de Certificados
// do tipo S4
private static String getCertUsage(String pcOid) {
String ret = "";
if (pcOid.startsWith("2.16.76.1.2.1")) {
ret = "ICP-Brasil A1";
} else if (pcOid.startsWith("2.16.76.1.2.2")) {
ret = "ICP-Brasil A2";
} else if (pcOid.startsWith("2.16.76.1.2.3")) {
ret = "ICP-Brasil A3";
} else if (pcOid.startsWith("2.16.76.1.2.4")) {
ret = "ICP-Brasil A4";
} else if (pcOid.startsWith("2.16.76.1.2.101")) {
ret = "ICP-Brasil S1";
} else if (pcOid.startsWith("2.16.76.1.2.102")) {
ret = "ICP-Brasil S2";
} else if (pcOid.startsWith("2.16.76.1.2.103")) {
ret = "ICP-Brasil S3";
} else if (pcOid.startsWith("2.16.76.1.2.104")) {
ret = "ICP-Brasil S4";
}
return ret;
}
}
|
0 | java-sources/al/bluecryst/bluecrystal/2.3.4/bluecrystal/service | java-sources/al/bluecryst/bluecrystal/2.3.4/bluecrystal/service/service/CryptoService.java | /*
Blue Crystal: Document Digital Signature Tool
Copyright (C) 2007-2015 Sergio Leal
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package bluecrystal.service.service;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.text.ParseException;
import java.util.Date;
import bluecrystal.domain.OperationStatus;
import bluecrystal.domain.SignCompare;
import bluecrystal.domain.SignCompare2;
import bluecrystal.domain.SignPolicyRef;
public interface CryptoService {
public abstract byte[] hashSignedAttribSha1(byte[] origHash,
Date signingTime, X509Certificate x509) throws Exception;
public abstract byte[] hashSignedAttribSha256(byte[] origHash,
Date signingTime, X509Certificate x509) throws Exception;
public abstract byte[] extractSignature(byte[] sign) throws Exception;
public abstract byte[] composeBodySha1(byte[] sign, X509Certificate c,
byte[] origHash, Date signingTime) throws Exception;
public abstract byte[] composeBodySha256(byte[] sign, X509Certificate c,
byte[] origHash, Date signingTime) throws Exception;
public byte[] calcSha256(byte[] content) throws NoSuchAlgorithmException;
public byte[] calcSha1(byte[] content) throws NoSuchAlgorithmException;
public SignCompare extractSignCompare(byte[] sign) throws Exception;
public SignPolicyRef extractVerifyRefence(byte[] policy) throws IOException, ParseException;
public boolean validateSignatureByPolicy(SignPolicyRef spr, SignCompare sc);
public OperationStatus validateSign(byte[] sign, byte[] content,
Date dtSign, boolean verifyCRL) throws Exception;
SignCompare2 extractSignCompare2(byte[] sign) throws Exception;
public boolean validateSignatureByPolicy(byte[] sign, byte[] ps) throws Exception;
OperationStatus validateSignByContent(byte[] signCms, byte[] content, Date dtSign, boolean verifyCRL) throws Exception;
} |
0 | java-sources/al/bluecryst/bluecrystal/2.3.4/bluecrystal/service | java-sources/al/bluecryst/bluecrystal/2.3.4/bluecrystal/service/service/CryptoServiceImpl.java | /*
Blue Crystal: Document Digital Signature Tool
Copyright (C) 2007-2015 Sergio Leal
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package bluecrystal.service.service;
import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.bouncycastle.asn1.DERTaggedObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import bluecrystal.bcdeps.helper.DerEncoder;
import bluecrystal.domain.AppSignedInfo;
import bluecrystal.domain.AppSignedInfoEx;
import bluecrystal.domain.OperationStatus;
import bluecrystal.domain.SignCompare;
import bluecrystal.domain.SignCompare2;
import bluecrystal.domain.SignPolicyRef;
import bluecrystal.domain.StatusConst;
import bluecrystal.service.loader.Messages;
import bluecrystal.service.loader.SignaturePolicyLoader;
import bluecrystal.service.loader.SignaturePolicyLoaderImpl;
import sun.misc.BASE64Decoder;
public class CryptoServiceImpl implements CryptoService {
static final Logger logger = LoggerFactory.getLogger(CryptoServiceImpl.class);
private String validateCert = Messages
.getString("CryptoService.validateCert");
private static EnvelopeService serv2048;
private static EnvelopeService serv1024;
private static CertificateService certServ;
private static SignVerifyService signVerifyServ;
private static SignaturePolicyLoader signaturePolicyLoader;
private static final int NDX_SHA1 = 0;
private static final int NDX_SHA224 = 1;
private static final int NDX_SHA256 = 2;
private static final int NDX_SHA384 = 3;
private static final int NDX_SHA512 = 4;
private static final int SIGNER_ONLY = 1;
private static final int FULL_PATH = 2;
private static final String ID_SHA1 = "1.3.14.3.2.26";
private static final String ID_SHA256 = "2.16.840.1.101.3.4.2.1";
// private static final String ID_SIG_POLICY = "1.2.840.113549.1.9.16.2.15";
public int doIt(String src) {
return 0;
}
public CryptoServiceImpl() {
super();
serv2048 = new ADRBService_21();
serv2048 = new ADRBService_23();
serv1024 = new ADRBService_10();
certServ = new CertificateService();
signVerifyServ = new SignVerifyService();
signaturePolicyLoader = new SignaturePolicyLoaderImpl();
}
/*
* (non-Javadoc)
*
* @see com.ittru.service.CCService#hashSignedAttribSha1(byte[],
* java.util.Date, java.security.cert.X509Certificate)
*/
public byte[] hashSignedAttribSha1(byte[] origHash, Date signingTime,
X509Certificate x509) throws Exception {
return serv1024.hashSignedAttribSha1(origHash, signingTime, x509);
}
/*
* (non-Javadoc)
*
* @see com.ittru.service.CCService#hashSignedAttribSha256(byte[],
* java.util.Date, java.security.cert.X509Certificate)
*/
public byte[] hashSignedAttribSha256(byte[] origHash, Date signingTime,
X509Certificate x509) throws Exception {
return serv2048.hashSignedAttribSha256(origHash, signingTime, x509);
}
/*
* (non-Javadoc)
*
* @see com.ittru.service.CCService#extractSignature(byte[])
*/
public byte[] extractSignature(byte[] sign) throws Exception {
return DerEncoder.extractSignature(sign);
}
public String extractHashId(byte[] sign) throws Exception {
return DerEncoder.extractHashId(sign);
}
public SignCompare extractSignCompare(byte[] sign) throws Exception {
SignCompare signCompare = new SignCompare();
DERTaggedObject signedAttribsDTO = extractDTOSignPolicyOid(sign,
signCompare);
if (signedAttribsDTO != null) {
extractSignPolicyRefFromSignedAttrib(signedAttribsDTO, signCompare);
}
return signCompare;
}
@Override
public SignCompare2 extractSignCompare2(byte[] sign) throws Exception {
SignCompare2 signCompare = new SignCompare2();
DerEncoder.extractSignCompare2(sign, signCompare);
return signCompare;
}
public DERTaggedObject extractDTOSignPolicyOid(byte[] sign,
SignCompare signCompare) throws Exception {
return DerEncoder.extractDTOSignPolicyOid(sign, signCompare);
}
@Override
public OperationStatus validateSignByContent(byte[] signCms, byte[] content,
Date dtSign, boolean verifyCRL) throws Exception {
byte[] origHash = null;
String hashIdStr = extractHashId(signCms);
if (ID_SHA256.compareTo(hashIdStr) == 0) {
origHash = calcSha256(content);
} else {
origHash = calcSha1(content);
}
return validateSign(signCms, origHash, dtSign, verifyCRL);
}
public OperationStatus validateSign(byte[] signCms, byte[] origHash, Date dtSign,
boolean verifyCRL) throws Exception {
boolean ret = true;
OperationStatus operationStatus = null;
// Extract Signature Info from CMS
SignCompare signCompare = extractSignCompare(signCms);
X509Certificate cert = certServ.decodeEE(signCms);
String hashIdStr = extractHashId(signCms);
byte[] sign = extractSignature(signCms);
// Validate Certificate Status
boolean validateCertB = Boolean.parseBoolean(validateCert);
if (validateCertB) {
logger.debug("Certificado será validado");
if (dtSign != null) {
operationStatus = certServ.isValid(dtSign, cert, verifyCRL);
} else {
operationStatus = certServ.isValid(signCompare.getSigningTime(),
cert, verifyCRL);
}
} else {
operationStatus = new OperationStatus(StatusConst.GOOD, new Date());
logger.warn("Certificado NÃO será validado! Usar essa opção apenas em AMBIENTE DE TESTES. Altere no bluc.properties.");
}
// if (!(operationStatus.getStatus() == StatusConst.GOOD ||
// operationStatus.getStatus() == StatusConst.UNKNOWN)) {
// return false;
// }
// Go on with Validation,otherwise return error...
if (operationStatus.getStatus() == StatusConst.GOOD || operationStatus.getStatus() == StatusConst.UNKNOWN){
int hashId = NDX_SHA1;
byte[] contentHash = null;
if (signCompare.getSignedAttribs() == null
|| signCompare.getSignedAttribs().size() == 0) {
contentHash = origHash;
} else {
if (ID_SHA256.compareTo(hashIdStr) == 0) {
hashId = NDX_SHA256;
byte[] hashSa = hashSignedAttribSha256(origHash,
signCompare.getSigningTime(), cert);
contentHash = calcSha256(hashSa);
} else {
byte[] hashSa = hashSignedAttribSha1(origHash,
signCompare.getSigningTime(), cert);
contentHash = calcSha1(hashSa);
}
}
ret = signVerifyServ.verify(hashId, contentHash, sign, cert);
if(!ret){
logger.error("Definido status da assinatura como StatusConst.INVALID_SIGN");
operationStatus.setStatus(StatusConst.INVALID_SIGN);
} else {
logger.debug("Assinatura é valida");
}
}
return operationStatus;
}
public boolean validateSignatureByPolicy(SignPolicyRef spr, SignCompare sc) {
boolean isNotBefore = sc.getSigningTime().after(spr.getNotBefore());
boolean isNotAfter = sc.getSigningTime().before(spr.getNotAfter());
List<String> sprAttr = spr.getMandatedSignedAttr();
List<String> scAttr = sc.getSignedAttribs();
boolean attrOk = true;
for (String next : sprAttr) {
if (!scAttr.contains(next)) {
attrOk = false;
}
}
boolean isMcr = true;
if (spr.getMandatedCertificateRef() == SIGNER_ONLY) {
isMcr = sc.getNumCerts() == 1 ? true : false;
} else if (spr.getMandatedCertificateRef() == FULL_PATH) {
isMcr = sc.getNumCerts() > 1 ? true : false;
// TODO: validate full path
}
boolean isPolOid = spr.getPsOid().compareTo(sc.getPsOid()) == 0;
return isNotBefore && isNotAfter && attrOk && isMcr && isPolOid;
}
private void extractSignPolicyRefFromSignedAttrib(
DERTaggedObject signedAttribsDTO, SignCompare signCompare)
throws Exception {
DerEncoder.extractSignPolicyRefFromSignedAttrib(signedAttribsDTO,
signCompare);
}
public SignPolicyRef extractVerifyRefence(byte[] policy)
throws IOException, ParseException {
return DerEncoder.extractVerifyRefence(policy);
}
/*
* (non-Javadoc)
*
* @see com.ittru.service.CCService#composeBodySha1(byte[],
* java.security.cert.X509Certificate, byte[], java.util.Date)
*/
public byte[] composeBodySha1(byte[] sign, X509Certificate c,
byte[] origHash, Date signingTime) throws Exception {
byte[] ret = null;
int idSha = NDX_SHA1;
List<AppSignedInfoEx> listAsiEx = new ArrayList<AppSignedInfoEx>();
List<X509Certificate> chain = new ArrayList<X509Certificate>();
byte[] certHash = calcSha1(c.getEncoded());
AppSignedInfoEx asiEx = new AppSignedInfoEx(sign, origHash,
signingTime, c, certHash, idSha);
listAsiEx.add(asiEx);
ret = serv1024.buildCms(listAsiEx, -1);
return ret;
}
/*
* (non-Javadoc)
*
* @see com.ittru.service.CCService#composeBodySha256(byte[],
* java.security.cert.X509Certificate, byte[], java.util.Date)
*/
public byte[] composeBodySha256(byte[] sign, X509Certificate c,
byte[] origHash, Date signingTime) throws Exception {
byte[] ret = null;
int idSha = NDX_SHA256;
List<AppSignedInfoEx> listAsiEx = new ArrayList<AppSignedInfoEx>();
// List<X509Certificate> chain = new ArrayList<X509Certificate>();
byte[] certHash = calcSha256(c.getEncoded());
AppSignedInfoEx asiEx = new AppSignedInfoEx(sign, origHash,
signingTime, c, certHash, idSha);
listAsiEx.add(asiEx);
ret = serv2048.buildCms(listAsiEx, -1);
return ret;
}
public byte[] composeBodySha256(List<AppSignedInfo> listAsi) throws Exception {
byte[] ret = null;
int idSha = NDX_SHA256;
List<AppSignedInfoEx> listAsiEx = new ArrayList<AppSignedInfoEx>();
// List<X509Certificate> chain = new ArrayList<X509Certificate>();
BASE64Decoder b64dec = new BASE64Decoder();
for (AppSignedInfo appSignedInfo : listAsi) {
// AppSignedInfo appSignedInfo = listAsi.get(0);
byte[] x509 = b64dec.decodeBuffer(appSignedInfo.getCertId());
X509Certificate cert = loadCert(x509);
byte[] certHash = calcSha256(cert.getEncoded());
AppSignedInfoEx asiEx = new AppSignedInfoEx(appSignedInfo, cert,
certHash, idSha);
listAsiEx.add(asiEx);
}
ret = serv2048.buildCms(listAsiEx, -1);
return ret;
}
private X509Certificate loadCert(byte[] certEnc)
throws FileNotFoundException, CertificateException, IOException {
InputStream is = new ByteArrayInputStream(certEnc);
CertificateFactory cf = CertificateFactory.getInstance("X509");
X509Certificate c = (X509Certificate) cf.generateCertificate(is);
is.close();
return c;
}
public byte[] calcSha1(byte[] content) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA1");
md.reset();
md.update(content);
byte[] output = md.digest();
return output;
}
public byte[] calcSha256(byte[] content) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA256");
md.reset();
md.update(content);
byte[] output = md.digest();
return output;
}
public boolean validateSignatureByPolicy(byte[] sign, byte[] ps)
throws Exception {
try {
// byte[] sign = Base64.decode(signb64);
// byte[] ps = (psb64 != null && psb64.length() > 0) ? Base64.decode(signb64) : null;
SignCompare sc = extractSignCompare(sign);
if (ps == null) {
ps = signaturePolicyLoader.loadFromUrl(sc.getPsUrl());
}
SignPolicyRef spr = extractVerifyRefence(ps);
return validateSignatureByPolicy(spr, sc);
} catch (Exception e) {
throw e;
}
}
}
|
0 | java-sources/al/bluecryst/bluecrystal/2.3.4/bluecrystal/service | java-sources/al/bluecryst/bluecrystal/2.3.4/bluecrystal/service/service/ServiceFacade.java | package bluecrystal.service.service;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import org.bouncycastle.util.encoders.Base64;
import bluecrystal.domain.NameValue;
import bluecrystal.domain.OperationStatus;
import bluecrystal.service.exception.InvalidSigntureException;
import bluecrystal.service.helper.UtilsLocal;
import bluecrystal.service.jwt.Claim;
import bluecrystal.service.jwt.Credential;
import bluecrystal.service.jwt.JwtService;
public class ServiceFacade {
public static final int NDX_SHA1 = 0;
public static final int NDX_SHA224 = 1;
public static final int NDX_SHA256 = 2;
public static final int NDX_SHA384 = 3;
public static final int NDX_SHA512 = 4;
private CryptoService ccServ = null;
private CertificateService certServ = null;
private SignVerifyService verify = null;
private ValidatorSrv validatorServ = null;
private JwtService jwtServ = null;
public ServiceFacade() {
super();
ccServ = new CryptoServiceImpl();
certServ = new CertificateService();
verify = new SignVerifyService();
validatorServ = new Validator();
jwtServ = new JwtService();
}
public byte[] calcSha256(byte[] content) throws NoSuchAlgorithmException {
return ccServ.calcSha256(content);
}
public String hashSignedAttribADRB21(String origHashB64, Date signingTime, String x509B64) throws Exception {
// logger.debug("hashSignedAttribSha256: " + "\norigHashB64 (" +
// origHashB64
// + ")" + "\nsigningTime(" + signingTime + ")" + "\nx509B64("
// + x509B64 + ")");
try {
byte[] origHash = Base64.decode(origHashB64);
byte[] x509 = Base64.decode(x509B64);
X509Certificate cert = certServ.createFromB64(x509);
byte[] ret = ccServ.hashSignedAttribSha256(origHash, signingTime, cert);
return new String(Base64.encode(ret));
} catch (Exception e) {
// ;logger.error("ERRO: ", e);
throw e;
}
}
public String hashSignedAttribADRB10(String origHashB64, Date signingTime, String x509B64) throws Exception {
// logger.debug("hashSignedAttribSha1: " + "\norigHashB64 (" +
// origHashB64
// + ")" + "\nsigningTime(" + signingTime + ")" + "\nx509B64("
// + x509B64 + ")");
try {
byte[] origHash = Base64.decode(origHashB64);
byte[] x509 = Base64.decode(x509B64);
X509Certificate cert = certServ.createFromB64(x509);
byte[] ret = ccServ.hashSignedAttribSha1(origHash, signingTime, cert);
return new String(Base64.encode(ret));
} catch (Exception e) {
// logger.error("ERRO: ", e);
throw e;
}
}
public String composeEnvelopeADRB21(String signB64, String x509B64, String origHashB64, Date signingTime)
throws Exception {
// logger.debug("composeBodySha256: " + "\nsignB64 (" + signB64 + ")"
// + "\nx509B64 (" + x509B64 + ")" + "\norigHashB64 ("
// + origHashB64 + ")" + "\nsigningTime (" + signingTime + ")");
try {
byte[] sign = Base64.decode(signB64);
byte[] origHash = Base64.decode(origHashB64);
byte[] x509 = Base64.decode(x509B64);
X509Certificate cert = certServ.createFromB64(x509);
byte[] hashSa = ccServ.hashSignedAttribSha256(origHash, signingTime, cert);
if (!verify.verify(NDX_SHA256, ccServ.calcSha256(hashSa), sign, cert)) {
// logger.error("Verificação retornou erro, lancando
// InvalidSigntureException.");
throw new InvalidSigntureException();
} else {
// logger.debug("Assinatura verificada com sucesso!");
}
byte[] ret = ccServ.composeBodySha256(sign, cert, origHash, signingTime);
return new String(Base64.encode(ret));
} catch (Exception e) {
// logger.error("ERRO: ", e.getLocalizedMessage());
// logger.error(LogManager.exceptionToString(e));
throw e;
}
}
public Date parseDate(String srcDate) throws ParseException{
DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
Date result1 = df1.parse(srcDate);
return result1;
}
public String parseDate(Date srcDate) throws ParseException{
DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
String result1 = df1.format(srcDate);
return result1;
}
// private int validateSignWithStatus(Boolean algSha256, String ret, String filename) throws Exception {
//
// MessageDigest hashSum = null;
// if(algSha256){
// hashSum = MessageDigest.getInstance("SHA-256");
// logger.debug("Validar assinatura SHA-256");
//
// } else {
// hashSum = MessageDigest.getInstance("SHA-1");
// logger.debug("Validar assinatura SHA-1");
// }
// hashSum.update(Convert.readFile(filename));
// byte[] digestResult = hashSum.digest();
//
//// Base64.Encoder encoder = Base64.getEncoder();
// String digestB64 = new String(Base64.encode(digestResult));
// return serv.validateSignWithStatus(ret, digestB64, Convert.asXMLGregorianCalendar(new Date()), false);
// }
// Validate CMS envelope
public int validateSignWithStatus(String signCms, String origHashb64, Date dtSign,
boolean verifyCRL) throws Exception {
// logger.debug("validateSign: " + "\n signCms (" + signCms + ")"
// + "\n content (" + origHashb64 + ")" + "\n dtSign (" + dtSign + ")"
// + "\n verifyCRL (" + verifyCRL + ")");
try {
byte[] sign = Base64.decode(signCms);
byte[] origHash = Base64.decode(origHashb64);
int validateSign = ccServ.validateSign(sign, origHash, dtSign, verifyCRL).getStatus();
return validateSign;
} catch (Exception e) {
// logger.error("ERRO: ", e);
throw e;
}
}
public String extractSignerCert(String signb64) throws Exception {
// logger.debug("extractSignCompare: " + "\nsignb64 (" + signb64 + ")");
try {
byte[] sign = Base64.decode(signb64);
X509Certificate certEE = certServ.decodeEE(sign);
return new String ( Base64.encode(certEE.getEncoded() ));
} catch (Exception e) {
// logger.error("ERRO: ", e);
throw e;
}
}
public String getCertSubject(String cert) throws Exception {
// logger.debug("getCertSubject: " + "\ncert (" + cert + ")");
try {
Map<String, String> certEE = validatorServ.parseCertificateAsMap(cert);
return certEE.get("subject0");
} catch (Exception e) {
// logger.error("ERRO: ", e);
throw e;
}
}
public OperationStatus isValid(Date refDate, String certb64,
boolean verifyRevoke) throws Exception
{
X509Certificate cert = UtilsLocal.createCert(certb64);
return certServ.isValid(refDate, cert, verifyRevoke);
}
public String preSign(Claim claim, Credential credential) throws Exception {
return jwtServ.preSign(claim, credential);
}
public String sign(Claim claim, Credential credential) throws Exception {
return jwtServ.sign(claim, credential);
}
public String postSign(Credential credential, String preSigned, String signed) throws Exception {
return jwtServ.postSign(credential, preSigned, Base64.decode(signed));
}
public Claim verify(Credential credential, String token) throws Exception {
return jwtServ.verify(token, credential);
}
public NameValue[] parseCertificate(String certificate) throws Exception{
return validatorServ.parseCertificate(certificate);
}
}
|
0 | java-sources/al/bluecryst/bluecrystal/2.3.4/bluecrystal/service | java-sources/al/bluecryst/bluecrystal/2.3.4/bluecrystal/service/service/SignVerifyService.java | /*
Blue Crystal: Document Digital Signature Tool
Copyright (C) 2007-2015 Sergio Leal
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package bluecrystal.service.service;
import java.io.IOException;
import java.security.cert.X509Certificate;
import java.security.interfaces.RSAPublicKey;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.asn1.x509.DigestInfo;
import org.bouncycastle.crypto.AsymmetricBlockCipher;
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.Digest;
import org.bouncycastle.crypto.digests.SHA1Digest;
import org.bouncycastle.crypto.digests.SHA224Digest;
import org.bouncycastle.crypto.digests.SHA256Digest;
import org.bouncycastle.crypto.digests.SHA384Digest;
import org.bouncycastle.crypto.digests.SHA512Digest;
import org.bouncycastle.crypto.encodings.PKCS1Encoding;
import org.bouncycastle.crypto.engines.RSABlindedEngine;
import org.bouncycastle.crypto.params.RSAKeyParameters;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import bluecrystal.bcdeps.helper.DerEncoder;
import bluecrystal.domain.helper.IttruLoggerFactory;
import bluecrystal.service.helper.UtilsLocal;
public class SignVerifyService {
static final Logger logger = LoggerFactory.getLogger(SignVerifyService.class);
public SignVerifyService() {
super();
}
public static String [] algName = {"SHA1withRSA", "SHA224withRSA", "SHA256withRSA", "SHA384withRSA", "SHA512withRSA"};
public boolean verify(int hashId, byte[] contentHash, byte[] sigBytes, X509Certificate cert)
throws Exception {
RSAPublicKey pubK = (RSAPublicKey) cert.getPublicKey();
CipherParameters param = new RSAKeyParameters(false, pubK.getModulus(), pubK.getPublicExponent());
RSABlindedEngine cipher2 = new RSABlindedEngine();
cipher2.init(false, param);
AsymmetricBlockCipher cipher = new PKCS1Encoding(cipher2);
byte[] sig = cipher.processBlock(sigBytes, 0, sigBytes.length);
AlgorithmIdentifier algId = createAlgorithm(hashId);
byte[] expected = derEncode(contentHash, algId);
logger.debug("Sig:("+sigBytes.length+")"+UtilsLocal.conv(sigBytes));
logger.debug("Has:("+contentHash.length+")"+UtilsLocal.conv(contentHash));
logger.debug("Sig:("+sig.length+")"+UtilsLocal.conv(sig));
logger.debug("Exp:("+expected.length+")"+UtilsLocal.conv(expected));
System.out.println("Sig:("+sigBytes.length+")"+UtilsLocal.conv(sigBytes));
System.out.println("Has:("+contentHash.length+")"+UtilsLocal.conv(contentHash));
System.out.println("Sig:("+sig.length+")"+UtilsLocal.conv(sig));
System.out.println("Exp:("+expected.length+")"+UtilsLocal.conv(expected));
if (sig.length == expected.length) {
for (int i = 0; i < sig.length; i++) {
if (sig[i] != expected[i]) {
logger.error("Comprimento da assinatura é invalido.");
return false;
}
}
}
else if (sig.length == expected.length - 2) // NULL left out
{
int sigOffset = sig.length - contentHash.length - 2;
int expectedOffset = expected.length - contentHash.length - 2;
expected[1] -= 2; // adjust lengths
expected[3] -= 2;
for (int i = 0; i < contentHash.length; i++)
{
if (sig[sigOffset + i] != expected[expectedOffset + i]) // check hash
{
return false;
}
}
for (int i = 0; i < sigOffset; i++)
{
if (sig[i] != expected[i]) // check header less NULL
{
return false;
}
}
}
else
{
return false;
}
return true;
}
private AlgorithmIdentifier createAlgorithm(int hashId) throws Exception {
return DerEncoder.createAlgorithm(hashId);
}
private byte[] derEncode(byte[] contentHash, AlgorithmIdentifier algId)
throws Exception {
DigestInfo dInfo = new DigestInfo(algId, contentHash);
byte[] encoded = encodeDigest(dInfo);
return encoded;
}
private byte[] encodeDigest(DigestInfo dInfo) throws IOException {
return DerEncoder.encodeDigest(dInfo);
}
private Digest getHashById(int hashId) {
Digest ret = null;
switch (hashId) {
case DerEncoder.NDX_SHA1:
ret = new SHA1Digest();
break;
case DerEncoder.NDX_SHA224:
ret = new SHA224Digest();
break;
case DerEncoder.NDX_SHA256:
ret = new SHA256Digest();
break;
case DerEncoder.NDX_SHA384:
ret = new SHA384Digest();
break;
case DerEncoder.NDX_SHA512:
ret = new SHA512Digest();
break;
default:
break;
}
return ret;
}
}
|
0 | java-sources/al/bluecryst/bluecrystal/2.3.4/bluecrystal/service | java-sources/al/bluecryst/bluecrystal/2.3.4/bluecrystal/service/validator/CrlValidatorImpl.java | /*
Blue Crystal: Document Digital Signature Tool
Copyright (C) 2007-2015 Sergio Leal
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package bluecrystal.service.validator;
import java.io.IOException;
import java.security.cert.CRLException;
import java.security.cert.CertificateException;
import java.security.cert.X509CRL;
import java.security.cert.X509CRLEntry;
import java.security.cert.X509Certificate;
import java.util.Date;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import bluecrystal.domain.OperationStatus;
import bluecrystal.domain.StatusConst;
import bluecrystal.service.exception.RevokedException;
import bluecrystal.service.exception.UndefStateException;
import bluecrystal.service.loader.LCRLoader;
public class CrlValidatorImpl implements CrlValidator {
static final Logger logger = LoggerFactory.getLogger(CrlValidatorImpl.class);
private LCRLoader lcrLoader;
public CrlValidatorImpl(LCRLoader lcrLoader) {
super();
this.lcrLoader = lcrLoader;
}
public OperationStatus verifyLCR(X509Certificate nextCert,
Date date, List<String> distPoints)
throws IOException, CertificateException, CRLException,
UndefStateException, RevokedException {
// List<String> distPoints = getCrlDistributionPoints(nextCert);
X509CRL lcr = null;
if (distPoints.size() != 0) {
lcr = lcrLoader.get(distPoints, date);
if (lcr != null) {
X509CRLEntry entry = lcr.getRevokedCertificate(nextCert
.getSerialNumber());
if (entry != null) {
if (entry.getRevocationDate() != null
&& entry.getRevocationDate().before(date)) {
throw new RevokedException();
}
}
if (lcr.getThisUpdate().before(date)) {
logger.debug("LCR é anterior a data da assinatura, não tenho como ter certeza do status: UNKOWN");
Date upd = lcr.getNextUpdate();
return new OperationStatus(StatusConst.UNKNOWN, upd);
}
Date upd = lcr.getNextUpdate();
return new OperationStatus(StatusConst.GOOD, upd);
}
else {
logger.error("LCR is NULL");
return new OperationStatus(StatusConst.UNTRUSTED, null);
}
} else {
logger.error("CRL DP not found");
return new OperationStatus(StatusConst.UNKNOWN, null);
}
}
}
|
0 | java-sources/al/bluecryst/bluecrystal/2.3.4/bluecrystal/service | java-sources/al/bluecryst/bluecrystal/2.3.4/bluecrystal/service/validator/StatusValidatorImpl.java | /*
Blue Crystal: Document Digital Signature Tool
Copyright (C) 2007-2015 Sergio Leal
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package bluecrystal.service.validator;
import java.io.IOException;
import java.security.cert.CRLException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.bouncycastle.operator.OperatorCreationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import bluecrystal.domain.OperationStatus;
import bluecrystal.domain.StatusConst;
import bluecrystal.domain.helper.IttruLoggerFactory;
import bluecrystal.service.exception.RevokedException;
import bluecrystal.service.exception.UndefStateException;
public class StatusValidatorImpl implements StatusValidator {
static final Logger LOG = LoggerFactory.getLogger(StatusValidatorImpl.class);
private boolean useOcsp;
private OcspValidator ocspValidator;
private CrlValidator crlValidator;
public StatusValidatorImpl(CrlValidator crlValidator,
OcspValidator ocspValidator) {
super();
this.ocspValidator = ocspValidator;
this.crlValidator = crlValidator;
}
public void setUseOcsp(boolean useOcsp) {
this.useOcsp = useOcsp;
}
public OperationStatus verifyStatusEE(Collection<X509Certificate> certsOnPath,
Date date, List<String> crlDist)
throws IOException, CertificateException, CRLException,
UndefStateException, RevokedException {
Iterator<X509Certificate> it = certsOnPath.iterator();
OperationStatus eeCertStatus = new OperationStatus(StatusConst.GOOD, null);
OperationStatus nextCertStatus = new OperationStatus(StatusConst.GOOD, null);
X509Certificate nextCert = null;
X509Certificate nextIssuer = null;
// First cert is EE
if (it.hasNext()) {
nextCert = it.next();
LOG.debug("** EE - VALIDATING: "+nextCert.getSubjectDN().getName()+ " " + new Date());
nextCertStatus = crlValidator.verifyLCR(nextCert, date, crlDist);
eeCertStatus = nextCertStatus;
} else {
LOG.error("** ERROR: nenhum certificado na hierarquia! " + new Date());
}
if (it.hasNext() && useOcsp) {
// while (it.hasNext() && useOcsp) {
nextIssuer = it.next();
if (nextCertStatus.getStatus() == StatusConst.UNKNOWN) {
if (useOcsp) {
LOG.debug("validating OCSP");
try {
nextCertStatus = ocspValidator.verifyOCSP(nextCert,
nextIssuer, date);
} catch (Exception e) {
// se deu excecao, ok. Continua com o status anterior.
}
}
if (isEE(nextCert)) {
eeCertStatus = nextCertStatus;
}
}
}
LOG.debug("Cert bom até .."+eeCertStatus.getGoodUntil());
return eeCertStatus;
}
public OperationStatus verifyStatus(Collection<X509Certificate> certsOnPath, Date date)
throws IOException, CertificateException, CRLException,
UndefStateException, RevokedException, OperatorCreationException {
Iterator<X509Certificate> it = certsOnPath.iterator();
OperationStatus eeCertStatus = new OperationStatus(StatusConst.GOOD, null);
OperationStatus nextCertStatus = new OperationStatus(StatusConst.GOOD, null);
X509Certificate nextCert = null;
X509Certificate nextIssuer = null;
// First cert is EE
if (it.hasNext()) {
nextCert = it.next();
LOG.debug("** EE - VALIDATING: "+nextCert.getSubjectDN().getName()+ " " + new Date());
nextCertStatus = crlValidator.verifyLCR(nextCert, date, null);
eeCertStatus = nextCertStatus;
}
while (it.hasNext() && useOcsp) {
nextIssuer = it.next();
if (nextCertStatus.getStatus() == StatusConst.UNKNOWN) {
if (useOcsp) {
nextCertStatus = ocspValidator.verifyOCSP(nextCert,
nextIssuer, date);
}
if (isEE(nextCert)) {
eeCertStatus = nextCertStatus;
}
}
nextCert = nextIssuer;
LOG.debug("VALIDATING: "+nextCert.getSubjectDN().getName()+ " " + new Date());
nextCertStatus = crlValidator.verifyLCR(nextCert, date, null);
}
if (useOcsp) {
ocspValidator.verifyOCSP(nextCert, nextCert, date);
if (eeCertStatus.getStatus() == StatusConst.UNKNOWN) {
throw new UndefStateException();
}
}
return eeCertStatus;
}
private static boolean isEE(X509Certificate nextCert) {
return nextCert.getBasicConstraints() == -1;
}
}
|
0 | java-sources/al/bluecryst/bluecrystal.deps.bc_g3/1.16.0/bluecrystal/bcdeps | java-sources/al/bluecryst/bluecrystal.deps.bc_g3/1.16.0/bluecrystal/bcdeps/helper/DerEncoder.java | /*
Blue Crystal: Document Digital Signature Tool
Copyright (C) 2007-2015 Sergio Leal
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package bluecrystal.bcdeps.helper;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.cert.CRLException;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateParsingException;
import java.security.cert.X509Certificate;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.bouncycastle.asn1.ASN1Encodable;
import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.ASN1Encoding;
import org.bouncycastle.asn1.ASN1Enumerated;
import org.bouncycastle.asn1.ASN1GeneralizedTime;
import org.bouncycastle.asn1.ASN1InputStream;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.ASN1OctetString;
import org.bouncycastle.asn1.ASN1OutputStream;
import org.bouncycastle.asn1.ASN1Primitive;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.ASN1Set;
import org.bouncycastle.asn1.ASN1UTCTime;
import org.bouncycastle.asn1.DERBitString;
import org.bouncycastle.asn1.DERIA5String;
import org.bouncycastle.asn1.DERInteger;
import org.bouncycastle.asn1.DERNull;
import org.bouncycastle.asn1.DERObjectIdentifier;
import org.bouncycastle.asn1.DEROctetString;
import org.bouncycastle.asn1.DERPrintableString;
import org.bouncycastle.asn1.DERSequence;
import org.bouncycastle.asn1.DERSet;
import org.bouncycastle.asn1.DERTaggedObject;
import org.bouncycastle.asn1.DERUTCTime;
import org.bouncycastle.asn1.DERUTF8String;
import org.bouncycastle.asn1.DLSequence;
import org.bouncycastle.asn1.cms.Attribute;
import org.bouncycastle.asn1.ocsp.OCSPObjectIdentifiers;
import org.bouncycastle.asn1.x509.AccessDescription;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.asn1.x509.AuthorityInformationAccess;
import org.bouncycastle.asn1.x509.CRLDistPoint;
import org.bouncycastle.asn1.x509.DigestInfo;
import org.bouncycastle.asn1.x509.DistributionPoint;
import org.bouncycastle.asn1.x509.DistributionPointName;
import org.bouncycastle.asn1.x509.Extension;
import org.bouncycastle.asn1.x509.Extensions;
import org.bouncycastle.asn1.x509.GeneralName;
import org.bouncycastle.asn1.x509.GeneralNames;
import org.bouncycastle.asn1.x509.X509Extensions;
import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.cert.ocsp.CertificateID;
import org.bouncycastle.cert.ocsp.OCSPException;
import org.bouncycastle.cert.ocsp.OCSPReq;
import org.bouncycastle.cert.ocsp.OCSPReqBuilder;
import org.bouncycastle.operator.DigestCalculatorProvider;
import org.bouncycastle.operator.OperatorCreationException;
import org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder;
import org.bouncycastle.util.encoders.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import bluecrystal.domain.AppSignedInfoEx;
import bluecrystal.domain.CertConstants;
import bluecrystal.domain.SignCompare;
import bluecrystal.domain.SignCompare2;
import bluecrystal.domain.SignPolicy;
import bluecrystal.domain.SignPolicyRef;
public class DerEncoder {
static final Logger LOG = LoggerFactory.getLogger(DerEncoder.class);
private static final int DETACHED = -1;
private static final int SI_VERSION = 1;
private static final String CMS_SIGNED_ID = "1.2.840.113549.1.7.2";
private static final String ID_PKCS7_SIGNED_DATA = "1.2.840.113549.1.7.2"; // o
// mesmo
// de
// cima
private static final String ID_PKCS7_DATA = "1.2.840.113549.1.7.1";
private static final String ID_RSA = "1.2.840.113549.1.1.1";
private static final String ID_SHA1_RSA = "1.2.840.113549.1.1.5";
private static final String ID_SHA256_RSA = "1.2.840.113549.1.1.11";
private static final String ID_SHA384_RSA = "1.2.840.113549.1.1.12";
private static final String ID_SHA512_RSA = "1.2.840.113549.1.1.13";
private static final String ID_CONTENT_TYPE = "1.2.840.113549.1.9.3";
private static final String ID_MESSAGE_DIGEST = "1.2.840.113549.1.9.4";
public static final String ID_SIGNING_TIME = "1.2.840.113549.1.9.5";
private static final String ID_SIGNING_CERT = "1.2.840.113549.1.9.16.2.12";
private static final String ID_SIGNING_CERT2 = "1.2.840.113549.1.9.16.2.47";
public static final String ID_SIG_POLICY = "1.2.840.113549.1.9.16.2.15";
private static final String ID_SIG_POLICY_URI = "1.2.840.113549.1.9.16.5.1";
private static final String ID_ADBE_REVOCATION = "1.2.840.113583.1.1.8";
private static final String ID_SHA1 = "1.3.14.3.2.26";
private static final String ID_SHA224 = "2.16.840.1.101.3.4.2.4";
private static final String ID_SHA256 = "2.16.840.1.101.3.4.2.1";
private static final String ID_SHA384 = "2.16.840.1.101.3.4.2.2";
private static final String ID_SHA512 = "2.16.840.1.101.3.4.2.3";
public static final int NDX_SHA1 = 0;
public static final int NDX_SHA224 = 1;
public static final int NDX_SHA256 = 2;
public static final int NDX_SHA384 = 3;
public static final int NDX_SHA512 = 4;
private static final String PF_PF_ID = "2.16.76.1.3.1";
private static final int BIRTH_DATE_INI = 0;
private static final int BIRTH_DATE_LEN = 8;
private static final int CPF_INI = BIRTH_DATE_LEN;
private static final int CPF_LEN = CPF_INI + 11;
private static final int PIS_INI = CPF_LEN;
private static final int PIS_LEN = PIS_INI + 11;
private static final int RG_INI = PIS_LEN;
private static final int RG_LEN = RG_INI + 15;
private static final int RG_ORG_UF_INI = RG_LEN;
private static final int RG_ORG_UF_LEN = RG_ORG_UF_INI + 6;
private static final int RG_UF_LEN = 2;
private static final String ICP_BRASIL_PF = "ICP-Brasil PF";
private static final String ICP_BRASIL_PJ = "ICP-Brasil PJ";
private static final String CERT_TYPE_FMT = "cert_type%d";
private static final String CNPJ_OID = "2.16.76.1.3.3";
private static final String ICP_BRASIL_PC_PREFIX_OID = "2.16.76.1.2";
private static final String EKU_OCSP_SIGN_OID = "1.3.6.1.5.5.7.3.9";
private static final String EKU_TIMESTAMP_OID = "1.3.6.1.5.5.7.3.8";
private static final String EKU_IPSEC_USER_OID = "1.3.6.1.5.5.7.3.7";
private static final String EKU_IPSEC_TUNNEL_OID = "1.3.6.1.5.5.7.3.6";
private static final String EKU_IPSEC_END_OID = "1.3.6.1.5.5.7.3.5";
private static final String EKU_EMAIL_PROT_OID = "1.3.6.1.5.5.7.3.4";
private static final String EKU_CODE_SIGN_OID = "1.3.6.1.5.5.7.3.3";
private static final String EKU_CLIENT_AUTH_OID = "1.3.6.1.5.5.7.3.2";
private static final String EKU_SERVER_AUTH_OID = "1.3.6.1.5.5.7.3.1";
private static final String UPN = "1.3.6.1.4.1.311.20.2.3";
private static final String PROFESSIONAL_OID = "2.16.76.1.4.";
private static final String OAB_OID = "2.16.76.1.4.2.1.1";
private static final String PJ_PF_INSS_OID = "2.16.76.1.3.7";
private static final String PERSON_NAME_OID = "2.16.76.1.3.2";
private static final String PF_PF_INSS_OID = "2.16.76.1.3.6";
private static final String ELEITOR_OID = "2.16.76.1.3.5";
private static final String PJ_PF_ID = "2.16.76.1.3.4";
// PF 2.16.76.1.3.5 - Titulo de eleitor(12), Zona Eleitoral (3), Secao (4)
private static final int ELEITOR_INI = 0;
private static final int ELEITOR_LEN = 12;
private static final int ZONA_INI = ELEITOR_LEN;
private static final int ZONA_LEN = 3;
private static final int SECAO_INI = ZONA_INI + ZONA_LEN;
private static final int SECAO_LEN = 4;
// PJ 2.16.76.1.3.7 - INSS (12)
private static final int INSS_INI = 0;
private static final int INSS_LEN = 12;
// 2.16.76.1.4.2.1.1- = nas primeiras 07 (sete) posicoes os digitos
// alfanumericos do Numero de Inscricao junto a Seccional, e nas 2 (duas)
// posicoes subsequentes a sigla do Estado da Seccional.
private static final int OAB_REG_INI = 0;
private static final int OAB_REG_LEN = 12;
private static final int OAB_UF_INI = OAB_REG_LEN;
private static final int OAB_UF_LEN = 3;
private static final String CERT_POL_OID = "certPolOid%d";
private static final String CERT_POL_QUALIFIER = "certPolQualifier%d";
public byte[] buildCmsBody(String signedHashId,
X509Certificate certContent, byte[] content, String hashId,
int version) throws CertificateEncodingException, IOException {
final ASN1EncodableVector whole = new ASN1EncodableVector();
whole.add(new DERObjectIdentifier(CMS_SIGNED_ID));
final ASN1EncodableVector body = new ASN1EncodableVector();
// ----- versao -------
// final int version = 1;
body.add(new DERInteger(version));
buildDigestAlg(body, hashId);
// buildContentInfo(body, content);
buildCerts(body, certContent);
buildSignerInfo(body, signedHashId, certContent, hashId);
whole.add(new DERTaggedObject(0, new DERSequence(body)));
return genOutput(new DERSequence(whole));
}
public byte[] buildCmsBody(byte[] signedHashId,
X509Certificate certContent, List<X509Certificate> chain,
int hashId, int version, int attachSize) throws Exception {
final ASN1EncodableVector whole = new ASN1EncodableVector(); // 0 SEQ
whole.add(new DERObjectIdentifier(CMS_SIGNED_ID)); // 1 SEQ
final ASN1EncodableVector body = new ASN1EncodableVector();
// ----- versao -------
// final int version = 1;
body.add(new DERInteger(version)); // 3 INT
buildDigestAlg(body, getHashAlg(hashId)); // 3 SET
buildContentInfo(body, attachSize); // 3 SEQ
buildCerts(body, chain); // 3 CS
buildSignerInfo(body, signedHashId, certContent, hashId); // 3 SET
whole.add(new DERTaggedObject(0, new DERSequence( // 2 SEQ
body))); // 1 CS
return genOutput(new DERSequence(whole));
}
// cmsOut = de.buildADRBBody(asiEx.getSignedHash(), asiEx.getX509(),
// addChain?chain:null,
// asiEx.getOrigHash(),
// policyHash, asiEx.getCertHash(), asiEx.getSigningTime(),
// asiEx.getIdSha(), policyUri, policyId,
// version, signingCertFallback);
public byte[] buildADRBBody(List<AppSignedInfoEx> listAsiEx,
SignPolicy signPol, List<X509Certificate> chain, int version,
boolean signingCertFallback, int attachSize) throws Exception {
// AppSignedInfoEx asiEx = listAsiEx.get(0);
final ASN1EncodableVector whole = new ASN1EncodableVector(); // 0 SEQ
whole.add(new DERObjectIdentifier(CMS_SIGNED_ID)); // 1 SEQ
final ASN1EncodableVector body = new ASN1EncodableVector();
// ----- versao -------
// final int version = 1;
body.add(new DERInteger(version)); // 3 INT
List<String> listHashId = createHashList(listAsiEx);
buildDigestAlg(body, listHashId); // 3 SET
buildContentInfo(body, attachSize); // 3 SEQ
if (chain != null) {
buildCerts(body, chain); // 3 CS
} else {
buildCertsASIE(body, listAsiEx); // 3 CS
}
// buildADRBSignerInfo(body, asiEx.getSignedHash(), asiEx.getX509(),
// asiEx.getOrigHash(), signPol.getPolicyHash(),
// asiEx.getCertHash(), asiEx.getSigningTime(),
// asiEx.getIdSha(), signPol.getPolicyUri(),
// signPol.getPolicyId(),
// signingCertFallback); // 3 SET
buildADRBSignerInfo(body, listAsiEx, signPol, signingCertFallback); // 3
// SET
whole.add(new DERTaggedObject(0, new DERSequence( // 2 SEQ
body))); // 1 CS
return genOutput(new DERSequence(whole));
}
private List<String> createHashList(List<AppSignedInfoEx> listAsiEx)
throws Exception {
List<String> ret = new ArrayList<String>();
for (AppSignedInfoEx next : listAsiEx) {
ret.add(getHashAlg(next.getIdSha()));
}
dedup(ret);
return ret;
}
private void dedup(List<String> list) {
Map<String, String> map = new HashMap<String, String>();
Iterator<String> it = list.iterator();
while (it.hasNext()) {
String next = it.next();
map.put(next, next);
}
list.clear();
for (String next : map.values()) {
list.add(next);
}
}
private byte[] genOutput(DERSequence whole) throws IOException {
final ByteArrayOutputStream bOut = new ByteArrayOutputStream();
final ASN1OutputStream dout = new ASN1OutputStream(bOut);
dout.writeObject(whole);
dout.close();
return bOut.toByteArray();
}
private void buildSignerInfo(ASN1EncodableVector body,
byte[] signedHashContent, X509Certificate certContent, int hashId)
throws Exception {
// ----- Signers Info --------
final ASN1EncodableVector vec = new ASN1EncodableVector();
final ASN1EncodableVector signerinfoVector = new ASN1EncodableVector();
signerinfoVector.add(new DERInteger(SI_VERSION));
signerinfoVector.add(siAddCert(certContent));
signerinfoVector.add(siAddDigestAlgorithm(getHashAlg(hashId)));
signerinfoVector
.add(siAddDigestEncryptionAlgorithm(getHashSignAlg(hashId)));
// Add the digest
signerinfoVector.add(new DEROctetString(signedHashContent));
final DERSequence siSeq = new DERSequence(signerinfoVector);
vec.add(siSeq);
DERSet siSet = new DERSet(vec);
body.add(siSet);
}
private void buildADRBSignerInfo(ASN1EncodableVector body,
List<AppSignedInfoEx> listAsiEx, SignPolicy signPol,
boolean signingCertFallback) throws Exception {
final ASN1EncodableVector vec = new ASN1EncodableVector();
// DERSequence siSeq = null;
// ----- Signers Info --------
for (AppSignedInfoEx next : listAsiEx) {
final ASN1EncodableVector signerinfoVector = new ASN1EncodableVector();
String hashId = getHashAlg(next.getIdSha());
String hashSignId = getHashSignAlg(next.getIdSha());
signerinfoVector.add(new DERInteger(SI_VERSION));
signerinfoVector.add(siAddCert(next.getX509()));
signerinfoVector.add(siAddDigestAlgorithm(hashId));
// der encoded structure
DERTaggedObject derEncStruct = adrbSiCreateDerEncSigned(
next.getOrigHash(), signPol.getPolicyHash(),
next.getCertHash(), next.getX509(), next.getSigningTime(),
next.getIdSha(), signPol.getPolicyUri(),
signPol.getPolicyId(), signingCertFallback);
signerinfoVector.add(derEncStruct);
signerinfoVector.add(siAddDigestEncryptionAlgorithm(hashSignId));
// Add the digest
signerinfoVector.add(new DEROctetString(next.getSignedHash()));
final DERSequence siSeq = new DERSequence(signerinfoVector);
vec.add(siSeq);
}
// ----- Signers Info --------
DERSet siSet = new DERSet(vec);
body.add(siSet);
}
// private void buildADRBSignerInfo(ASN1EncodableVector body,
// byte[] signedHashContent, X509Certificate certContent,
// byte[] origHash, byte[] polHash, byte[] certHash, Date now,
// int hashOption, String sigPolicyUri, String sigPolicyId,
// boolean signingCertFallback) throws Exception {
// String hashId = getHashAlg(hashOption);
// String hashSignId = getHashSignAlg(hashOption);
// // ----- Signers Info --------
//
// final ASN1EncodableVector vec = new ASN1EncodableVector();
// final ASN1EncodableVector signerinfoVector = new ASN1EncodableVector();
// signerinfoVector.add(new DERInteger(SI_VERSION));
//
// signerinfoVector.add(siAddCert(certContent));
// signerinfoVector.add(siAddDigestAlgorithm(hashId));
// // der encoded structure
// DERTaggedObject derEncStruct = adrbSiCreateDerEncSigned(origHash,
// polHash, certHash, certContent, now, hashOption, sigPolicyUri,
// sigPolicyId, signingCertFallback);
// signerinfoVector.add(derEncStruct);
//
// signerinfoVector.add(siAddDigestEncryptionAlgorithm(hashSignId));
// // Add the digest
// signerinfoVector.add(new DEROctetString(signedHashContent));
//
// final DERSequence siSeq = new DERSequence(signerinfoVector);
// vec.add(siSeq);
// DERSet siSet = new DERSet(vec);
// body.add(siSet);
//
// }
public DERTaggedObject adrbSiCreateDerEncSigned(byte[] origHash,
byte[] polHash, byte[] certHash, X509Certificate cert, Date now,
int hashId, String sigPolicyUri, String sigPolicyId,
boolean signingCertFallback) throws Exception {
DERSequence seq00 = siCreateDerEncSeqADRB(origHash, polHash, certHash,
cert, now, hashId, sigPolicyUri, sigPolicyId,
signingCertFallback);
DERTaggedObject derEncStruct = new DERTaggedObject(false, 0, seq00);
return derEncStruct;
}
public ASN1Set siCreateDerEncSignedADRB(byte[] origHash, byte[] polHash,
byte[] certHash, X509Certificate cert, Date now, int hashId,
String sigPolicyUri, String sigPolicyId, boolean signingCertFallback)
throws Exception {
DERSequence seq00 = siCreateDerEncSeqADRB(origHash, polHash, certHash,
cert, now, hashId, sigPolicyUri, sigPolicyId,
signingCertFallback);
ASN1Set retSet = new DERSet(seq00);
return retSet;
}
public ASN1Set siCreateDerEncSignedCMS3(byte[] origHash, byte[] certHash,
X509Certificate cert, Date now, String hashId)
throws CertificateEncodingException {
return null;
}
private DERSequence siCreateDerEncSeqADRB(byte[] origHash, byte[] polHash,
byte[] certHash, X509Certificate cert, Date now, int hashNdx,
String sigPolicyUri, String sigPolicyId, boolean signingCertFallback)
throws Exception {
String hashId = getHashAlg(hashNdx);
final ASN1EncodableVector desSeq = new ASN1EncodableVector();
// As assinaturas feitas segundo esta PA definem como obrigatorios as
// seguintes atributos
// assinados:
// a) id-contentType;
// b) id-messageDigest;
// c.1) Para as versoes 1.0, 1.1 e 2.0, id-aa-signingCertificate;
// c.2) A partir da versao 2.1, inclusive, id-aa-signingCertificateV2;
// d) id-aa-ets-sigPolicyId.
// OPTIONAL
// private static final String ID_SIGNING_TIME = "1.2.840.113549.1.9.5";
if (now != null) {
Attribute seq3 = createSigningTime(now);
desSeq.add(seq3);
}
// D
// private static final String ID_SIG_POLICY =
// "1.2.840.113549.1.9.16.2.15";
if (polHash != null && sigPolicyUri != null && sigPolicyId != null) {
Attribute seq2 = createPolicyId(polHash, hashId, sigPolicyUri,
sigPolicyId);
desSeq.add(seq2);
}
// C
// private static final String ID_SIGNING_CERT2 =
// "1.2.840.113549.1.9.16.2.47";
if (certHash != null && cert != null) {
Attribute seq1 = createCertRef(certHash, cert, signingCertFallback,
hashNdx);
desSeq.add(seq1);
}
// B
// private static final String ID_MESSAGE_DIGEST =
// "1.2.840.113549.1.9.4";
if (origHash != null) {
Attribute seq4 = createMessageDigest(origHash);
desSeq.add(seq4);
}
// A
// private static final String ID_CONTENT_TYPE = "1.2.840.113549.1.9.3";
Attribute seq5 = createContentType();
desSeq.add(seq5);
DERSequence seq00 = new DERSequence(desSeq);
return seq00;
}
private Attribute createContentType() {
// // final ASN1EncodableVector desSeq = new ASN1EncodableVector();
// // desSeq.add(new DERObjectIdentifier(ID_CONTENT_TYPE));
final ASN1EncodableVector setEV = new ASN1EncodableVector();
setEV.add(new DERObjectIdentifier(ID_PKCS7_DATA));
DERSet set = new DERSet(setEV);
// // desSeq.add(set);
// // DERSequence seq = new DERSequence(desSeq);
Attribute seq1 = new Attribute(
new ASN1ObjectIdentifier(ID_CONTENT_TYPE), set);
return seq1;
}
private Attribute createMessageDigest(byte[] origHash) {
final ASN1EncodableVector setEV = new ASN1EncodableVector();
setEV.add(new DEROctetString(origHash));
DERSet set = new DERSet(setEV);
Attribute seq1 = new Attribute(new ASN1ObjectIdentifier(
ID_MESSAGE_DIGEST), set);
return seq1;
}
private Attribute createSigningTime(Date now) {
final ASN1EncodableVector setEV = new ASN1EncodableVector();
setEV.add(new DERUTCTime(now));
DERSet set = new DERSet(setEV);
Attribute seq1 = new Attribute(
new ASN1ObjectIdentifier(ID_SIGNING_TIME), set);
return seq1;
}
private Attribute createPolicyId(byte[] polHash, String polHashAlg,
String sigPolicyUri, String sigPolicyId) {
final ASN1EncodableVector desSeq12 = new ASN1EncodableVector();
desSeq12.add(new DERObjectIdentifier(polHashAlg));
DERSequence seq12 = new DERSequence(desSeq12);
final ASN1EncodableVector desSeq1 = new ASN1EncodableVector();
desSeq1.add(seq12);
desSeq1.add(new DEROctetString(polHash));
DERSequence seq1 = new DERSequence(desSeq1);
// // end seq 1
// IGUALAR AO ITAU
final ASN1EncodableVector desSeq22 = new ASN1EncodableVector();
desSeq22.add(new DERObjectIdentifier(ID_SIG_POLICY_URI));
desSeq22.add(new DERIA5String(sigPolicyUri));
DERSequence seq22 = new DERSequence(desSeq22);
final ASN1EncodableVector desSeq2 = new ASN1EncodableVector();
desSeq2.add(seq22);
DERSequence seq2 = new DERSequence(desSeq2);
final ASN1EncodableVector aevDSet1 = new ASN1EncodableVector();
final ASN1EncodableVector aevDSeq1 = new ASN1EncodableVector();
aevDSeq1.add(new DERObjectIdentifier(sigPolicyId));
aevDSeq1.add(seq1);
aevDSeq1.add(seq2);
DERSequence dsq1 = new DERSequence(aevDSeq1);
aevDSet1.add(dsq1);
DERSet ds1 = new DERSet(aevDSet1);
Attribute ret = new Attribute(new ASN1ObjectIdentifier(ID_SIG_POLICY),
ds1);
return ret;
}
private Attribute createCertRef(byte[] certHash,
X509Certificate certContent, boolean signingCertFallback, int hashId)
throws Exception {
// *** BEGIN ***
// 5.2.1.1.3 Certificados Obrigatoriamente Referenciados
// O atributo signingCertificate deve conter referencia apenas ao
// certificado do signatario.
// 5.2.1.1.4 Certificados Obrigatorios do Caminho de Certificacao
// Para a versao 1.0: nenhum certificado
// Para as versoes 1.1, 2.0 e 2.1: o certificado do signatario.
// ESSCertIDv2 ::= SEQUENCE {
// hashAlgorithm AlgorithmIdentifier
// DEFAULT {algorithm id-sha256},
// certHash Hash,
// issuerSerial IssuerSerial OPTIONAL
// }
//
// Hash ::= OCTET STRING
//
// IssuerSerial ::= SEQUENCE {
// issuer GeneralNames,
// serialNumber CertificateSerialNumber
// }
final ASN1EncodableVector issuerSerialaev = new ASN1EncodableVector();
final ASN1EncodableVector issuerCertaev = new ASN1EncodableVector();
DERTaggedObject issuerName = new DERTaggedObject(true, 4, // issuer
// GeneralNames,
getEncodedIssuer(certContent.getTBSCertificate()));
// DERTaggedObject issuerName = new DERTaggedObject(false, 0, // issuer
// GeneralNames,
// getEncodedIssuer(certContent.getTBSCertificate()));
issuerCertaev.add(issuerName);
DERSequence issuerCertseq = new DERSequence(issuerCertaev); // IssuerSerial
// ::=
// SEQUENCE
// {
issuerSerialaev.add(issuerCertseq);
// serialNumber CertificateSerialNumber
BigInteger serialNumber = certContent.getSerialNumber();
issuerSerialaev.add(new DERInteger(serialNumber));
DERSequence issuerSerial = new DERSequence(issuerSerialaev);
// *** END ***
final ASN1EncodableVector essCertIDv2aev = new ASN1EncodableVector();
essCertIDv2aev.add(new DEROctetString(certHash)); // Hash ::= OCTET
// STRING
essCertIDv2aev.add(issuerSerial); // ESSCertIDv2 ::= SEQUENCE {
// hashAlgorithm AlgorithmIdentifier
if (!((signingCertFallback && hashId == NDX_SHA1) || (!signingCertFallback && hashId == NDX_SHA256))) {
DERObjectIdentifier hashAlgorithm = new DERObjectIdentifier(
getHashAlg(hashId));
essCertIDv2aev.add(hashAlgorithm);
}
// Nota 4: Para o atributo ESSCertIDv2, utilizada nas versoes 2.1 das
// politicas de assinatura
// baseadas em CAdES, as aplicacoes NaO DEVEM codificar o campo
// hashAlgorithm caso
// utilize o mesmo algoritmo definido como valor default (SHA-256),
// conforme ISO 8825-1.
DERSequence essCertIDv2seq = new DERSequence(essCertIDv2aev);
// ************************************************************************
//
final ASN1EncodableVector aevSeq3 = new ASN1EncodableVector();
aevSeq3.add(essCertIDv2seq);
DERSequence seq3 = new DERSequence(aevSeq3);
final ASN1EncodableVector aevSeq2 = new ASN1EncodableVector();
aevSeq2.add(seq3);
DERSequence seq2 = new DERSequence(aevSeq2);
final ASN1EncodableVector aevSet = new ASN1EncodableVector();
aevSet.add(seq2);
ASN1Set mainSet = new DERSet(aevSet);
Attribute seq1 = new Attribute(new ASN1ObjectIdentifier(
signingCertFallback ? ID_SIGNING_CERT : ID_SIGNING_CERT2),
mainSet);
return seq1;
}
private void buildSignerInfo(ASN1EncodableVector body,
String signedHashContent, X509Certificate certContent, String hashId)
throws CertificateEncodingException {
// ----- Signers Info --------
final ASN1EncodableVector vec = new ASN1EncodableVector();
final ASN1EncodableVector signerinfoVector = new ASN1EncodableVector();
signerinfoVector.add(new DERInteger(SI_VERSION)); // 5 INT
signerinfoVector.add(siAddCert(certContent));
signerinfoVector.add(siAddDigestAlgorithm(hashId));
signerinfoVector.add(siAddDigestEncryptionAlgorithm(ID_SHA1_RSA)); // 6
// OCT
// STR
// Add the digest
signerinfoVector.add(new DEROctetString(
getDerSignedDigest(signedHashContent)));
final DERSequence siSeq = new DERSequence(signerinfoVector); // 4 SEQ
vec.add(siSeq);
DERSet siSet = new DERSet(vec); // 3 SET
body.add(siSet);
}
private byte[] getDerSignedDigest(String signedHashContent) {
byte[] ret = Base64.decode(signedHashContent);
return ret;
}
private DERSequence siAddDigestEncryptionAlgorithm(String hashId) {
// Nota 3: Em atencao aa RFC 3370 (Cryptographic Message Syntax (CMS)
// Algorithms), item
// "2.1 SHA-1"; e RFC 5754 (Using SHA2 Algorithms with Cryptographic
// Message Syntax),
// item "2 - Message Digest Algorithms", recomenda-se a ausencia do
// campo "parameters" na
// estrutura "AlgorithmIdentifier", usada na indicacao do algoritmo de
// hash, presentes nas
// estruturas ASN.1 "SignedData.digestAlgorithms",
// "SignerInfo.digestAlgorithm" e
// "SignaturePolicyId.sigPolicyHash.hashAlgorithm".
// AlgorithmIdentifier ::= SEQUENCE {
// algorithm OBJECT IDENTIFIER,
// parameters ANY DEFINED BY algorithm OPTIONAL }
// Os processos para criacao e verificacao de assinaturas segundo esta
// PA devem utilizar o
// algoritmo :
// a) para a versao 1.0: sha1withRSAEncryption(1 2 840 113549 1 1 5),
// b) para a versao 1.1: sha1withRSAEncryption(1 2 840 113549 1 1 5) ou
// sha256WithRSAEncryption(1.2.840.113549.1.1.11)
// c) para as versoes 2.0 e 2.1:
// sha256WithRSAEncryption(1.2.840.113549.1.1.11).
ASN1EncodableVector digestEncVetor = new ASN1EncodableVector();
digestEncVetor.add(new DERObjectIdentifier(hashId));
// VER NOTA
// digestEncVetor.add(new DERNull());
return new DERSequence(digestEncVetor);
}
private DERSequence siAddDigestAlgorithm(String hashId) {
// Add the digestEncAlgorithm
ASN1EncodableVector digestVetor = new ASN1EncodableVector();
digestVetor.add(new DERObjectIdentifier(hashId)); // 6 OID
digestVetor.add(new DERNull()); // 6 NULL
return new DERSequence(digestVetor); // 5 SEQ
}
private DERSequence siAddCert(X509Certificate certContent)
throws CertificateEncodingException {
ASN1EncodableVector certVetor = new ASN1EncodableVector();
certVetor.add(getEncodedIssuer(certContent.getTBSCertificate())); // 6
// ISSUER
certVetor.add(new DERInteger(certContent.getSerialNumber())); // 6 INT -
// SERIAL
return (new DERSequence(certVetor)); // 5 SEQ
}
private static DLSequence getEncodedIssuer(final byte[] enc) {
try {
final ASN1InputStream in = new ASN1InputStream(
new ByteArrayInputStream(enc));
final ASN1Sequence seq = (ASN1Sequence) in.readObject();
return (DLSequence) seq
.getObjectAt(seq.getObjectAt(0) instanceof DERTaggedObject ? 3
: 2);
} catch (final IOException e) {
return null;
}
}
private void buildCertsASIE(ASN1EncodableVector body,
List<AppSignedInfoEx> listAsiEx)
throws CertificateEncodingException, IOException {
List<X509Certificate> chain = new ArrayList<X509Certificate>();
for (AppSignedInfoEx next : listAsiEx) {
chain.add(next.getX509());
}
buildCerts(body, chain);
}
private void buildCerts(ASN1EncodableVector body,
List<X509Certificate> chain) throws IOException,
CertificateEncodingException {
// -------- Certificados
ASN1EncodableVector certVector = new ASN1EncodableVector();
for (X509Certificate next : chain) {
ASN1InputStream tempstream = new ASN1InputStream(
new ByteArrayInputStream(next.getEncoded()));
certVector.add(tempstream.readObject()); // 5 CERT (SEQ)
}
final DERSet dercertificates = new DERSet(certVector); // 4 SET
body.add(new DERTaggedObject(false, 0, dercertificates)); // 3 CS
}
private void buildCerts(ASN1EncodableVector body,
X509Certificate certContent) throws IOException,
CertificateEncodingException {
// -------- Certificados
ASN1EncodableVector certVector = new ASN1EncodableVector();
ASN1InputStream tempstream = new ASN1InputStream(
new ByteArrayInputStream(certContent.getEncoded()));
certVector.add(tempstream.readObject()); // 5 CERT (SEQ)
final DERSet dercertificates = new DERSet(certVector); // 4 SET
body.add(new DERTaggedObject(false, 0, dercertificates)); // 3 CS
}
private void buildContentInfo(final ASN1EncodableVector body, int size) {
// ------ Content Info
ASN1EncodableVector contentInfoVector = new ASN1EncodableVector();
contentInfoVector.add(new DERObjectIdentifier(ID_PKCS7_DATA)); // 4 OID
if (size != DETACHED) {
byte[] content = new byte[size];
for (int i = 0; i < size; i++) {
content[i] = (byte) 0xba;
}
contentInfoVector.add(new DERTaggedObject(0, new DEROctetString(
content)));
}
// CONTENT INFO
final DERSequence contentinfo = new DERSequence(contentInfoVector); // 3
// SEQ
body.add(contentinfo);
}
private void buildDigestAlg(final ASN1EncodableVector body, String hashId) {
// ---------- algoritmos de digest
final ASN1EncodableVector algos = new ASN1EncodableVector();
algos.add(new DERObjectIdentifier(hashId)); // 4 OID
algos.add(new DERNull()); // 4 NULL
final ASN1EncodableVector algoSet = new ASN1EncodableVector();
algoSet.add(new DERSequence(algos));
final DERSet digestAlgorithms = new DERSet(algoSet); // 2
// SET
body.add(digestAlgorithms);
}
private void buildDigestAlg(final ASN1EncodableVector body,
List<String> listHashId) {
// ---------- algoritmos de digest
final ASN1EncodableVector algos = new ASN1EncodableVector();
for (String next : listHashId) {
algos.add(new DERObjectIdentifier(next)); // 4 OID
algos.add(new DERNull()); // 4 NULL
}
final ASN1EncodableVector algoSet = new ASN1EncodableVector();
algoSet.add(new DERSequence(algos));
final DERSet digestAlgorithms = new DERSet(algoSet); // 2
// SET
body.add(digestAlgorithms);
}
public static String getHashAlg(int hash) throws Exception {
String ret = "";
switch (hash) {
case NDX_SHA1:
ret = ID_SHA1;
break;
case NDX_SHA224:
ret = ID_SHA1;
break;
case NDX_SHA256:
ret = ID_SHA256;
break;
case NDX_SHA384:
ret = ID_SHA384;
break;
case NDX_SHA512:
ret = ID_SHA512;
break;
default:
throw new Exception("hash alg nao identificado:" + hash);
}
return ret;
}
private String getHashSignAlg(int hash) throws Exception {
String ret = "";
switch (hash) {
case NDX_SHA1:
ret = ID_SHA1_RSA;
break;
case NDX_SHA224:
ret = ID_SHA1_RSA;
break;
case NDX_SHA256:
ret = ID_SHA256_RSA;
break;
case NDX_SHA384:
ret = ID_SHA384_RSA;
break;
case NDX_SHA512:
ret = ID_SHA512_RSA;
break;
default:
throw new Exception("hash alg nao identificado:" + hash);
// break;
}
return ret;
}
// capicom service
public static String extractHashId(byte[] sign) throws Exception {
String ret = null;
ASN1InputStream is = new ASN1InputStream(new ByteArrayInputStream(sign));
ASN1Primitive topLevel = is.readObject();
LOG.trace("top level:" + topLevel.getClass().getName());
if (topLevel instanceof org.bouncycastle.asn1.DLSequence) {
DLSequence topLevelDLS = (DLSequence) topLevel;
if (topLevelDLS.size() == 2) {
ASN1Encodable level1 = topLevelDLS.getObjectAt(1);
LOG.trace("level1:"
+ level1.getClass().getName());
if (level1 instanceof org.bouncycastle.asn1.DERTaggedObject) {
DERTaggedObject level1TO = (DERTaggedObject) level1;
ASN1Primitive level2 = level1TO.getObject();
LOG.trace("level2:"
+ level2.getClass().getName());
if (level2 instanceof org.bouncycastle.asn1.DERSequence) {
DERSequence level2DS = (DERSequence) level2;
LOG.trace("level2 len:"
+ level2DS.size());
ASN1Encodable level3_1 = level2DS.getObjectAt(1);
LOG.trace("level3_1:"
+ level3_1.getClass().getName());
if (level3_1 instanceof org.bouncycastle.asn1.DERSet) {
DERSet level3_1Set = (DERSet) level3_1;
ASN1Encodable level4_1 = level3_1Set.getObjectAt(0);
LOG.trace("level4_1:"
+ level4_1.getClass().getName());
if (level4_1 instanceof org.bouncycastle.asn1.DERSequence) {
DERSequence level4_1Seq = (DERSequence) level4_1;
ASN1Encodable level5_0 = level4_1Seq.getObjectAt(0);
LOG.trace("level5_0:"
+ level5_0.getClass().getName());
if (level5_0 instanceof org.bouncycastle.asn1.ASN1ObjectIdentifier) {
ASN1ObjectIdentifier level5_0Seq = (ASN1ObjectIdentifier) level5_0;
LOG.trace(level5_0Seq.toString());
ret = level5_0Seq.toString();
} else {
throw new Exception("DER enconding error");
}
} else {
throw new Exception("DER enconding error");
}
} else {
throw new Exception("DER enconding error");
}
} else {
throw new Exception("DER enconding error");
}
} else {
throw new Exception("DER enconding error");
}
} else {
throw new Exception("DER enconding error");
}
} else {
throw new Exception("DER enconding error");
}
return ret;
}
public static byte[] extractSignature(byte[] sign) throws Exception {
byte[] ret = null;
ASN1InputStream is = new ASN1InputStream(new ByteArrayInputStream(sign));
ASN1Primitive topLevel = is.readObject();
LOG.trace("top level:"
+ topLevel.getClass().getName());
if (topLevel instanceof org.bouncycastle.asn1.DLSequence) {
DLSequence topLevelDLS = (DLSequence) topLevel;
if (topLevelDLS.size() == 2) {
ASN1Encodable level1 = topLevelDLS.getObjectAt(1);
LOG.trace("level1:"
+ level1.getClass().getName());
if (level1 instanceof org.bouncycastle.asn1.DERTaggedObject) {
DERTaggedObject level1TO = (DERTaggedObject) level1;
ASN1Primitive level2 = level1TO.getObject();
LOG.trace("level2:"
+ level2.getClass().getName());
if (level2 instanceof org.bouncycastle.asn1.DERSequence) {
DERSequence level2DS = (DERSequence) level2;
LOG.trace("level2 len:"
+ level2DS.size());
ASN1Encodable level3_4 = level2DS.getObjectAt(level2DS
.size() - 1);
LOG.trace("level3_4:"
+ level3_4.getClass().getName());
if (level3_4 instanceof org.bouncycastle.asn1.DERSet) {
DERSet level3_4DS = (DERSet) level3_4;
ASN1Encodable level3_4_0 = level3_4DS
.getObjectAt(0);
LOG.trace("level3_4_0:"
+ level3_4_0.getClass().getName());
if (level3_4_0 instanceof org.bouncycastle.asn1.DERSequence) {
DERSequence level3_4_0DS = (DERSequence) level3_4_0;
LOG.trace("level3_4_0DS len:"
+ level3_4_0DS.size());
ASN1Encodable signature = level3_4_0DS
.getObjectAt(level3_4_0DS.size() - 1);
LOG.trace("signature:"
+ signature.getClass().getName());
if (signature instanceof org.bouncycastle.asn1.DEROctetString) {
DEROctetString signDOS = (DEROctetString) signature;
ret = signDOS.getOctets();
}
} else {
throw new Exception("DER enconding error");
}
} else {
throw new Exception("DER enconding error");
}
} else {
throw new Exception("DER enconding error");
}
} else {
throw new Exception("DER enconding error");
}
} else {
throw new Exception("DER enconding error");
}
} else {
throw new Exception("DER enconding error");
}
return ret;
}
public static DERTaggedObject extractDTOSignPolicyOid(byte[] sign,
SignCompare signCompare) throws Exception {
DERTaggedObject ret = null;
ASN1InputStream is = new ASN1InputStream(new ByteArrayInputStream(sign));
ASN1Primitive topLevel = is.readObject();
LOG.trace("top level:"
+ topLevel.getClass().getName());
if (topLevel instanceof org.bouncycastle.asn1.DLSequence) {
DLSequence topLevelDLS = (DLSequence) topLevel;
if (topLevelDLS.size() == 2) {
ASN1Encodable level1 = topLevelDLS.getObjectAt(1);
LOG.trace("level1:"
+ level1.getClass().getName());
if (level1 instanceof org.bouncycastle.asn1.DERTaggedObject) {
DERTaggedObject level1TO = (DERTaggedObject) level1;
ASN1Primitive level2 = level1TO.getObject();
LOG.trace("level2:"
+ level2.getClass().getName());
if (level2 instanceof org.bouncycastle.asn1.DERSequence) {
DERSequence level2DS = (DERSequence) level2;
LOG.trace("level2 len:"
+ level2DS.size());
signCompare.setNumCerts(extractCertCount(level2DS));
ret = extractSignedAttributes(level2DS);
} else {
throw new Exception("DER enconding error");
}
} else {
throw new Exception("DER enconding error");
}
} else {
throw new Exception("DER enconding error");
}
} else {
throw new Exception("DER enconding error");
}
return ret;
}
private static void saveDebug(byte[] sign) {
String x = "C:\\Users\\sergio.fonseca\\iniciativas\\bluecrystal\\temp\\sign.bin";
try {
OutputStream os = new FileOutputStream(x);
os.write(sign);
os.close();
} catch (Exception e) {
// TODO: handle exception
}
}
public static void extractSignCompare2(byte[] sign,
SignCompare2 signCompare) throws Exception {
saveDebug(sign);
DERTaggedObject ret = null;
ASN1InputStream is = new ASN1InputStream(new ByteArrayInputStream(sign));
ASN1Primitive topLevel = is.readObject();
LOG.trace("top level:"
+ topLevel.getClass().getName());
if (topLevel instanceof org.bouncycastle.asn1.DLSequence) {
DLSequence topLevelDLS = (DLSequence) topLevel;
if (topLevelDLS.size() == 2) {
ASN1Encodable level1 = topLevelDLS.getObjectAt(1);
LOG.trace("level1:"
+ level1.getClass().getName());
if (level1 instanceof org.bouncycastle.asn1.DERTaggedObject) {
DERTaggedObject level1TO = (DERTaggedObject) level1;
ASN1Primitive level2 = level1TO.getObject();
LOG.trace("level2:"
+ level2.getClass().getName());
if (level2 instanceof org.bouncycastle.asn1.DERSequence) {
DERSequence level2DS = (DERSequence) level2;
LOG.trace("level2 len:"
+ level2DS.size());
signCompare.setNumCerts(extractCertCount(level2DS));
ret = extractSignedAttributes(level2DS);
} else {
throw new Exception("DER enconding error");
}
} else {
throw new Exception("DER enconding error");
}
} else {
throw new Exception("DER enconding error");
}
} else {
throw new Exception("DER enconding error");
}
// return ret;
}
public static List<byte[]> extractCertList(byte[] sign) throws Exception {
List<byte[]> ret = null;
ASN1InputStream is = new ASN1InputStream(new ByteArrayInputStream(sign));
ASN1Primitive topLevel = is.readObject();
LOG.trace("top level:"
+ topLevel.getClass().getName());
if (topLevel instanceof org.bouncycastle.asn1.DLSequence) {
DLSequence topLevelDLS = (DLSequence) topLevel;
if (topLevelDLS.size() == 2) {
ASN1Encodable level1 = topLevelDLS.getObjectAt(1);
LOG.trace("level1:"
+ level1.getClass().getName());
if (level1 instanceof org.bouncycastle.asn1.DERTaggedObject) {
DERTaggedObject level1TO = (DERTaggedObject) level1;
ASN1Primitive level2 = level1TO.getObject();
LOG.trace("level2:"
+ level2.getClass().getName());
if (level2 instanceof org.bouncycastle.asn1.DERSequence) {
DERSequence level2DS = (DERSequence) level2;
LOG.trace("level2 len:"
+ level2DS.size());
ret = extractCertArray(level2DS);
} else {
throw new Exception("DER enconding error");
}
} else {
throw new Exception("DER enconding error");
}
} else {
throw new Exception("DER enconding error");
}
} else {
throw new Exception("DER enconding error");
}
return ret;
}
public static int extractCertCount(DERSequence certTree) {
ASN1Encodable level0 = getAt(certTree, 3);
if (level0 instanceof DERTaggedObject) {
DERTaggedObject level0Tag = (DERTaggedObject) level0;
ASN1Encodable level0Obj = level0Tag.getObject();
if (level0Obj instanceof DERSequence) {
DERSequence level0Seq = (DERSequence) level0Obj;
return 1;
} else if (level0Obj instanceof DLSequence) {
DLSequence level0Seq = (DLSequence) level0Obj;
return level0Seq.size();
}
}
return certTree.size();
}
public static List<byte[]> extractCertArray(DERSequence certTree) {
List<byte[]> ret = new ArrayList<byte[]>();
ASN1Encodable level0 = getAt(certTree, 3);
if (level0 instanceof DERTaggedObject) {
DERTaggedObject level0Tag = (DERTaggedObject) level0;
ASN1Encodable level0Obj = level0Tag.getObject();
if (level0Obj instanceof DERSequence) {
try {
DERSequence level0Seq = (DERSequence) level0Obj;
if (level0Seq.getObjectAt(2) instanceof DERBitString) {
// achei o certificado
byte[] b = level0Seq.getEncoded();
ret.add(b);
} else {
for (int i = 0; i < level0Seq.size(); i++) {
ASN1Encodable objNdx = level0Seq.getObjectAt(i);
if (objNdx instanceof DERSequence) {
try {
DERSequence objNdx2 = (DERSequence) objNdx;
byte[] b = objNdx2.getEncoded();
ret.add(b);
} catch (IOException e) {
LOG.error("DER decoding error", e);
}
}
}
}
} catch (IOException e) {
LOG.error("DER decoding error", e);
}
} else if (level0Obj instanceof ASN1Sequence) {
ASN1Sequence level0Seq = (ASN1Sequence) level0Obj;
for (int i = 0; i < level0Seq.size(); i++) {
ASN1Encodable objNdx = level0Seq.getObjectAt(i);
if (objNdx instanceof DERSequence) {
try {
DERSequence objNdx2 = (DERSequence) objNdx;
byte[] b = objNdx2.getEncoded();
ret.add(b);
} catch (IOException e) {
LOG.error("DER decoding error", e);
}
}
}
}
}
return ret;
}
public static DERTaggedObject extractSignedAttributes(DERSequence level2DS)
throws Exception {
DERTaggedObject ret = null;
ASN1Encodable level3_4 = level2DS.getObjectAt(level2DS.size() - 1);
LOG.trace("level3_4:"
+ level3_4.getClass().getName());
if (level3_4 instanceof org.bouncycastle.asn1.DERSet) {
DERSet level3_4DS = (DERSet) level3_4;
ASN1Encodable level3_4_0 = level3_4DS.getObjectAt(0);
LOG.trace("level3_4_0:"
+ level3_4_0.getClass().getName());
if (level3_4_0 instanceof org.bouncycastle.asn1.DERSequence) {
DERSequence level3_4_0DS = (DERSequence) level3_4_0;
LOG.trace("level3_4_0DS len:"
+ level3_4_0DS.size());
ASN1Encodable signedAttribs = level3_4_0DS.getObjectAt(3);
LOG.trace("signature:"
+ signedAttribs.getClass().getName());
if (signedAttribs instanceof org.bouncycastle.asn1.DERTaggedObject) {
DERTaggedObject signedAttribsDTO = (DERTaggedObject) signedAttribs;
ret = signedAttribsDTO;
// trata busca da Policy OID
} else if (signedAttribs instanceof org.bouncycastle.asn1.DERSequence) {
ret = null;
} else {
throw new Exception("DER enconding error");
}
} else {
throw new Exception("DER enconding error");
}
} else {
throw new Exception("DER enconding error");
}
return ret;
}
public static void extractSignPolicyRefFromSignedAttrib(
DERTaggedObject signedAttribsDTO, SignCompare signCompare)
throws Exception {
// String SignCompare = null;
ASN1Primitive dtoObj = signedAttribsDTO.getObject();
if (dtoObj instanceof DLSequence) {
DLSequence topSeq = (DLSequence) dtoObj;
List<String> signedAttribOid = new ArrayList<String>();
signCompare.setSignedAttribs(signedAttribOid);
for (int i = 0; i < topSeq.size(); i++) {
// treat each SIGNED ATTRIBUTE
ASN1Encodable objL1 = topSeq.getObjectAt(i);
if (objL1 instanceof DERSequence) {
DERSequence seqL1 = (DERSequence) objL1;
ASN1Encodable objL2 = seqL1.getObjectAt(0);
if (objL2 instanceof ASN1ObjectIdentifier) {
ASN1ObjectIdentifier saOid = (ASN1ObjectIdentifier) objL2;
String saOIdStr = saOid.toString();
// System.out.println(saOIdStr);
signedAttribOid.add(saOIdStr);
if (saOIdStr.compareTo(DerEncoder.ID_SIG_POLICY) == 0) {
ASN1Encodable objL21 = seqL1.getObjectAt(1);
if (objL21 instanceof DERSet) {
DERSet objL21Set = (DERSet) objL21;
ASN1Encodable objL3 = objL21Set.getObjectAt(0);
if (objL3 instanceof DERSequence) {
DERSequence objL3Seq = (DERSequence) objL3;
ASN1Encodable objL4 = objL3Seq
.getObjectAt(0);
if (objL4 instanceof ASN1ObjectIdentifier) {
ASN1ObjectIdentifier objL4Oid = (ASN1ObjectIdentifier) objL4;
signCompare.setPsOid(objL4Oid
.toString());
}
ASN1Encodable objL42 = getAt(objL3Seq, 2);
if (objL42 instanceof DERSequence) {
DERSequence objL42DerSeq = (DERSequence) objL42;
ASN1Encodable objL420 = getAt(
objL42DerSeq, 0);
if (objL420 instanceof DERSequence) {
DERSequence objL420DerSeq = (DERSequence) objL420;
ASN1Encodable psUrl = getAt(
objL420DerSeq, 1);
if (psUrl instanceof DERIA5String) {
DERIA5String psUrlIA5 = (DERIA5String) psUrl;
signCompare.setPsUrl(psUrlIA5
.getString());
}
}
}
}
}
} else if (saOIdStr
.compareTo(DerEncoder.ID_SIGNING_TIME) == 0) {
ASN1Encodable objL2SetTime = seqL1.getObjectAt(1);
if (objL2SetTime instanceof DERSet) {
DERSet objL2SetTimeDer = (DERSet) objL2SetTime;
ASN1Encodable objL2SignTime = objL2SetTimeDer
.getObjectAt(0);
if (objL2SignTime instanceof ASN1UTCTime) {
ASN1UTCTime objL2SignTimeUTC = (ASN1UTCTime) objL2SignTime;
signCompare.setSigningTime(objL2SignTimeUTC
.getDate());
}
}
}
}
}
}
}
}
public static SignPolicyRef extractVerifyRefence(byte[] policy)
throws IOException, ParseException {
SignPolicyRef ret = new SignPolicyRef();
ASN1InputStream is = new ASN1InputStream(new ByteArrayInputStream(
policy));
ASN1Primitive topLevel = is.readObject();
// SignaturePolicy ::= SEQUENCE {
// signPolicyHashAlg AlgorithmIdentifier,
// signPolicyInfo SignPolicyInfo,
// signPolicyHash SignPolicyHash OPTIONAL }
if (topLevel instanceof DLSequence) {
DLSequence topLevelDLS = (DLSequence) topLevel;
ASN1Encodable dseqL10 = topLevelDLS.getObjectAt(0);
ASN1Encodable psHashAlg = null;
if (dseqL10 instanceof DLSequence) {
DLSequence dseqL10DLS = (DLSequence) dseqL10;
psHashAlg = dseqL10DLS.getObjectAt(0);
} else if (dseqL10 instanceof ASN1ObjectIdentifier){
psHashAlg = (ASN1ObjectIdentifier) dseqL10;
} else return null;
if (psHashAlg instanceof ASN1ObjectIdentifier) {
ASN1ObjectIdentifier psHashAlgOid = (ASN1ObjectIdentifier) psHashAlg;
ret.setPsHashAlg(psHashAlgOid.toString());
}
ASN1Encodable dseqL11 = topLevelDLS.getObjectAt(1);
if (dseqL11 instanceof DLSequence) {
// SignPolicyInfo ::= SEQUENCE {
DLSequence dseqL11DLS = (DLSequence) dseqL11;
ASN1Encodable psOid = dseqL11DLS.getObjectAt(0);
// signPolicyIdentifier SignPolicyId,
// 2.16.76.1.7.1.6.2.1
if (psOid instanceof ASN1ObjectIdentifier) {
ASN1ObjectIdentifier psOidOid = (ASN1ObjectIdentifier) psOid;
ret.setPsOid(psOidOid.toString());
}
ASN1Encodable dateOfIssue = dseqL11DLS.getObjectAt(1);
// dateOfIssue GeneralizedTime,
// 2012-03-22
if (dateOfIssue instanceof ASN1GeneralizedTime) {
ASN1GeneralizedTime dateOfIssueGT = (ASN1GeneralizedTime) dateOfIssue;
ret.setDateOfIssue(dateOfIssueGT.getDate());
}
ASN1Encodable policyIssuerName = dseqL11DLS.getObjectAt(2);
// policyIssuerName PolicyIssuerName,
// C=BR, O=ICP-Brasil, OU=Instituto Nacional de Tecnologia da
// Informacao
// - ITI
if (policyIssuerName instanceof DLSequence) {
DLSequence policyIssuerNameDLSeq = (DLSequence) policyIssuerName;
ASN1Encodable policyIssuerName2 = policyIssuerNameDLSeq
.getObjectAt(0);
if (policyIssuerName2 instanceof DERTaggedObject) {
DERTaggedObject policyIssuerName2DTO = (DERTaggedObject) policyIssuerName2;
ASN1Primitive polIssuerNameObj = policyIssuerName2DTO
.getObject();
if (polIssuerNameObj instanceof DEROctetString) {
String polIssuerNameStr = new String(
((DEROctetString) polIssuerNameObj)
.getOctets());
ret.setPolIssuerName(polIssuerNameStr);
}
}
}
ASN1Encodable fieldOfApplication = dseqL11DLS.getObjectAt(3);
// fieldOfApplication FieldOfApplication,
// Este tipo de assinatura deve ser utilizado em aplicacoes ou
// processos
// de negocio nos quais a assinatura digital agrega seguranca a
// autenticacao de entidades e verificacao de integridade,
// permitindo
// sua validacao durante o prazo de, validade dos certificados
// dos
// signatarios. Uma vez que nao sao usados carimbos do tempo, a
// validacao posterior so sera possivel se existirem referencias
// temporais que identifiquem o momento em que ocorreu a
// assinatura
// digital. Nessas situacoes, deve existir legislacao especifica
// ou um
// acordo previo entre as partes definindo as referencias a
// serem
// utilizadas. Segundo esta PA, e permitido o emprego de
// multiplas
// assinaturas.
if (fieldOfApplication instanceof DEROctetString) {
DERUTF8String fieldOfApplicationDUS = (DERUTF8String) fieldOfApplication;
ret.setFieldOfApplication(fieldOfApplicationDUS.getString());
}
// signatureValidationPolicy SignatureValidationPolicy,
// signPolExtensions SignPolExtensions OPTIONAL
// SignatureValidationPolicy ::= SEQUENCE {
ASN1Encodable signatureValidationPolicy = dseqL11DLS
.getObjectAt(4);
if (signatureValidationPolicy instanceof DLSequence) {
DLSequence signatureValidationPolicyDLS = (DLSequence) signatureValidationPolicy;
// signingPeriod SigningPeriod,
// NotBefore 2012-03-22
// NotAfter 2023-06-21
ASN1Encodable signingPeriod = signatureValidationPolicyDLS
.getObjectAt(0);
if (signingPeriod instanceof DLSequence) {
DLSequence signingPeriodDLS = (DLSequence) signingPeriod;
ASN1Encodable notBefore = signingPeriodDLS
.getObjectAt(0);
if (notBefore instanceof ASN1GeneralizedTime) {
ASN1GeneralizedTime notBeforeAGT = (ASN1GeneralizedTime) notBefore;
ret.setNotBefore(notBeforeAGT.getDate());
}
ASN1Encodable notAfter = signingPeriodDLS
.getObjectAt(1);
if (notAfter instanceof ASN1GeneralizedTime) {
ASN1GeneralizedTime notAfterAGT = (ASN1GeneralizedTime) notAfter;
ret.setNotAfter(notAfterAGT.getDate());
}
}
//
// commonRules CommonRules,
ASN1Encodable commonRules = getAt(
signatureValidationPolicyDLS, 1);
if (commonRules instanceof DLSequence) {
DLSequence commonRulesDLS = (DLSequence) commonRules;
// CommonRules ::= SEQUENCE {
// signerAndVeriferRules [0] SignerAndVerifierRules
// OPTIONAL,
// signingCertTrustCondition [1]
// SigningCertTrustCondition OPTIONAL,
// timeStampTrustCondition [2] TimestampTrustCondition
// OPTIONAL,
// attributeTrustCondition [3] AttributeTrustCondition
// OPTIONAL,
// algorithmConstraintSet [4] AlgorithmConstraintSet
// OPTIONAL,
// signPolExtensions [5] SignPolExtensions OPTIONAL
// }
ASN1Encodable signerAndVeriferRules = getAt(
commonRulesDLS, 0);
// SignerAndVerifierRules ::= SEQUENCE {
// signerRules SignerRules,
// verifierRules VerifierRules }
if (signerAndVeriferRules instanceof DERTaggedObject) {
DERTaggedObject signerAndVeriferRulesDTO = (DERTaggedObject) signerAndVeriferRules;
ASN1Encodable signerAndVeriferRulesTmp = signerAndVeriferRulesDTO
.getObject();
if (signerAndVeriferRulesTmp instanceof DERSequence) {
DERSequence signerAndVeriferRulesDERSeq = (DERSequence) signerAndVeriferRulesTmp;
ASN1Encodable signerRules = getAt(
signerAndVeriferRulesDERSeq, 0);
if (signerRules instanceof DERSequence) {
DERSequence signerRulesDERSeq = (DERSequence) signerRules;
// SignerRules ::= SEQUENCE {
// externalSignedData BOOLEAN OPTIONAL,
// -- True if signed data is external to CMS
// structure
// -- False if signed data part of CMS
// structure
// -- not present if either allowed
// mandatedSignedAttr CMSAttrs,
// -- Mandated CMS signed attributes
// 1.2.840.113549.1.9.3
// 1.2.840.113549.1.9.4
// 1.2.840.113549.1.9.16.2.15
// 1.2.840.113549.1.9.16.2.47
// mandatedUnsignedAttr CMSAttrs,
// <empty sequence>
// -- Mandated CMS unsigned attributed
// mandatedCertificateRef [0] CertRefReq
// DEFAULT signerOnly,
// (1)
// -- Mandated Certificate Reference
// mandatedCertificateInfo [1] CertInfoReq
// DEFAULT none,
// -- Mandated Certificate Info
// signPolExtensions [2] SignPolExtensions
// OPTIONAL}
// CMSAttrs ::= SEQUENCE OF OBJECT
// IDENTIFIER
ASN1Encodable mandatedSignedAttr = getAt(
signerRulesDERSeq, 0);
if (mandatedSignedAttr instanceof DERSequence) {
DERSequence mandatedSignedAttrDERSeq = (DERSequence) mandatedSignedAttr;
for (int i = 0; i < mandatedSignedAttrDERSeq
.size(); i++) {
ASN1Encodable at = getAt(
mandatedSignedAttrDERSeq, i);
ret.addMandatedSignedAttr(at
.toString());
}
}
ASN1Encodable mandatedUnsignedAttr = getAt(
signerRulesDERSeq, 1);
if (mandatedUnsignedAttr instanceof DERSequence) {
DERSequence mandatedUnsignedAttrDERSeq = (DERSequence) mandatedUnsignedAttr;
}
ASN1Encodable mandatedCertificateRef = getAt(
signerRulesDERSeq, 2);
if (mandatedCertificateRef instanceof DERTaggedObject) {
DERTaggedObject mandatedCertificateRefDERSeq = (DERTaggedObject) mandatedCertificateRef;
// CertRefReq ::= ENUMERATED {
// signerOnly (1),
// -- Only reference to signer cert
// mandated
// fullpath (2)
//
// -- References for full cert path up
// to a trust point required
// }
ASN1Encodable mandatedCertificateRefTmp = mandatedCertificateRefDERSeq
.getObject();
ASN1Enumerated mandatedCertificateRefEnum = (ASN1Enumerated) mandatedCertificateRefTmp;
BigInteger valEnum = mandatedCertificateRefEnum
.getValue();
int mandatedCertificateRefInt = valEnum
.intValue();
ret.setMandatedCertificateRef(mandatedCertificateRefInt);
int x = 0;
}
}
ASN1Encodable verifierRules = getAt(
signerAndVeriferRulesDERSeq, 1);
if (verifierRules instanceof DERSequence) {
DERSequence verifierRulesDERSeq = (DERSequence) verifierRules;
}
}
}
ASN1Encodable signingCertTrustCondition = getAt(
commonRulesDLS, 1);
if (signingCertTrustCondition instanceof DERTaggedObject) {
DERTaggedObject signingCertTrustConditionDTO = (DERTaggedObject) signingCertTrustCondition;
ASN1Encodable signingCertTrustConditionTmp = signingCertTrustConditionDTO
.getObject();
if (signingCertTrustConditionTmp instanceof DERSequence) {
DERSequence signingCertTrustConditionDERSeq = (DERSequence) signingCertTrustConditionTmp;
}
}
ASN1Encodable timeStampTrustCondition = getAt(
commonRulesDLS, 2);
if (timeStampTrustCondition instanceof DERTaggedObject) {
DERTaggedObject timeStampTrustConditionDTO = (DERTaggedObject) timeStampTrustCondition;
ASN1Encodable timeStampTrustConditionTmp = timeStampTrustConditionDTO
.getObject();
if (timeStampTrustConditionTmp instanceof DERSequence) {
DERSequence timeStampTrustConditionDERSeq = (DERSequence) timeStampTrustConditionTmp;
}
}
ASN1Encodable attributeTrustCondition = getAt(
commonRulesDLS, 3);
if (attributeTrustCondition instanceof DERTaggedObject) {
DERTaggedObject attributeTrustConditionDTO = (DERTaggedObject) attributeTrustCondition;
ASN1Encodable attributeTrustConditionTmp = attributeTrustConditionDTO
.getObject();
if (attributeTrustConditionTmp instanceof DERSequence) {
DERSequence attributeTrustConditionDERSeq = (DERSequence) attributeTrustConditionTmp;
}
}
// *****************************
ASN1Encodable algorithmConstraintSet = getAt(
commonRulesDLS, 4);
ASN1Encodable signPolExtensions = getAt(commonRulesDLS,
5);
}
// commitmentRules CommitmentRules,
ASN1Encodable commitmentRules = getAt(
signatureValidationPolicyDLS, 2);
if (commitmentRules instanceof DLSequence) {
}
// signPolExtensions SignPolExtensions
// OPTIONAL
ASN1Encodable signPolExtensions = getAt(
signatureValidationPolicyDLS, 3);
if (signPolExtensions instanceof DLSequence) {
}
// }
}
}
}
// CertInfoReq ::= ENUMERATED {
// none (0) ,
// -- No mandatory requirements
// signerOnly (1) ,
// -- Only reference to signer cert mandated
// fullpath (2)
// -- References for full cert path up to a
// -- trust point mandated
// }
is.close();
return ret;
}
// ********************
// certificate Service
// *******************
public static Map<String, String> createSanMap(byte[] extensionValue,
int index) {
Map<String, String> ret = new HashMap<String, String>();
try {
if (extensionValue == null) {
return null;
}
ASN1InputStream oAsnInStream = new ASN1InputStream(
new ByteArrayInputStream(extensionValue));
ASN1Primitive derObjCP = oAsnInStream.readObject();
DLSequence derSeq = (DLSequence) derObjCP;
// int seqLen = derSeq.size();
ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) derSeq
.getObjectAt(0);
String sanOid = oid.getId();
DERTaggedObject derTO = (DERTaggedObject) derSeq.getObjectAt(1);
// int tag = derTO.getTagNo();
ASN1Primitive derObjA = derTO.getObject();
DERTaggedObject derTO2 = (DERTaggedObject) derObjA;
// int tag2 = derTO2.getTagNo();
ASN1Primitive derObjB = derTO2.getObject();
String contentStr = "";
if (derObjB instanceof DEROctetString) {
DEROctetString derOCStr = (DEROctetString) derObjB;
contentStr = new String(derOCStr.getOctets(), "UTF8");
} else if (derObjB instanceof DERPrintableString) {
DERPrintableString derOCStr = (DERPrintableString) derObjB;
contentStr = new String(derOCStr.getOctets(), "UTF8");
} else {
LOG.info("FORMAT OF SAN: UNRECOGNIZED -> "
+ derObjB.getClass().getCanonicalName());
}
LOG.trace(sanOid + " -> " + contentStr);
String value = "";
String name = "";
if (sanOid.compareTo(PF_PF_ID) == 0
|| sanOid.compareTo(PJ_PF_ID) == 0) {
value = contentStr.substring(BIRTH_DATE_INI, BIRTH_DATE_LEN);
if (isValidValue(value)) {
name = String.format(CertConstants.BIRTH_DATE_D, index);
ret.put(name, value);
}
value = contentStr.substring(CPF_INI, CPF_LEN);
if (isValidValue(value)) {
name = String.format(CertConstants.CPF_D, index);
ret.put(name, value);
}
value = contentStr.substring(PIS_INI, PIS_LEN);
if (isValidValue(value)) {
name = String.format(CertConstants.PIS_D, index);
ret.put(name, value);
}
value = contentStr.substring(RG_INI, RG_LEN);
if (isValidValue(value)) {
name = String.format(CertConstants.RG_D, index);
ret.put(name, value);
}
int rgOrgUfLen = RG_ORG_UF_LEN > contentStr.length() ? contentStr
.length() : RG_ORG_UF_LEN;
if (rgOrgUfLen > RG_ORG_UF_INI) {
value = contentStr.substring(RG_ORG_UF_INI, rgOrgUfLen);
String rgOrg = value.substring(0, value.length() - 2);
String rgUf = value.substring(value.length() - 2,
value.length());
if (isValidValue(rgOrg)) {
name = String.format(CertConstants.RG_ORG_D, index);
ret.put(name, rgOrg);
}
if (isValidValue(rgUf)) {
name = String.format(CertConstants.RG_UF_D, index);
ret.put(name, rgUf);
}
}
} else if (sanOid.compareTo(PERSON_NAME_OID) == 0) {
value = contentStr;
if (isValidValue(value)) {
name = String.format(CertConstants.PERSON_NAME_D, index);
ret.put(name, value);
}
} else if (sanOid.compareTo(CNPJ_OID) == 0) {
name = String.format(CERT_TYPE_FMT, index);
ret.put(name, ICP_BRASIL_PJ);
value = contentStr;
if (isValidValue(value)) {
name = String.format(CertConstants.CNPJ_D, index);
ret.put(name, value);
}
} else if (sanOid.compareTo(ELEITOR_OID) == 0) {
name = String.format(CERT_TYPE_FMT, index);
ret.put(name, ICP_BRASIL_PF);
value = contentStr.substring(ELEITOR_INI, ELEITOR_LEN);
if (isValidValue(value)) {
name = String.format(CertConstants.ELEITOR_D, index);
ret.put(name, value);
}
int zonaLen = ZONA_LEN > contentStr.length() ? contentStr
.length() : ZONA_LEN;
if (zonaLen > ZONA_LEN) {
value = contentStr.substring(ZONA_INI, zonaLen);
if (isValidValue(value)) {
name = String.format(CertConstants.ZONA_D, index);
ret.put(name, value);
}
}
int secaoLen = SECAO_LEN > contentStr.length() ? contentStr
.length() : SECAO_LEN;
if (secaoLen > SECAO_LEN) {
value = contentStr.substring(SECAO_INI, SECAO_LEN);
if (isValidValue(value)) {
name = String.format(CertConstants.SECAO_D, index);
ret.put(name, value);
}
}
} else if (sanOid.compareTo(PF_PF_INSS_OID) == 0
|| sanOid.compareTo(PJ_PF_INSS_OID) == 0) {
value = contentStr.substring(INSS_INI, INSS_LEN);
if (isValidValue(value)) {
name = String.format(CertConstants.INSS_D, index);
ret.put(name, value);
}
} else if (sanOid.compareTo(OAB_OID) == 0) {
value = contentStr.substring(OAB_REG_INI, OAB_REG_LEN);
if (isValidValue(value)) {
name = String.format(CertConstants.OAB_REG_D, index);
ret.put(name, value);
}
value = contentStr.substring(OAB_UF_INI, OAB_UF_LEN);
if (isValidValue(value)) {
name = String.format(CertConstants.OAB_UF_D, index);
ret.put(name, value);
}
} else if (sanOid.startsWith(PROFESSIONAL_OID)) {
value = contentStr;
if (isValidValue(value)) {
name = String.format(CertConstants.PROFESSIONAL_D, index);
ret.put(name, value);
}
} else if (sanOid.startsWith(UPN)) {
value = contentStr;
if (isValidValue(value)) {
name = String.format(CertConstants.UPN_D, index);
ret.put(name, value);
}
} else {
LOG.error("SAN:OTHER NAME NOT RECOGNIZED");
}
} catch (Exception e) {
e.printStackTrace();
}
return ret;
}
public static byte[] getAKI(byte[] extensionValue, int index) {
byte[] ret = null;
try {
if (extensionValue == null) {
return null;
}
ASN1InputStream oAsnInStream = new ASN1InputStream(
new ByteArrayInputStream(extensionValue));
ASN1Primitive derObjCP = oAsnInStream.readObject();
DEROctetString dosCP = (DEROctetString) derObjCP;
byte[] cpOctets = dosCP.getOctets();
ASN1InputStream oAsnInStream2 = new ASN1InputStream(
new ByteArrayInputStream(cpOctets));
ASN1Primitive derObj2 = oAsnInStream2.readObject();
// derObj2 = oAsnInStream2.readObject();
DLSequence derSeq = (DLSequence) derObj2;
int seqLen = derSeq.size();
// for(int i = 0; i < seqLen; i++){
ASN1Encodable derObj3 = derSeq.getObjectAt(0);
DERTaggedObject derTO = (DERTaggedObject) derObj3;
int tag = derTO.getTagNo();
boolean empty = derTO.isEmpty();
ASN1Primitive derObj4 = derTO.getObject();
DEROctetString ocStr4 = (DEROctetString) derObj4;
ret = ocStr4.getOctets();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ret;
}
public static Map<String, String> getAIAComplete(byte[] ext)
throws UnsupportedEncodingException {
Map<String, String> ret = new HashMap<String, String>();
try {
if (ext == null)
return null;
ASN1InputStream oAsnInStream = new ASN1InputStream(
new ByteArrayInputStream(ext));
ASN1Primitive derObjAIA = oAsnInStream.readObject();
DEROctetString dosAia = (DEROctetString) derObjAIA;
byte[] aiaExtOctets = dosAia.getOctets();
// ------------ level 2
ASN1InputStream oAsnInStream2 = new ASN1InputStream(
new ByteArrayInputStream(aiaExtOctets));
ASN1Primitive derObj2 = oAsnInStream2.readObject();
DLSequence aiaDLSeq = (DLSequence) derObj2;
ASN1Encodable[] aiaAsArray = aiaDLSeq.toArray();
for (ASN1Encodable next : aiaAsArray) {
DLSequence aiaDLSeq2 = (DLSequence) next;
ASN1Encodable[] aiaAsArray2 = aiaDLSeq2.toArray();
// oid = 0 / content = 1
ASN1Encodable aiaOidEnc = aiaAsArray2[0];
ASN1ObjectIdentifier aiaOid = (ASN1ObjectIdentifier) aiaOidEnc;
String idStr = aiaOid.getId();
// if (idStr.compareTo("1.3.6.1.5.5.7.48.2") == 0) {
ASN1Encodable aiaContent = aiaAsArray2[1];
DERTaggedObject aiaDTO = (DERTaggedObject) aiaContent;
ASN1Primitive aiaObj = aiaDTO.getObject();
DEROctetString aiaDOS = (DEROctetString) aiaObj;
byte[] aiaOC = aiaDOS.getOctets();
ret.put(idStr, new String(aiaOC));
// break;
// }
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ret;
}
public static AlgorithmIdentifier createAlgorithm(int hashId)
throws Exception {
return new AlgorithmIdentifier(new ASN1ObjectIdentifier(
DerEncoder.getHashAlg(hashId)), new DERNull());
}
public static Map<String, String> getCertPolicies(byte[] certPols, int index)
throws CertificateParsingException, IOException {
Map<String, String> ret = new HashMap<String, String>();
if (certPols == null) {
return null;
}
ASN1InputStream oAsnInStream = new ASN1InputStream(
new ByteArrayInputStream(certPols));
ASN1Primitive derObjCP = oAsnInStream.readObject();
DEROctetString dosCP = (DEROctetString) derObjCP;
byte[] cpOctets = dosCP.getOctets();
ASN1InputStream oAsnInStream2 = new ASN1InputStream(
new ByteArrayInputStream(cpOctets));
ASN1Primitive derObj2 = oAsnInStream2.readObject();
DLSequence dlCP = (DLSequence) derObj2;
int seqLen = dlCP.size();
for (int i = 0; i < seqLen; i++) {
ASN1Encodable nextObj = dlCP.getObjectAt(i);
DLSequence dlCP2 = (DLSequence) nextObj;
// for(int j = 0; j < dlCP2.size(); j++){
ASN1Encodable nextObj2 = dlCP2.getObjectAt(0);
ASN1ObjectIdentifier pcOID = (ASN1ObjectIdentifier) nextObj2;
ret.put(String.format(CERT_POL_OID, index), pcOID.toString());
if (pcOID.toString().startsWith(ICP_BRASIL_PC_PREFIX_OID)) {
ret.put(String.format(CertConstants.CERT_USAGE_D, index),
getCertUsage(pcOID.toString()));
}
if (dlCP2.size() == 2) {
nextObj2 = dlCP2.getObjectAt(1);
ASN1Encodable nextObj3 = null;
if (nextObj2 instanceof DLSequence) {
DLSequence dlCP3 = (DLSequence) nextObj2;
nextObj3 = dlCP3.getObjectAt(0);
} else if (nextObj2 instanceof DERSequence) {
DERSequence dlCP3 = (DERSequence) nextObj2;
if (dlCP3.size() > 1) {
nextObj3 = dlCP3.getObjectAt(0);
}
}
if (nextObj3 != null) {
DLSequence dlCP4 = (DLSequence) nextObj3;
ASN1Encodable nextObj4a = dlCP4.getObjectAt(0);
ASN1Encodable nextObj4b = dlCP4.getObjectAt(1);
ret.put(String.format(CERT_POL_QUALIFIER, index),
nextObj4b.toString());
}
}
}
return ret;
}
public static List<String> getCrlDistributionPoints(byte[] crldpExt)
throws CertificateParsingException, IOException {
if (crldpExt == null) {
return new ArrayList<String>();
}
ASN1InputStream oAsnInStream = new ASN1InputStream(
new ByteArrayInputStream(crldpExt));
ASN1Primitive derObjCrlDP = oAsnInStream.readObject();
DEROctetString dosCrlDP = (DEROctetString) derObjCrlDP;
byte[] crldpExtOctets = dosCrlDP.getOctets();
ASN1InputStream oAsnInStream2 = new ASN1InputStream(
new ByteArrayInputStream(crldpExtOctets));
ASN1Primitive derObj2 = oAsnInStream2.readObject();
CRLDistPoint distPoint = CRLDistPoint.getInstance(derObj2);
List<String> crlUrls = new ArrayList<String>();
for (DistributionPoint dp : distPoint.getDistributionPoints()) {
DistributionPointName dpn = dp.getDistributionPoint();
// Look for URIs in fullName
if (dpn != null && dpn.getType() == DistributionPointName.FULL_NAME) {
GeneralName[] genNames = GeneralNames
.getInstance(dpn.getName()).getNames();
// Look for an URI
for (int j = 0; j < genNames.length; j++) {
if (genNames[j].getTagNo() == GeneralName.uniformResourceIdentifier) {
String url = DERIA5String.getInstance(
genNames[j].getName()).getString();
crlUrls.add(url);
}
}
}
}
return crlUrls;
}
public static byte[] encodeDigest(DigestInfo dInfo) throws IOException {
return dInfo.getEncoded(ASN1Encoding.DER);
}
public static ASN1Encodable getAt(DLSequence seq, int index) {
return seq.size() > index ? seq.getObjectAt(index) : null;
}
public static ASN1Encodable getAt(DERSequence seq, int index) {
return seq.size() > index ? seq.getObjectAt(index) : null;
}
public static boolean isValidValue(String value) {
boolean ret = true;
if (value == null || value.length() == 0) {
ret = false;
} else {
String regex = "^0*$";
Pattern datePatt = Pattern.compile(regex);
Matcher m = datePatt.matcher(value);
if (m.matches()) {
ret = false;
}
}
return ret;
}
// 2.16.76.1.2.1.n Identificacao de campos associados a Politicas de
// Certificados
// do tipo A1
// 2.16.76.1.2.2.n Identificacao de campos associados a Politicas de
// Certificados
// do tipo A2
// 2.16.76.1.2.3.n Identificacao de campos associados a Politicas de
// Certificados
// do tipo A3
// 2.16.76.1.2.4.n Identificacao de campos associados a Politicas de
// Certificados
// do tipo A4
// 2.16.76.1.2.101.n Identificacao de campos associados a Politicas de
// Certificados
// do tipo S1
// 2.16.76.1.2 2.16.76.1.2....102.n... Identificacao de campos associados a
// Politicas de Certificados
// do tipo 2
// 2.16.76.1.2 2.16.76.1.2....103.n... Identificacao de campos associados a
// Politicas de Certificados
// do tipo S3
// 2.16.76.1.2 2.16.76.1.2....104.n... Identificacao de campos associados a
// Politicas de Certificados
// do tipo S4
private static String getCertUsage(String pcOid) {
String ret = "";
if (pcOid.startsWith("2.16.76.1.2.1")) {
ret = "ICP-Brasil A1";
} else if (pcOid.startsWith("2.16.76.1.2.2")) {
ret = "ICP-Brasil A2";
} else if (pcOid.startsWith("2.16.76.1.2.3")) {
ret = "ICP-Brasil A3";
} else if (pcOid.startsWith("2.16.76.1.2.4")) {
ret = "ICP-Brasil A4";
} else if (pcOid.startsWith("2.16.76.1.2.101")) {
ret = "ICP-Brasil S1";
} else if (pcOid.startsWith("2.16.76.1.2.102")) {
ret = "ICP-Brasil S2";
} else if (pcOid.startsWith("2.16.76.1.2.103")) {
ret = "ICP-Brasil S3";
} else if (pcOid.startsWith("2.16.76.1.2.104")) {
ret = "ICP-Brasil S4";
}
return ret;
}
public static OCSPReq GenOcspReq(X509Certificate nextCert,
X509Certificate nextIssuer) throws OCSPException, OperatorCreationException, CertificateEncodingException, IOException {
OCSPReqBuilder ocspRequestGenerator = new OCSPReqBuilder();
DigestCalculatorProvider digCalcProv = new JcaDigestCalculatorProviderBuilder().setProvider("BC").build();
// CertificateID certId = new CertificateID(
// CertificateID.HASH_SHA1,
// nextIssuer, nextCert.getSerialNumber()
// );
CertificateID certId = new CertificateID(digCalcProv.get(CertificateID.HASH_SHA1),
new X509CertificateHolder (nextIssuer.getEncoded()), nextCert.getSerialNumber());
// CertificateID id = new CertificateID(digCalcProv.get(CertificateID.HASH_SHA1), testCert, BigInteger.valueOf(1));
ocspRequestGenerator.addRequest(certId);
BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis());
Extension ext = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false, new DEROctetString(nonce.toByteArray()));
ocspRequestGenerator.setRequestExtensions(new Extensions(new Extension[]{ext}));
return ocspRequestGenerator.build();
// Vector<DERObjectIdentifier> oids = new Vector<DERObjectIdentifier>();
// Vector<X509Extension> values = new Vector<X509Extension>();
//
// oids.add(OCSPObjectIdentifiers.id_pkix_ocsp_nonce);
// values.add(new X509Extension(false, new DEROctetString(nonce
// .toByteArray())));
//
// ocspRequestGenerator.setRequestExtensions(new X509Extensions(oids,
// values));
// return ocspRequestGenerator.generate();
}
// public static OCSPReq GenOcspReq(X509Certificate nextCert,
// X509Certificate nextIssuer) throws OCSPException {
//
// OCSPReqGenerator ocspRequestGenerator = new OCSPReqGenerator();
// CertificateID certId = new CertificateID(CertificateID.HASH_SHA1,
// nextIssuer, nextCert.getSerialNumber());
// ocspRequestGenerator.addRequest(certId);
//
// BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis());
// Vector<DERObjectIdentifier> oids = new Vector<DERObjectIdentifier>();
// Vector<X509Extension> values = new Vector<X509Extension>();
//
// oids.add(OCSPObjectIdentifiers.id_pkix_ocsp_nonce);
// values.add(new X509Extension(false, new DEROctetString(nonce
// .toByteArray())));
//
// ocspRequestGenerator.setRequestExtensions(new X509Extensions(oids,
// values));
// return ocspRequestGenerator.generate();
// }
public static List<String> extractOCSPUrl(X509Certificate nextCert)
throws CRLException {
List<String> OCSPUrl = new ArrayList<String>();
// LOG.trace("MISSING!!");
ASN1Primitive aiaExt = getExtensionValue(nextCert,
X509Extensions.AuthorityInfoAccess.getId());
if (aiaExt != null) {
extractAuthorityInformationAccess(OCSPUrl, aiaExt);
}
return OCSPUrl;
}
public static void extractAuthorityInformationAccess(List<String> OCSPUrl,
ASN1Primitive aiaExt) {
AuthorityInformationAccess aia = AuthorityInformationAccess.getInstance(aiaExt);
AccessDescription[] accessDescriptions = aia.getAccessDescriptions();
DERObjectIdentifier OCSPOid = new DERObjectIdentifier(
"1.3.6.1.5.5.7.48.1"); //$NON-NLS-1$
for (AccessDescription accessDescription : accessDescriptions) {
GeneralName generalName = accessDescription.getAccessLocation();
String nextName = generalName.getName().toString();
ASN1ObjectIdentifier acessMethod = accessDescription.getAccessMethod();
if (acessMethod.equals(OCSPOid)) {
OCSPUrl.add(nextName);
}
}
}
protected static ASN1Primitive getExtensionValue(
java.security.cert.X509Extension ext, String oid)
throws CRLException {
byte[] bytes = ext.getExtensionValue(oid);
if (bytes == null) {
return null;
}
return getObject(oid, bytes);
}
private static ASN1Primitive getObject(String oid, byte[] ext)
throws CRLException {
try {
ASN1InputStream aIn = new ASN1InputStream(ext);
ASN1OctetString octs = (ASN1OctetString) aIn.readObject();
aIn = new ASN1InputStream(octs.getOctets());
return aIn.readObject();
} catch (Exception e) {
throw new CRLException("exception processing extension " + oid, e); //$NON-NLS-1$
}
}
public static byte[] convSiToByte(ASN1Set newSi) throws IOException {
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
ASN1OutputStream aOut = new ASN1OutputStream(bOut);
aOut.writeObject(newSi);
aOut.close();
byte[] saAsBytes = bOut.toByteArray();
return saAsBytes;
}
}
|
0 | java-sources/al/bluecryst/bluecrystal.deps.bc_g3/1.16.0/bluecrystal/bcdeps | java-sources/al/bluecryst/bluecrystal.deps.bc_g3/1.16.0/bluecrystal/bcdeps/helper/PkiOps.java | /*
Blue Crystal: Document Digital Signature Tool
Copyright (C) 2007-2015 Sergio Leal
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package bluecrystal.bcdeps.helper;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.KeyStoreException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Security;
import java.security.Signature;
import java.security.SignatureException;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Iterator;
import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
import org.bouncycastle.cms.CMSProcessableByteArray;
import org.bouncycastle.cms.CMSSignedData;
import org.bouncycastle.cms.SignerId;
import org.bouncycastle.cms.SignerInformation;
import org.bouncycastle.cms.SignerInformationStore;
import org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoVerifierBuilder;
import org.bouncycastle.util.Store;
import org.bouncycastle.util.encoders.Base64;
import bluecrystal.domain.helper.IttruLoggerFactory;
public class PkiOps {
private static final String SHA1WITH_RSA = "SHA1withRSA";
private static final String SHA224WITH_RSA = "SHA224withRSA";
private static final String SHA256WITH_RSA = "SHA256withRSA";
private static final String SHA384WITH_RSA = "SHA384withRSA";
private static final String SHA512WITH_RSA = "SHA512withRSA";
private static final long MAXLENGTH = 100 * 1024 * 1024;
static {
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
}
public PkiOps() {
super();
}
public boolean verify(String contentPath, String envPath) throws Exception {
CMSSignedData csd = null;
byte[] buffer = loadEnv(envPath);
if (contentPath != null) {
byte[] content = getBytesFromFile(new File(contentPath));
CMSProcessableByteArray cpbfile = new CMSProcessableByteArray(
content);
csd = new CMSSignedData(cpbfile, buffer);
} else {
csd = new CMSSignedData(buffer);
}
return verify(csd);
}
public static byte[] signSha1(PrivateKey pk, byte[] data) throws Exception {
String alg = SHA1WITH_RSA;
return signByAlg(pk, data, alg);
}
public static byte[] signSha224(PrivateKey pk, byte[] data)
throws Exception {
String alg = SHA224WITH_RSA;
return signByAlg(pk, data, alg);
}
public static byte[] signSha256(PrivateKey pk, byte[] data)
throws Exception {
String alg = SHA256WITH_RSA;
return signByAlg(pk, data, alg);
}
public static byte[] signSha384(PrivateKey pk, byte[] data)
throws Exception {
String alg = SHA384WITH_RSA;
return signByAlg(pk, data, alg);
}
public static byte[] signSha512(PrivateKey pk, byte[] data)
throws Exception {
String alg = SHA512WITH_RSA;
return signByAlg(pk, data, alg);
}
private static byte[] signByAlg(PrivateKey pk, byte[] data, String alg)
throws NoSuchAlgorithmException, InvalidKeyException,
SignatureException {
Signature sig = Signature.getInstance(alg);
sig.initSign(pk);
sig.update(data);
byte[] signatureBytes = sig.sign();
return signatureBytes;
}
public byte[] calcSha1(byte[] content) throws NoSuchAlgorithmException {
String algorithm = "SHA1";
return calcSha(content, algorithm);
}
public byte[] calcSha224(byte[] content) throws NoSuchAlgorithmException {
String algorithm = "SHA224";
return calcSha(content, algorithm);
}
public byte[] calcSha256(byte[] content) throws NoSuchAlgorithmException {
String algorithm = "SHA256";
return calcSha(content, algorithm);
}
public byte[] calcSha384(byte[] content) throws NoSuchAlgorithmException {
String algorithm = "SHA384";
return calcSha(content, algorithm);
}
public byte[] calcSha512(byte[] content) throws NoSuchAlgorithmException {
String algorithm = "SHA512";
return calcSha(content, algorithm);
}
private byte[] calcSha(byte[] content, String algorithm)
throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance(algorithm);
md.reset();
md.update(content);
byte[] output = md.digest();
return output;
}
public boolean verify(CMSSignedData csd) throws Exception {
boolean verified = true;
Store certs = csd.getCertificates();
SignerInformationStore signers = csd.getSignerInfos();
Collection c = signers.getSigners();
Iterator it = c.iterator();
while (it.hasNext()) {
SignerInformation signer = (SignerInformation) it.next();
SignerId sid = signer.getSID();
Collection certCollection = certs.getMatches(signer.getSID());
if (certCollection.size() > 1) {
return false;
}
Iterator itCert = certCollection.iterator();
X509CertificateHolder signCertHolder = (X509CertificateHolder) itCert
.next();
X509Certificate signCert = new JcaX509CertificateConverter()
.setProvider("BC").getCertificate(signCertHolder);
// verified = signer.verify(signCert.getPublicKey(), "BC");
verified = signer.verify((new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(signCert)));
if (!verified) {
return false;
}
}
return verified;
}
public X509Certificate loadCertFromP12(String certFilePath, String passwd)
throws KeyStoreException, IOException, NoSuchAlgorithmException,
CertificateException, FileNotFoundException {
return loadCertFromP12(new java.io.FileInputStream(certFilePath), passwd);
}
public X509Certificate loadCertFromP12(java.io.InputStream is, String passwd)
throws KeyStoreException, IOException, NoSuchAlgorithmException,
CertificateException, FileNotFoundException {
X509Certificate x509 = null;
java.security.KeyStore ks = java.security.KeyStore
.getInstance("PKCS12");
ks.load(is, passwd.toCharArray());
// ks.load(new java.io.FileInputStream(certFilePath),null);
Enumeration<String> aliases = ks.aliases();
String nextAlias = "";
while (aliases.hasMoreElements()) {
try {
nextAlias = aliases.nextElement();
PrivateKey pk = (PrivateKey) ks.getKey(nextAlias,
passwd.toCharArray());
if (pk != null) {
x509 = (X509Certificate) ks.getCertificate(nextAlias);
break;
}
} catch (UnrecoverableKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return x509;
}
public PrivateKey loadPrivFromP12(String certFilePath, String passwd)
throws KeyStoreException, IOException, NoSuchAlgorithmException,
CertificateException, FileNotFoundException {
return loadPrivFromP12(new java.io.FileInputStream(certFilePath), passwd);
}
public PrivateKey loadPrivFromP12(InputStream is, String passwd)
throws KeyStoreException, IOException, NoSuchAlgorithmException,
CertificateException, FileNotFoundException {
PrivateKey pk = null;
java.security.KeyStore ks = java.security.KeyStore
.getInstance("PKCS12");
ks.load(is, passwd.toCharArray());
// ks.load(new java.io.FileInputStream(certFilePath),null);
Enumeration<String> aliases = ks.aliases();
String nextAlias = "";
while (aliases.hasMoreElements()) {
nextAlias = aliases.nextElement();
try {
pk = (PrivateKey) ks.getKey(nextAlias, passwd.toCharArray());
if (pk != null) {
break;
}
} catch (UnrecoverableKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return pk;
}
public PublicKey createPublicKey(String pubKey) throws Exception{
byte[] pkBytes = Base64.decode(pubKey);
PublicKey publicKey = null;
try {
createPubKey(pkBytes);
} catch (Exception e) {
publicKey = createPubKeyFromCertificate(pkBytes);
}
return publicKey;
}
private PublicKey createPubKeyFromCertificate(byte[] pkBytes) throws CertificateException {
PublicKey publicKey;
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
Certificate certificate = certificateFactory.generateCertificate(new ByteArrayInputStream(pkBytes));
publicKey = certificate.getPublicKey();
return publicKey;
}
private void createPubKey(byte[] pkBytes) throws InvalidKeySpecException, NoSuchAlgorithmException {
PublicKey publicKey;
publicKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(pkBytes));
}
private static byte[] getBytesFromFile(File file) throws IOException {
InputStream is = null;
byte[] ret = null;
try {
long length = file.length();
if (length > MAXLENGTH)
throw new IllegalArgumentException("File is too big");
ret = new byte[(int) length];
is = new FileInputStream(file);
is.read(ret);
} finally {
if (is != null)
try {
is.close();
} catch (IOException ex) {
}
}
return ret;
}
private byte[] loadEnv(String envPath) throws FileNotFoundException,
IOException {
File f = new File(envPath);
if (!f.exists()) {
(IttruLoggerFactory.get()).println("Nao existe: " + envPath);
}
byte[] buffer = new byte[(int) f.length()];
DataInputStream in = new DataInputStream(new FileInputStream(f));
in.readFully(buffer);
in.close();
return buffer;
}
}
|
0 | java-sources/al/bluecryst/bluecrystal.deps.bc_g3/1.16.0/bluecrystal/bcdeps | java-sources/al/bluecryst/bluecrystal.deps.bc_g3/1.16.0/bluecrystal/bcdeps/helper/package-info.java | /**
*
*/
/**
* @author sergio
*
*/
package bluecrystal.bcdeps.helper; |
0 | java-sources/al/bluecryst/bluecrystal.deps.domain/1.16.0/bluecrystal | java-sources/al/bluecryst/bluecrystal.deps.domain/1.16.0/bluecrystal/domain/AppSignedInfo.java | /*
Blue Crystal: Document Digital Signature Tool
Copyright (C) 2007-2015 Sergio Leal
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package bluecrystal.domain;
import java.util.Date;
public class AppSignedInfo {
private String certId;
private byte[] signedHash;
private byte[] origHash;
private Date signingTime;
public AppSignedInfo(String certId, byte[] signedHash, byte[] origHash,
Date signingTime) {
super();
this.certId = certId;
this.signedHash = signedHash;
this.origHash = origHash;
this.signingTime = signingTime;
}
public String getCertId() {
return certId;
}
public byte[] getSignedHash() {
return signedHash;
}
public byte[] getOrigHash() {
return origHash;
}
public Date getSigningTime() {
return signingTime;
}
}
|
0 | java-sources/al/bluecryst/bluecrystal.deps.domain/1.16.0/bluecrystal | java-sources/al/bluecryst/bluecrystal.deps.domain/1.16.0/bluecrystal/domain/AppSignedInfoEx.java | /*
Blue Crystal: Document Digital Signature Tool
Copyright (C) 2007-2015 Sergio Leal
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package bluecrystal.domain;
import java.security.cert.X509Certificate;
import java.util.Date;
public class AppSignedInfoEx extends AppSignedInfo {
X509Certificate x509;
byte[] certHash;
int idSha;
public AppSignedInfoEx(AppSignedInfo asi, X509Certificate x509, byte[] certHash, int idSha) {
super(asi.getCertId(), asi.getSignedHash(), asi.getOrigHash(), asi.getSigningTime());
this.x509 = x509;
this.certHash = certHash;
this.idSha = idSha;
}
public AppSignedInfoEx(byte[] signedHash, byte[] origHash,
Date signingTime, X509Certificate x509, byte[] certHash, int idSha) {
super(null, signedHash, origHash, signingTime);
this.x509 = x509;
this.certHash = certHash;
this.idSha = idSha;
}
public X509Certificate getX509() {
return x509;
}
public byte[] getCertHash() {
return certHash;
}
public int getIdSha() {
return idSha;
}
}
|
0 | java-sources/al/bluecryst/bluecrystal.deps.domain/1.16.0/bluecrystal | java-sources/al/bluecryst/bluecrystal.deps.domain/1.16.0/bluecrystal/domain/CertConstants.java | /*
Blue Crystal: Document Digital Signature Tool
Copyright (C) 2007-2015 Sergio Leal
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package bluecrystal.domain;
public class CertConstants {
public static final String THUMBPRINT_SHA256_D = "thumbprint_sha256%d";
public static final String EKU_D = "eku%d";
public static final String KU_D = "ku%d";
public static final String SAN_EMAIL_D = "san_email%d";
public static final String BASIC_CONSTRAINT_D = "basicConstraint%d";
public static final String KEY_LENGTH_D = "key_length%d";
public static final String SERIAL_D = "serial%d";
public static final String CERT_SHA256_D = "certSha256%d";
public static final String VERSION_D = "version%d";
public static final String NOT_BEFORE_D = "notBefore%d";
public static final String NOT_AFTER_D = "notAfter%d";
public static final String ISSUER_D = "issuer%d";
public static final String SUBJECT_D = "subject%d";
public static final String OCSP_STR = "ocsp%d";
public static final String CA_ISSUERS_STR = "chain%d";
public static final String AKI_FMT = "aki%d";
public static final String CRL_DP = "crlDP%d";
public static final String CERT_POL_OID = "certPolOid%d";
public static final String CERT_POL_QUALIFIER = "certPolQualifier%d";
public static final String CERT_USAGE_D = "cert_usage%d";
public static final String BIRTH_DATE_D = "birth_date%d";
public static final String CPF_D = "cpf%d";
public static final String PIS_D = "pis%d";
public static final String RG_D = "rg%d";
public static final String RG_ORG_D = "rg_org%d";
public static final String RG_UF_D = "rg_uf%d";
public static final String PERSON_NAME_D = "person_name%d";
public static final String CNPJ_D = "cnpj%d";
public static final String ELEITOR_D = "eleitor%d";
public static final String ZONA_D = "zona%d";
public static final String SECAO_D = "secao%d";
public static final String INSS_D = "inss%d";
public static final String OAB_REG_D = "oab_reg%d";
public static final String OAB_UF_D = "oab_uf%d";
public static final String PROFESSIONAL_D = "professional%d";
public static final String UPN_D = "upn%d";
public static String getSubject(int i){
return String.format(CertConstants.SUBJECT_D, i);
}
public static String getIssuer(int i){
return String.format(CertConstants.ISSUER_D, i);
}
}
|
0 | java-sources/al/bluecryst/bluecrystal.deps.domain/1.16.0/bluecrystal | java-sources/al/bluecryst/bluecrystal.deps.domain/1.16.0/bluecrystal/domain/CiKeyUsage.java | /*
Blue Crystal: Document Digital Signature Tool
Copyright (C) 2007-2015 Sergio Leal
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package bluecrystal.domain;
//KeyUsage ::= BIT STRING {
//digitalSignature (0),
//nonRepudiation (1),
//keyEncipherment (2),
//dataEncipherment (3),
//keyAgreement (4),
//keyCertSign (5),
//cRLSign (6),
//encipherOnly (7),
//decipherOnly (8) }
public class CiKeyUsage {
public final static int digitalSignature = 0;
public final static int nonRepudiation = 1;
public final static int keyEncipherment = 2;
public final static int dataEncipherment = 3;
public final static int keyAgreement = 4;
public final static int keyCertSign = 5;
public final static int cRLSign = 6;
public final static int encipherOnly = 7;
public final static int decipherOnly = 8;
public final static int length = decipherOnly+1;
}
|
0 | java-sources/al/bluecryst/bluecrystal.deps.domain/1.16.0/bluecrystal | java-sources/al/bluecryst/bluecrystal.deps.domain/1.16.0/bluecrystal/domain/Messages.java | package bluecrystal.domain;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
public class Messages {
private static final String BUNDLE_NAME = "bluecrystal.domain.messages"; //$NON-NLS-1$
private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME);
private Messages() {
}
public static String getString(String key) {
try {
return RESOURCE_BUNDLE.getString(key);
} catch (MissingResourceException e) {
return '!' + key + '!';
}
}
}
|
0 | java-sources/al/bluecryst/bluecrystal.deps.domain/1.16.0/bluecrystal | java-sources/al/bluecryst/bluecrystal.deps.domain/1.16.0/bluecrystal/domain/NameValue.java | /*
Blue Crystal: Document Digital Signature Tool
Copyright (C) 2007-2015 Sergio Leal
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package bluecrystal.domain;
public class NameValue {
@Override
public String toString() {
return "NameValue [name=" + name + ", value=" + value + "]";
}
private String name;
private String value;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public NameValue() {
super();
// TODO Auto-generated constructor stub
}
public NameValue(String name, String value) {
super();
this.name = name;
this.value = value;
}
}
|
0 | java-sources/al/bluecryst/bluecrystal.deps.domain/1.16.0/bluecrystal | java-sources/al/bluecryst/bluecrystal.deps.domain/1.16.0/bluecrystal/domain/OperationStatus.java | /*
Blue Crystal: Document Digital Signature Tool
Copyright (C) 2007-2015 Sergio Leal
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package bluecrystal.domain;
import java.util.Date;
public class OperationStatus {
@Override
public String toString() {
return "CertStatus [status=" + status + ", goodUntil=" + goodUntil
+ "]";
}
private int status;
private Date goodUntil;
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public Date getGoodUntil() {
return goodUntil;
}
public void setGoodUntil(Date goodUntil) {
this.goodUntil = goodUntil;
}
public OperationStatus(int status, Date goodUntil) {
super();
this.status = status;
this.goodUntil = goodUntil;
}
}
|
0 | java-sources/al/bluecryst/bluecrystal.deps.domain/1.16.0/bluecrystal | java-sources/al/bluecryst/bluecrystal.deps.domain/1.16.0/bluecrystal/domain/SignCompare.java | /*
Blue Crystal: Document Digital Signature Tool
Copyright (C) 2007-2015 Sergio Leal
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package bluecrystal.domain;
import java.util.Date;
import java.util.List;
public class SignCompare {
@Override
public String toString() {
return String
.format("SignCompare [signingTime=%s,\nnumCerts=%s,\nsignedAttribs=%s,\npsOid=%s,\npsUrl=%s]",
signingTime, numCerts, signedAttribs, psOid, psUrl);
}
private Date signingTime;
private int numCerts;
private List<String> signedAttribs;
private String psOid;
private String psUrl;
public Date getSigningTime() {
return signingTime;
}
public void setSigningTime(Date signingTime) {
this.signingTime = signingTime;
}
public int getNumCerts() {
return numCerts;
}
public void setNumCerts(int numCerts) {
this.numCerts = numCerts;
}
public List<String> getSignedAttribs() {
return signedAttribs;
}
public void setSignedAttribs(List<String> signedAttribs) {
this.signedAttribs = signedAttribs;
}
public String getPsOid() {
return psOid;
}
public void setPsOid(String psOid) {
this.psOid = psOid;
}
public String getPsUrl() {
return psUrl;
}
public void setPsUrl(String psUrl) {
this.psUrl = psUrl;
}
}
|
0 | java-sources/al/bluecryst/bluecrystal.deps.domain/1.16.0/bluecrystal | java-sources/al/bluecryst/bluecrystal.deps.domain/1.16.0/bluecrystal/domain/SignCompare2.java | /*
Blue Crystal: Document Digital Signature Tool
Copyright (C) 2007-2015 Sergio Leal
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package bluecrystal.domain;
import java.util.Date;
import java.util.List;
public class SignCompare2 {
@Override
public String toString() {
return String
.format("SignCompare [signingTime=%s,\nnumCerts=%s,\nsignedAttribs=%s,\npsOid=%s,\npsUrl=%s]",
signingTime, numCerts, signedAttribs, psOid, psUrl);
}
private Date signingTime;
private int numCerts;
private List<String> signedAttribs;
private String psOid;
private String psUrl;
private String signedHashb64;
private String origHashb64;
public String getSignedHashb64() {
return signedHashb64;
}
public void setSignedHashb64(String signedHashb64) {
this.signedHashb64 = signedHashb64;
}
public String getOrigHashb64() {
return origHashb64;
}
public void setOrigHashb64(String origHashb64) {
this.origHashb64 = origHashb64;
}
public Date getSigningTime() {
return signingTime;
}
public void setSigningTime(Date signingTime) {
this.signingTime = signingTime;
}
public int getNumCerts() {
return numCerts;
}
public void setNumCerts(int numCerts) {
this.numCerts = numCerts;
}
public List<String> getSignedAttribs() {
return signedAttribs;
}
public void setSignedAttribs(List<String> signedAttribs) {
this.signedAttribs = signedAttribs;
}
public String getPsOid() {
return psOid;
}
public void setPsOid(String psOid) {
this.psOid = psOid;
}
public String getPsUrl() {
return psUrl;
}
public void setPsUrl(String psUrl) {
this.psUrl = psUrl;
}
}
|
0 | java-sources/al/bluecryst/bluecrystal.deps.domain/1.16.0/bluecrystal | java-sources/al/bluecryst/bluecrystal.deps.domain/1.16.0/bluecrystal/domain/SignDetails.java | /*
Blue Crystal: Document Digital Signature Tool
Copyright (C) 2007-2015 Sergio Leal
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package bluecrystal.domain;
import java.util.Date;
import java.util.List;
public class SignDetails {
@Override
public String toString() {
return String
.format("SignCompare [signingTime=%s,\nnumCerts=%s,\nsignedAttribs=%s,\npsOid=%s,\npsUrl=%s]",
signingTime, numCerts, signedAttribs, psOid, psUrl);
}
private Date signingTime;
private int numCerts;
private String[] signedAttribs;
private String psOid;
private String psUrl;
public Date getSigningTime() {
return signingTime;
}
public void setSigningTime(Date signingTime) {
this.signingTime = signingTime;
}
public int getNumCerts() {
return numCerts;
}
public void setNumCerts(int numCerts) {
this.numCerts = numCerts;
}
public String[] getSignedAttribs() {
return signedAttribs;
}
public void setSignedAttribs(String[] signedAttribs) {
this.signedAttribs = signedAttribs;
}
public String getPsOid() {
return psOid;
}
public void setPsOid(String psOid) {
this.psOid = psOid;
}
public String getPsUrl() {
return psUrl;
}
public void setPsUrl(String psUrl) {
this.psUrl = psUrl;
}
}
|
0 | java-sources/al/bluecryst/bluecrystal.deps.domain/1.16.0/bluecrystal | java-sources/al/bluecryst/bluecrystal.deps.domain/1.16.0/bluecrystal/domain/SignPolicy.java | /*
Blue Crystal: Document Digital Signature Tool
Copyright (C) 2007-2015 Sergio Leal
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package bluecrystal.domain;
public class SignPolicy {
private byte[] policyHash;
private String policyUri;
private String policyId;
public SignPolicy(byte[] policyHash, String policyUri, String policyId) {
super();
this.policyHash = policyHash;
this.policyUri = policyUri;
this.policyId = policyId;
}
public byte[] getPolicyHash() {
return policyHash;
}
public String getPolicyUri() {
return policyUri;
}
public String getPolicyId() {
return policyId;
}
}
|
0 | java-sources/al/bluecryst/bluecrystal.deps.domain/1.16.0/bluecrystal | java-sources/al/bluecryst/bluecrystal.deps.domain/1.16.0/bluecrystal/domain/SignPolicyRef.java | /*
Blue Crystal: Document Digital Signature Tool
Copyright (C) 2007-2015 Sergio Leal
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package bluecrystal.domain;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class SignPolicyRef {
// notBefore -> 20120307000000Z
// mandatedSignedAttr.0 -> 1.2.840.113549.1.9.3
// mandatedSignedAttr.2 -> 1.2.840.113549.1.9.16.2.15
// mandatedCertificateRef -> 1
// mandatedSignedAttr.1 -> 1.2.840.113549.1.9.4
// psHashAlg -> 2.16.840.1.101.3.4.2.1
// mandatedSignedAttr.3 -> 1.2.840.113549.1.9.16.2.47
// psOid -> 2.16.76.1.7.1.1.2.1
// notAfter -> 20230621000000Z
// polIssuerName -> C=BR,O=ICP-Brasil,OU=Instituto Nacional de Tecnologia da Informacao - ITI
// dateOfIssue -> 20120307000000Z
private Date notBefore;
private Date notAfter;
private Date dateOfIssue;
private List<String> mandatedSignedAttr;
private int mandatedCertificateRef;
private String psHashAlg;
private String psOid;
private String polIssuerName;
private String fieldOfApplication;
public String getFieldOfApplication() {
return fieldOfApplication;
}
public void setFieldOfApplication(String fieldOfApplication) {
this.fieldOfApplication = fieldOfApplication;
}
public Date getNotBefore() {
return notBefore;
}
public void setNotBefore(Date notBefore) {
this.notBefore = notBefore;
}
public Date getNotAfter() {
return notAfter;
}
public void setNotAfter(Date notAfter) {
this.notAfter = notAfter;
}
public Date getDateOfIssue() {
return dateOfIssue;
}
public void setDateOfIssue(Date dateOfIssue) {
this.dateOfIssue = dateOfIssue;
}
public List<String> getMandatedSignedAttr() {
return mandatedSignedAttr;
}
public void addMandatedSignedAttr(String mandatedSignedAttr) {
if(this.mandatedSignedAttr == null ){
this.mandatedSignedAttr = new ArrayList<String>();
}
this.mandatedSignedAttr.add(mandatedSignedAttr);
}
@Override
public String toString() {
return "SignPolicyRef [notBefore=" + notBefore + ",\n"
+ " notAfter=" + notAfter + ",\n"
+ "dateOfIssue=" + dateOfIssue + ",\n"
+ " mandatedSignedAttr=" + mandatedSignedAttr + ",\n"
+ " mandatedCertificateRef="+ mandatedCertificateRef + ",\n"
+ " psHashAlg=" + psHashAlg + ",\n"
+ " psOid="+ psOid + ",\n"
+ " polIssuerName=" + polIssuerName + "]";
}
public int getMandatedCertificateRef() {
return mandatedCertificateRef;
}
public void setMandatedCertificateRef(int mandatedCertificateRef) {
this.mandatedCertificateRef = mandatedCertificateRef;
}
public String getPsHashAlg() {
return psHashAlg;
}
public void setPsHashAlg(String psHashAlg) {
this.psHashAlg = psHashAlg;
}
public String getPsOid() {
return psOid;
}
public void setPsOid(String psOid) {
this.psOid = psOid;
}
public String getPolIssuerName() {
return polIssuerName;
}
public void setPolIssuerName(String polIssuerName) {
this.polIssuerName = polIssuerName;
}
}
|
0 | java-sources/al/bluecryst/bluecrystal.deps.domain/1.16.0/bluecrystal | java-sources/al/bluecryst/bluecrystal.deps.domain/1.16.0/bluecrystal/domain/StatusConst.java | /*
Blue Crystal: Document Digital Signature Tool
Copyright (C) 2007-2015 Sergio Leal
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package bluecrystal.domain;
public class StatusConst {
public final static int GOOD = 0;
public final static int UNKNOWN = 1;
public final static int EXPIRED = 2;
public final static int PATH_ERROR = 3;
public final static int PROCESSING_ERROR = 4;
public final static int REVOKED = 100;
public final static int KEYCOMPROMISE = 101;
public final static int CACOMPROMISE = 102;
public final static int AFFILIATIONCHANGED = 103;
public final static int SUPERSEDED = 104;
public final static int CESSATIONOFOPERATION = 105;
public final static int CERTIFICATEHOLD = 106;
public final static int REMOVEFROMCRL = 108;
public final static int PRIVILEGEWITHDRAWN = 109;
public final static int AACOMPROMISE = 110;
public final static int UNSABLEKEY = 1000;
public final static int UNTRUSTED = 1001;
public final static int INVALID_SIGN = 9999;
public final static int LAST_STATUS = INVALID_SIGN;
public static String getMessageByStatus(int status){
return "status";
// String ret = Messages.getString("StatusConst."+status); //$NON-NLS-1$
// return ret;
}
}
|
0 | java-sources/al/bluecryst/bluecrystal.deps.domain/1.16.0/bluecrystal | java-sources/al/bluecryst/bluecrystal.deps.domain/1.16.0/bluecrystal/domain/package-info.java | /**
*
*/
/**
* @author sergio
*
*/
package bluecrystal.domain; |
0 | java-sources/al/bluecryst/bluecrystal.deps.domain/1.16.0/bluecrystal/domain | java-sources/al/bluecryst/bluecrystal.deps.domain/1.16.0/bluecrystal/domain/helper/IttruLogger.java | /*
Blue Crystal: Document Digital Signature Tool
Copyright (C) 2007-2015 Sergio Leal
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package bluecrystal.domain.helper;
public interface IttruLogger {
public abstract void print(Object msg);
public abstract void println(Object msg);
public abstract void println(Object obj, String msg);
public abstract void printError(Exception e);
} |
0 | java-sources/al/bluecryst/bluecrystal.deps.domain/1.16.0/bluecrystal/domain | java-sources/al/bluecryst/bluecrystal.deps.domain/1.16.0/bluecrystal/domain/helper/IttruLoggerFactory.java | /*
Blue Crystal: Document Digital Signature Tool
Copyright (C) 2007-2015 Sergio Leal
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package bluecrystal.domain.helper;
public class IttruLoggerFactory {
private static IttruLogger instance;
public static IttruLogger get (){
if(instance == null){
instance = new IttruLoggerStdOut();
}
return instance;
}
}
|
0 | java-sources/al/bluecryst/bluecrystal.deps.domain/1.16.0/bluecrystal/domain | java-sources/al/bluecryst/bluecrystal.deps.domain/1.16.0/bluecrystal/domain/helper/IttruLoggerStdOut.java | /*
Blue Crystal: Document Digital Signature Tool
Copyright (C) 2007-2015 Sergio Leal
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package bluecrystal.domain.helper;
import java.util.Date;
public class IttruLoggerStdOut implements IttruLogger {
/* (non-Javadoc)
* @see com.ittru.helper.IttruLogger#print(java.lang.String)
*/
@Override
public void print(Object msg) {
Date now = new Date();
System.out.print(now.toString() + " : "+ msg);
}
/* (non-Javadoc)
* @see com.ittru.helper.IttruLogger#println(java.lang.String)
*/
@Override
public void println(Object msg) {
Date now = new Date();
System.out.print(now.toString() + " : "+ msg+"\n");
}
@Override
public void printError(Exception e) {
// TODO Auto-generated method stub
}
@Override
public void println(Object obj, String msg) {
// TODO Auto-generated method stub
}
}
|
0 | java-sources/al/bluecryst/bluecrystal.deps.domain/1.16.0/bluecrystal/domain | java-sources/al/bluecryst/bluecrystal.deps.domain/1.16.0/bluecrystal/domain/helper/package-info.java | /**
*
*/
/**
* @author sergio
*
*/
package bluecrystal.domain.helper; |
0 | java-sources/al/bluecryst/bluecrystal.deps.domain/1.16.0/bluecrystal/domain | java-sources/al/bluecryst/bluecrystal.deps.domain/1.16.0/bluecrystal/domain/rest/RequestCertificateParsed.java | package bluecrystal.domain.rest;
public class RequestCertificateParsed {
public String certb64;
public boolean validate;
public RequestCertificateParsed() {
super();
// TODO Auto-generated constructor stub
}
public RequestCertificateParsed(String certb64, boolean validate) {
super();
this.certb64 = certb64;
this.validate = validate;
}
public String getCertb64() {
return certb64;
}
public void setCertb64(String certb64) {
this.certb64 = certb64;
}
public boolean isValidate() {
return validate;
}
public void setValidate(boolean validate) {
this.validate = validate;
}
@Override
public String toString() {
return "RequestCertificateParsed [certb64=" + certb64 + ", validate=" + validate + "]";
}
}
|
0 | java-sources/al/bluecryst/bluecrystal.deps.domain/1.16.0/bluecrystal/domain | java-sources/al/bluecryst/bluecrystal.deps.domain/1.16.0/bluecrystal/domain/rest/RequestEnvelope.java | package bluecrystal.domain.rest;
//String hash_valueb64 = (String) request.getParameter("hash_value");
//String timeValue = (String) request.getParameter("time_value");
//String saValueb64 = (String) request.getParameter("sa_value");
//String signedValueb64 = (String) request.getParameter("signed_value");
//String certb64 = (String) request.getParameter("cert");
//String alg = (String) request.getParameter("alg");
public class RequestEnvelope {
private String hashValueb64;
private String timeValue;
// "2010-10-27T11:58:22.973Z"
// ISO 8601 DateTime
private String saValueb64;
private String signedValueb64;
private String certb64;
private String alg;
public RequestEnvelope() {
super();
// TODO Auto-generated constructor stub
}
public RequestEnvelope(String hashValueb64, String timeValue, String saValueb64, String signedValueb64,
String certb64, String alg) {
super();
this.hashValueb64 = hashValueb64;
this.timeValue = timeValue;
this.saValueb64 = saValueb64;
this.signedValueb64 = signedValueb64;
this.certb64 = certb64;
this.alg = alg;
}
public String getHashValueb64() {
return hashValueb64;
}
public void setHashValueb64(String hashValueb64) {
this.hashValueb64 = hashValueb64;
}
public String getTimeValue() {
return timeValue;
}
public void setTimeValue(String timeValue) {
this.timeValue = timeValue;
}
public String getSaValueb64() {
return saValueb64;
}
public void setSaValueb64(String saValueb64) {
this.saValueb64 = saValueb64;
}
public String getSignedValueb64() {
return signedValueb64;
}
public void setSignedValueb64(String signedValueb64) {
this.signedValueb64 = signedValueb64;
}
public String getCertb64() {
return certb64;
}
public void setCertb64(String certb64) {
this.certb64 = certb64;
}
public String getAlg() {
return alg;
}
public void setAlg(String alg) {
this.alg = alg;
}
@Override
public String toString() {
return "RequestEnvelope [hashValueb64=" + hashValueb64 + ", timeValue=" + timeValue + ", saValueb64="
+ saValueb64 + ", signedValueb64=" + signedValueb64 + ", certb64=" + certb64 + ", alg=" + alg + "]";
}
}
|
0 | java-sources/al/bluecryst/bluecrystal.deps.domain/1.16.0/bluecrystal/domain | java-sources/al/bluecryst/bluecrystal.deps.domain/1.16.0/bluecrystal/domain/rest/RequestEnvelopeSigner.java | package bluecrystal.domain.rest;
public class RequestEnvelopeSigner {
private String envelopeSignedB64;
public RequestEnvelopeSigner() {
super();
// TODO Auto-generated constructor stub
}
public RequestEnvelopeSigner(String envelopeSigned) {
super();
this.envelopeSignedB64 = envelopeSigned;
}
public String getEnvelopeSignedB64() {
return envelopeSignedB64;
}
public void setEnvelopeSignedB64(String envelopeSignedB64) {
this.envelopeSignedB64 = envelopeSignedB64;
}
@Override
public String toString() {
return "RequestEnvelopeSigner [envelopeSignedB64=" + envelopeSignedB64 + "]";
}
}
|
0 | java-sources/al/bluecryst/bluecrystal.deps.domain/1.16.0/bluecrystal/domain | java-sources/al/bluecryst/bluecrystal.deps.domain/1.16.0/bluecrystal/domain/rest/RequestEnvelopeVerify.java | package bluecrystal.domain.rest;
public class RequestEnvelopeVerify {
@Override
public String toString() {
return "RequestEnvelopeVerify [envelope=" + envelope + ", contentHash=" + contentHash + "]";
}
private String envelope;
private String contentHash;
public RequestEnvelopeVerify() {
super();
// TODO Auto-generated constructor stub
}
public RequestEnvelopeVerify(String envelope, String contentHash) {
super();
this.envelope = envelope;
this.contentHash = contentHash;
}
public String getEnvelope() {
return envelope;
}
public void setEnvelope(String envelope) {
this.envelope = envelope;
}
public String getContentHash() {
return contentHash;
}
public void setContentHash(String contentHash) {
this.contentHash = contentHash;
}
}
|
0 | java-sources/al/bluecryst/bluecrystal.deps.domain/1.16.0/bluecrystal/domain | java-sources/al/bluecryst/bluecrystal.deps.domain/1.16.0/bluecrystal/domain/rest/RequestJwtPostSigned.java | package bluecrystal.domain.rest;
import java.util.Arrays;
public class RequestJwtPostSigned {
private String issuer;
private String subject;
private String audience;
private Long expirationTime;
private Long notBefore;
private Long issuedAt;
private String jwtId;
private String credential;
private int credentialType;
private String preSigned;
private String signed;
public RequestJwtPostSigned() {
super();
}
public RequestJwtPostSigned(String issuer, String subject, String audience, Long expirationTime, Long notBefore,
Long issuedAt, String jwtId, String credential, int credentialType, String preSigned, String signed) {
super();
this.issuer = issuer;
this.subject = subject;
this.audience = audience;
this.expirationTime = expirationTime;
this.notBefore = notBefore;
this.issuedAt = issuedAt;
this.jwtId = jwtId;
this.credential = credential;
this.credentialType = credentialType;
this.preSigned = preSigned;
this.signed = signed;
}
public String getIssuer() {
return issuer;
}
public String getSubject() {
return subject;
}
public String getAudience() {
return audience;
}
public Long getExpirationTime() {
return expirationTime;
}
public Long getNotBefore() {
return notBefore;
}
public Long getIssuedAt() {
return issuedAt;
}
public String getJwtId() {
return jwtId;
}
public String getCredential() {
return credential;
}
public int getCredentialType() {
return credentialType;
}
public String getPreSigned() {
return preSigned;
}
public String getSigned() {
return signed;
}
@Override
public String toString() {
return "RequestJwtPostSigned [issuer=" + issuer + ", subject=" + subject + ", audience=" + audience
+ ", expirationTime=" + expirationTime + ", notBefore=" + notBefore + ", issuedAt=" + issuedAt
+ ", jwtId=" + jwtId + ", credential=" + credential + ", credentialType=" + credentialType
+ ", preSigned=" + preSigned + ", signed=" + signed + "]";
}
public void setIssuer(String issuer) {
this.issuer = issuer;
}
public void setSubject(String subject) {
this.subject = subject;
}
public void setAudience(String audience) {
this.audience = audience;
}
public void setExpirationTime(Long expirationTime) {
this.expirationTime = expirationTime;
}
public void setNotBefore(Long notBefore) {
this.notBefore = notBefore;
}
public void setIssuedAt(Long issuedAt) {
this.issuedAt = issuedAt;
}
public void setJwtId(String jwtId) {
this.jwtId = jwtId;
}
public void setCredential(String credential) {
this.credential = credential;
}
public void setCredentialType(int credentialType) {
this.credentialType = credentialType;
}
public void setPreSigned(String preSigned) {
this.preSigned = preSigned;
}
public void setSigned(String signed) {
this.signed = signed;
}
}
|
0 | java-sources/al/bluecryst/bluecrystal.deps.domain/1.16.0/bluecrystal/domain | java-sources/al/bluecryst/bluecrystal.deps.domain/1.16.0/bluecrystal/domain/rest/RequestJwtPreSigned.java | package bluecrystal.domain.rest;
public class RequestJwtPreSigned {
private String issuer;
private String subject;
private String audience;
private Long expirationTime;
private Long notBefore;
private Long issuedAt;
private String jwtId;
private String credential;
private int credentialType;
public RequestJwtPreSigned() {
super();
}
public RequestJwtPreSigned(String issuer, String subject, String audience, Long expirationTime, Long notBefore,
Long issuedAt, String jwtId, String credential, int credentialType) {
super();
this.issuer = issuer;
this.subject = subject;
this.audience = audience;
this.expirationTime = expirationTime;
this.notBefore = notBefore;
this.issuedAt = issuedAt;
this.jwtId = jwtId;
this.credential = credential;
this.credentialType = credentialType;
}
public String getIssuer() {
return issuer;
}
public String getSubject() {
return subject;
}
public String getAudience() {
return audience;
}
public Long getExpirationTime() {
return expirationTime;
}
public Long getNotBefore() {
return notBefore;
}
public Long getIssuedAt() {
return issuedAt;
}
public String getJwtId() {
return jwtId;
}
public String getCredential() {
return credential;
}
public int getCredentialType() {
return credentialType;
}
@Override
public String toString() {
return "RequestJwtPreSigned [issuer=" + issuer + ", subject=" + subject + ", audience=" + audience
+ ", expirationTime=" + expirationTime + ", notBefore=" + notBefore + ", issuedAt=" + issuedAt
+ ", jwtId=" + jwtId + ", credential=" + credential + ", credentialType=" + credentialType + "]";
}
public void setIssuer(String issuer) {
this.issuer = issuer;
}
public void setSubject(String subject) {
this.subject = subject;
}
public void setAudience(String audience) {
this.audience = audience;
}
public void setExpirationTime(Long expirationTime) {
this.expirationTime = expirationTime;
}
public void setNotBefore(Long notBefore) {
this.notBefore = notBefore;
}
public void setIssuedAt(Long issuedAt) {
this.issuedAt = issuedAt;
}
public void setJwtId(String jwtId) {
this.jwtId = jwtId;
}
public void setCredential(String credential) {
this.credential = credential;
}
public void setCredentialType(int credentialType) {
this.credentialType = credentialType;
}
}
|
0 | java-sources/al/bluecryst/bluecrystal.deps.domain/1.16.0/bluecrystal/domain | java-sources/al/bluecryst/bluecrystal.deps.domain/1.16.0/bluecrystal/domain/rest/RequestSignable.java | package bluecrystal.domain.rest;
public class RequestSignable {
public String certb64;
public String alg;
public String contentHash;
public RequestSignable() {
super();
// TODO Auto-generated constructor stub
}
public RequestSignable(String certb64, String alg, String contentHash) {
super();
this.certb64 = certb64;
this.alg = alg;
this.contentHash = contentHash;
}
@Override
public String toString() {
return "RequestSignable [certb64=" + certb64 + ", alg=" + alg + ", contentHash=" + contentHash + "]";
}
public String getCertb64() {
return certb64;
}
public String getAlg() {
return alg;
}
public String getContentHash() {
return contentHash;
}
}
|
0 | java-sources/al/bluecryst/bluecrystal.deps.domain/1.16.0/bluecrystal/domain | java-sources/al/bluecryst/bluecrystal.deps.domain/1.16.0/bluecrystal/domain/rest/RequestStorage.java | package bluecrystal.domain.rest;
public class RequestStorage {
String firstName;
String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public RequestStorage(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public RequestStorage() {
}
} |
0 | java-sources/al/bluecryst/bluecrystal.deps.domain/1.16.0/bluecrystal/domain | java-sources/al/bluecryst/bluecrystal.deps.domain/1.16.0/bluecrystal/domain/rest/ResponseCertificateParsed.java | package bluecrystal.domain.rest;
import java.util.Arrays;
import bluecrystal.domain.NameValue;
public class ResponseCertificateParsed {
private NameValue[] certificate;
// @DynamoDBAttribute(attributeName="subjectRdn")
private NameValue[] subjectRdn;
private NameValue[] issuerRdn;
private int status;
public ResponseCertificateParsed() {
super();
// TODO Auto-generated constructor stub
}
public ResponseCertificateParsed(NameValue[] certificate, NameValue[] subjectRdn, NameValue[] issuerRdn,
int status) {
super();
this.certificate = certificate;
this.subjectRdn = subjectRdn;
this.issuerRdn = issuerRdn;
this.status = status;
}
public NameValue[] getCertificate() {
return certificate;
}
public void setCertificate(NameValue[] certificate) {
this.certificate = certificate;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public NameValue[] getSubjectRdn() {
return subjectRdn;
}
public void setSubjectRdn(NameValue[] subjectRdn) {
this.subjectRdn = subjectRdn;
}
public NameValue[] getIssuerRdn() {
return issuerRdn;
}
public void setIssuerRdn(NameValue[] issuerRdn) {
this.issuerRdn = issuerRdn;
}
@Override
public String toString() {
return "ResponseCertificateParsed [certificate=" + Arrays.toString(certificate) + ",\nsubjectRdn="
+ Arrays.toString(subjectRdn) + ",\nissuerRdn=" + Arrays.toString(issuerRdn) + ",\nstatus=" + status
+ "]";
}
}
|
0 | java-sources/al/bluecryst/bluecrystal.deps.domain/1.16.0/bluecrystal/domain | java-sources/al/bluecryst/bluecrystal.deps.domain/1.16.0/bluecrystal/domain/rest/ResponseEnvelope.java | package bluecrystal.domain.rest;
public class ResponseEnvelope {
private String signedContent;
private int signStatus;
private String statusMessage;
private String certB64;
private String certSubject;
public ResponseEnvelope() {
super();
// TODO Auto-generated constructor stub
}
public ResponseEnvelope(String signedContent, int signStatus, String statusMessage, String certB64,
String certSubject) {
super();
this.signedContent = signedContent;
this.signStatus = signStatus;
this.statusMessage = statusMessage;
this.certB64 = certB64;
this.certSubject = certSubject;
}
public String getSignedContent() {
return signedContent;
}
public void setSignedContent(String signedContent) {
this.signedContent = signedContent;
}
public int getSignStatus() {
return signStatus;
}
public void setSignStatus(int signStatus) {
this.signStatus = signStatus;
}
public String getStatusMessage() {
return statusMessage;
}
public void setStatusMessage(String statusMessage) {
this.statusMessage = statusMessage;
}
public String getCertB64() {
return certB64;
}
public void setCertB64(String certB64) {
this.certB64 = certB64;
}
public String getCertSubject() {
return certSubject;
}
public void setCertSubject(String certSubject) {
this.certSubject = certSubject;
}
@Override
public String toString() {
return "ResponseEnvelope [signedContent=" + signedContent + ", signStatus=" + signStatus + ", statusMessage="
+ statusMessage + ", certB64=" + certB64 + ", certSubject=" + certSubject + "]";
}
}
|
0 | java-sources/al/bluecryst/bluecrystal.deps.domain/1.16.0/bluecrystal/domain | java-sources/al/bluecryst/bluecrystal.deps.domain/1.16.0/bluecrystal/domain/rest/ResponseEnvelopeSigner.java | package bluecrystal.domain.rest;
public class ResponseEnvelopeSigner {
private String certificateB64;
public ResponseEnvelopeSigner() {
super();
// TODO Auto-generated constructor stub
}
public ResponseEnvelopeSigner(String certificateB64) {
super();
this.certificateB64 = certificateB64;
}
public String getCertificateB64() {
return certificateB64;
}
public void setCertificateB64(String certificateB64) {
this.certificateB64 = certificateB64;
}
@Override
public String toString() {
return "ResponseEnvelopeSigner [certificateB64=" + certificateB64 + "]";
}
}
|
0 | java-sources/al/bluecryst/bluecrystal.deps.domain/1.16.0/bluecrystal/domain | java-sources/al/bluecryst/bluecrystal.deps.domain/1.16.0/bluecrystal/domain/rest/ResponseEnvelopeVerify.java | package bluecrystal.domain.rest;
public class ResponseEnvelopeVerify {
@Override
public String toString() {
return "ResponseEnvelopeVerify [signStatus=" + signStatus
+ ",\nstatusMessage=" + statusMessage + ",\ncertB64=" + certB64 + ",\ncertSubject=" + certSubject + "]";
}
private int signStatus;
private String statusMessage;
private String certB64;
private String certSubject;
public ResponseEnvelopeVerify() {
super();
}
public ResponseEnvelopeVerify(int signStatus, String statusMessage, String certB64, String certSubject) {
super();
this.signStatus = signStatus;
this.statusMessage = statusMessage;
this.certB64 = certB64;
this.certSubject = certSubject;
}
public int getSignStatus() {
return signStatus;
}
public void setSignStatus(int signStatus) {
this.signStatus = signStatus;
}
public String getStatusMessage() {
return statusMessage;
}
public void setStatusMessage(String statusMessage) {
this.statusMessage = statusMessage;
}
public String getCertB64() {
return certB64;
}
public void setCertB64(String certB64) {
this.certB64 = certB64;
}
public String getCertSubject() {
return certSubject;
}
public void setCertSubject(String certSubject) {
this.certSubject = certSubject;
}
}
|
0 | java-sources/al/bluecryst/bluecrystal.deps.domain/1.16.0/bluecrystal/domain | java-sources/al/bluecryst/bluecrystal.deps.domain/1.16.0/bluecrystal/domain/rest/ResponseJwtPostSigned.java | package bluecrystal.domain.rest;
public class ResponseJwtPostSigned {
private String postSign;
public ResponseJwtPostSigned() {
super();
}
public ResponseJwtPostSigned(String postSign) {
super();
this.postSign = postSign;
}
public String getPostSign() {
return postSign;
}
public void setPostSign(String postSign) {
this.postSign = postSign;
}
@Override
public String toString() {
return "ResponseJwtPostSigned [postSign=" + postSign + "]";
}
}
|
0 | java-sources/al/bluecryst/bluecrystal.deps.domain/1.16.0/bluecrystal/domain | java-sources/al/bluecryst/bluecrystal.deps.domain/1.16.0/bluecrystal/domain/rest/ResponseJwtPreSigned.java | package bluecrystal.domain.rest;
public class ResponseJwtPreSigned {
private String preSign;
public ResponseJwtPreSigned(String preSign) {
super();
this.preSign = preSign;
}
public ResponseJwtPreSigned() {
super();
}
public String getPreSign() {
return preSign;
}
@Override
public String toString() {
return "ResponseJwtPreSigned [preSign=" + preSign + "]";
}
public void setPreSign(String preSign) {
this.preSign = preSign;
}
}
|
0 | java-sources/al/bluecryst/bluecrystal.deps.domain/1.16.0/bluecrystal/domain | java-sources/al/bluecryst/bluecrystal.deps.domain/1.16.0/bluecrystal/domain/rest/ResponseSignable.java | package bluecrystal.domain.rest;
public class ResponseSignable {
private String timeValue;
private String saValue;
public ResponseSignable() {
super();
// TODO Auto-generated constructor stub
}
public ResponseSignable(String timeValue, String saValue) {
super();
this.timeValue = timeValue;
this.saValue = saValue;
}
public String getTimeValue() {
return timeValue;
}
public void setTimeValue(String timeValue) {
this.timeValue = timeValue;
}
public String getSaValue() {
return saValue;
}
public void setSaValue(String saValue) {
this.saValue = saValue;
}
@Override
public String toString() {
return "ResponseSignable [timeValue=" + timeValue + ", saValue=" + saValue + "]";
}
}
|
0 | java-sources/al/bluecryst/bluecrystal.deps.service/1.16.0/bluecrystal/service | java-sources/al/bluecryst/bluecrystal.deps.service/1.16.0/bluecrystal/service/exception/ExpiredSessionException.java | /*
Blue Crystal: Document Digital Signature Tool
Copyright (C) 2007-2015 Sergio Leal
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package bluecrystal.service.exception;
public class ExpiredSessionException extends Exception {
public ExpiredSessionException() {
super();
// TODO Auto-generated constructor stub
}
public ExpiredSessionException(String message, Throwable cause) {
super(message, cause);
// TODO Auto-generated constructor stub
}
public ExpiredSessionException(String message) {
super(message);
// TODO Auto-generated constructor stub
}
public ExpiredSessionException(Throwable cause) {
super(cause);
// TODO Auto-generated constructor stub
}
}
|
0 | java-sources/al/bluecryst/bluecrystal.deps.service/1.16.0/bluecrystal/service | java-sources/al/bluecryst/bluecrystal.deps.service/1.16.0/bluecrystal/service/exception/InvalidSigntureException.java | /*
Blue Crystal: Document Digital Signature Tool
Copyright (C) 2007-2015 Sergio Leal
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package bluecrystal.service.exception;
public class InvalidSigntureException extends Exception {
int status;
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public InvalidSigntureException() {
super();
}
public InvalidSigntureException(String message, Throwable cause) {
super(message, cause);
}
public InvalidSigntureException(String message) {
super(message);
}
public InvalidSigntureException(Throwable cause) {
super(cause);
}
}
|
0 | java-sources/al/bluecryst/bluecrystal.deps.service/1.16.0/bluecrystal/service | java-sources/al/bluecryst/bluecrystal.deps.service/1.16.0/bluecrystal/service/exception/LicenseNotFoundExeception.java | /*
Blue Crystal: Document Digital Signature Tool
Copyright (C) 2007-2015 Sergio Leal
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package bluecrystal.service.exception;
public class LicenseNotFoundExeception extends Exception {
public LicenseNotFoundExeception() {
super();
// TODO Auto-generated constructor stub
}
public LicenseNotFoundExeception(String arg0, Throwable arg1) {
super(arg0, arg1);
// TODO Auto-generated constructor stub
}
public LicenseNotFoundExeception(String arg0) {
super(arg0);
// TODO Auto-generated constructor stub
}
public LicenseNotFoundExeception(Throwable arg0) {
super(arg0);
// TODO Auto-generated constructor stub
}
}
|
0 | java-sources/al/bluecryst/bluecrystal.deps.service/1.16.0/bluecrystal/service | java-sources/al/bluecryst/bluecrystal.deps.service/1.16.0/bluecrystal/service/exception/LoginErrorException.java | /*
Blue Crystal: Document Digital Signature Tool
Copyright (C) 2007-2015 Sergio Leal
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package bluecrystal.service.exception;
public class LoginErrorException extends Exception {
public LoginErrorException() {
super();
// TODO Auto-generated constructor stub
}
public LoginErrorException(String message, Throwable cause) {
super(message, cause);
// TODO Auto-generated constructor stub
}
public LoginErrorException(String message) {
super(message);
// TODO Auto-generated constructor stub
}
public LoginErrorException(Throwable cause) {
super(cause);
// TODO Auto-generated constructor stub
}
}
|
0 | java-sources/al/bluecryst/bluecrystal.deps.service/1.16.0/bluecrystal/service | java-sources/al/bluecryst/bluecrystal.deps.service/1.16.0/bluecrystal/service/exception/OCSPQueryException.java | /*
Blue Crystal: Document Digital Signature Tool
Copyright (C) 2007-2015 Sergio Leal
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package bluecrystal.service.exception;
public class OCSPQueryException extends Exception {
public OCSPQueryException() {
super();
// TODO Auto-generated constructor stub
}
public OCSPQueryException(String message, Throwable cause) {
super(message, cause);
// TODO Auto-generated constructor stub
}
public OCSPQueryException(String message) {
super(message);
// TODO Auto-generated constructor stub
}
public OCSPQueryException(Throwable cause) {
super(cause);
// TODO Auto-generated constructor stub
}
}
|
0 | java-sources/al/bluecryst/bluecrystal.deps.service/1.16.0/bluecrystal/service | java-sources/al/bluecryst/bluecrystal.deps.service/1.16.0/bluecrystal/service/exception/RevokedException.java | /*
Blue Crystal: Document Digital Signature Tool
Copyright (C) 2007-2015 Sergio Leal
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package bluecrystal.service.exception;
public class RevokedException extends Exception {
}
|
0 | java-sources/al/bluecryst/bluecrystal.deps.service/1.16.0/bluecrystal/service | java-sources/al/bluecryst/bluecrystal.deps.service/1.16.0/bluecrystal/service/exception/UndefStateException.java | /*
Blue Crystal: Document Digital Signature Tool
Copyright (C) 2007-2015 Sergio Leal
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package bluecrystal.service.exception;
public class UndefStateException extends Exception {
}
|
0 | java-sources/al/bluecryst/bluecrystal.deps.service/1.16.0/bluecrystal/service | java-sources/al/bluecryst/bluecrystal.deps.service/1.16.0/bluecrystal/service/exception/package-info.java | /**
*
*/
/**
* @author sergio
*
*/
package bluecrystal.service.exception; |
0 | java-sources/al/bluecryst/bluecrystal.deps.service/1.16.0/bluecrystal/service | java-sources/al/bluecryst/bluecrystal.deps.service/1.16.0/bluecrystal/service/helper/package-info.java | /**
*
*/
/**
* @author sergio
*
*/
package bluecrystal.service.helper; |
0 | java-sources/al/bluecryst/bluecrystal.deps.service/1.16.0/bluecrystal/service | java-sources/al/bluecryst/bluecrystal.deps.service/1.16.0/bluecrystal/service/interfaces/RepoLoader.java | /*
Blue Crystal: Document Digital Signature Tool
Copyright (C) 2007-2015 Sergio Leal
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package bluecrystal.service.interfaces;
import java.io.InputStream;
public interface RepoLoader {
public abstract InputStream load(String key) throws Exception;
public abstract InputStream loadFromContent(String key);
public abstract String Put(InputStream input, String key);
public abstract String PutInSupport(InputStream input, String key);
public abstract String PutInContent(InputStream input, String key);
public abstract String checkContentByHash(String sha256);
public abstract String PutIn(InputStream input, String key, String bucket);
public abstract String PutDirect(InputStream input, String key,
String bucket);
public abstract String createAuthUrl(String object) throws Exception;
public abstract boolean isDir(String object) throws Exception;
String[] list(String object) throws Exception;
boolean exists(String object) throws Exception;
String getFullPath(String object);
} |
0 | java-sources/al/bluecryst/bluecrystal.deps.service/1.16.0/bluecrystal/service | java-sources/al/bluecryst/bluecrystal.deps.service/1.16.0/bluecrystal/service/interfaces/package-info.java | /**
*
*/
/**
* @author sergio
*
*/
package bluecrystal.service.interfaces; |
0 | java-sources/al/bluecryst/bluecrystal.deps.service/1.16.0/bluecrystal/service | java-sources/al/bluecryst/bluecrystal.deps.service/1.16.0/bluecrystal/service/jwt/AppAlgorithm.java | package bluecrystal.service.jwt;
import com.auth0.jwt.JWTAlgorithmException;
public enum AppAlgorithm {
HS256("HmacSHA256"), HS384("HmacSHA384"), HS512("HmacSHA512"), RS256("SHA256withRSA"), RS384(
"SHA384withRSA"), RS512("SHA512withRSA");
private AppAlgorithm(final String value) {
this.value = value;
}
private String value;
public String getValue() {
return value;
}
public static AppAlgorithm findByName(final String name) throws JWTAlgorithmException {
try {
return AppAlgorithm.valueOf(name);
} catch (IllegalArgumentException e) {
throw new JWTAlgorithmException("Unsupported algorithm: " + name);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.