repo
stringlengths 1
191
⌀ | file
stringlengths 23
351
| code
stringlengths 0
5.32M
| file_length
int64 0
5.32M
| avg_line_length
float64 0
2.9k
| max_line_length
int64 0
288k
| extension_type
stringclasses 1
value |
---|---|---|---|---|---|---|
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/tests/headless/ErrorSpecification.java | package tests.headless;
import java.util.ArrayList;
import java.util.List;
import tests.headless.FindingsType.FalseNegatives;
import tests.headless.FindingsType.FalsePositives;
import tests.headless.FindingsType.TruePositives;
public class ErrorSpecification {
private String methodSignature;
private List<TruePositives> truePositives;
private List<FalsePositives> falsePositives;
private List<FalseNegatives> falseNegatives;
private Class<?> errorType;
public ErrorSpecification(String methodSignature, Class<?> errorType, List<TruePositives> truePositives, List<FalsePositives> falsePositives,
List<FalseNegatives> falseNegatives) {
this.methodSignature = methodSignature;
this.errorType = errorType;
this.truePositives = truePositives;
this.falsePositives = falsePositives;
this.falseNegatives = falseNegatives;
}
public ErrorSpecification(String methodSignature) {
this.methodSignature = methodSignature;
this.truePositives = new ArrayList<TruePositives>();
this.falseNegatives = new ArrayList<FalseNegatives>();
this.falsePositives = new ArrayList<FalsePositives>();
}
public Class<?> getErrorType() {
return errorType;
}
public void setErrorType(Class<?> errorType) {
this.errorType = errorType;
}
public String getMethodSignature() {
return methodSignature;
}
public void setMethodSignature(String methodSignature) {
this.methodSignature = methodSignature;
}
public List<TruePositives> getTruePositives() {
return truePositives;
}
public void setTruePositives(List<TruePositives> truePositives) {
this.truePositives = truePositives;
}
public List<FalsePositives> getFalsePositives() {
return falsePositives;
}
public void setFalsePositives(List<FalsePositives> falsePositives) {
this.falsePositives = falsePositives;
}
public List<FalseNegatives> getFalseNegatives() {
return falseNegatives;
}
public void setFalseNegatives(List<FalseNegatives> falseNegatives) {
this.falseNegatives = falseNegatives;
}
public int getTotalNumberOfFindings() {
int totalFindings = 0;
totalFindings += truePositives == null ? 0 : truePositives.size();
totalFindings += falsePositives == null ? 0 : falsePositives.size();
totalFindings += falseNegatives == null ? 0 : falseNegatives.size();
if (totalFindings == 0)
throw new IllegalArgumentException("Specify atleast one findings type.");
return totalFindings;
}
public static class Builder {
private ErrorSpecification spec;
public Builder(String methodSignature) {
this.spec = new ErrorSpecification(methodSignature);
}
public Builder withTPs(Class<?> errorType, int numberOfFindings) {
this.spec.truePositives.add(new TruePositives(errorType, numberOfFindings));
return this;
}
public Builder withFPs(Class<?> errorType, int numberOfFindings, String explanation) {
this.spec.falsePositives.add(new FalsePositives(errorType, numberOfFindings, explanation));
return this;
}
public Builder withFNs(Class<?> errorType, int numberOfFindings, String explanation) {
this.spec.falseNegatives.add(new FalseNegatives(errorType, numberOfFindings, explanation));
return this;
}
public ErrorSpecification build() {
return spec;
}
}
}
| 3,226 | 30.330097 | 142 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/tests/headless/ExternalTest.java | package tests.headless;
import java.io.File;
import java.util.List;
import com.google.common.collect.Lists;
import org.junit.Ignore;
import org.junit.Test;
import crypto.HeadlessCryptoScanner;
import crypto.exceptions.CryptoAnalysisException;
import crypto.rules.CrySLRule;
import crypto.rules.CrySLRuleReader;
public class ExternalTest {
@Ignore
@Test
public void testExternal(){
HeadlessCryptoScanner scanner = new HeadlessCryptoScanner() {
@Override
protected String applicationClassPath() {
return "YOUR/PATH";
}
@Override
protected List<CrySLRule> getRules() {
try {
return CrySLRuleReader.readFromDirectory(new File("./src/main/resources/JavaCryptographicArchitecture"));
} catch (CryptoAnalysisException e) {
e.printStackTrace();
}
return Lists.newArrayList();
}
};
scanner.exec();
}
}
| 859 | 19.97561 | 110 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/tests/headless/FindingsType.java | package tests.headless;
public class FindingsType {
private int numberOfFindings;
private FindingsType(int numberOfFindings) {
this.numberOfFindings = numberOfFindings;
}
public int getNumberOfFindings() {
return numberOfFindings;
}
public static final class TruePositives extends FindingsType {
private Class<?> errorType;
public TruePositives(int numberOfFindings) {
super(numberOfFindings);
}
public TruePositives(Class<?> errorType, int numberOfFindings) {
super(numberOfFindings);
this.errorType = errorType;
}
public Class<?> getErrorType(){
return errorType;
}
@Override
public String toString() {
return "TruePositives(" + getNumberOfFindings() + ")";
}
}
public static class FalsePositives extends FindingsType {
private String explanation;
private Class<?> errorType;
public FalsePositives(int numberOfFindings, String explanation) {
super(numberOfFindings);
this.explanation = explanation;
}
public FalsePositives(Class<?> errorType, int numberOfFindings, String explanation) {
super(numberOfFindings);
this.explanation = explanation;
this.errorType = errorType;
}
public Class<?> getErrorType(){
return errorType;
}
public String getExplanation() {
return explanation;
};
@Override
public String toString() {
return "FalsePositives(" + getNumberOfFindings() + ")";
}
}
public static class FalseNegatives extends FindingsType {
private String explanation;
private Class<?> errorType;
public FalseNegatives(int numberOfFindings, String explanation) {
super(numberOfFindings);
this.explanation = explanation;
}
public FalseNegatives(Class<?> errorType, int numberOfFindings, String explanation) {
super(numberOfFindings);
this.explanation = explanation;
this.errorType = errorType;
}
public Class<?> getErrorType(){
return errorType;
}
public String getExplanation() {
return explanation;
};
@Override
public String toString() {
return "FalsePositives(" + getNumberOfFindings() + ")";
}
}
public static class NoFalseNegatives extends FalseNegatives {
public NoFalseNegatives() {
super(0, "No false negatives, no explanation required!");
}
@Override
public String toString() {
return "No False Negatives";
}
}
public static class NoFalsePositives extends FalsePositives {
public NoFalsePositives() {
super(0, "No false positives, no explanation required!");
}
@Override
public String toString() {
return "No False Positives";
}
}
}
| 2,572 | 20.264463 | 87 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/tests/headless/MUBenchExamplesTest.java | package tests.headless;
import java.io.File;
import org.junit.Test;
import crypto.HeadlessCryptoScanner;
import crypto.analysis.errors.ConstraintError;
import crypto.analysis.errors.IncompleteOperationError;
import crypto.analysis.errors.RequiredPredicateError;
import crypto.analysis.errors.TypestateError;
/**
* @author Enri Ozuni
*/
public class MUBenchExamplesTest extends AbstractHeadlessTest{
/**
* The following Headless tests are deducted from the MUBench benchmarking tool
* that detects various API misuses. For the creating these Headless tests, only
* previous Cryptographic API misuses were considered from the data-set of MUBench,
* which contains numerous projects having these kind of API misuses.
*/
@Test
public void muBenchExamples() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/MUBenchExamples").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
/**
* The links for each test case redirect to the description of the misuse,
* and also contain the correct usage of the corresponding misuse in the directory
* where `misuse.yml` file is contained
*/
// This test case corresponds to the following project in MUBench having this misuse:
// https://github.com/akwick/MUBench/blob/master/data/tap-apps/misuses/1/misuse.yml
setErrorsCount("<example.CipherUsesBlowfishExample: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<example.CipherUsesBlowfishExample: void main(java.lang.String[])>", IncompleteOperationError.class, 1);
// This test case corresponds to the following project in MUBench having this misuse:
// https://github.com/akwick/MUBench/blob/master/data/drftpd3-extended/misuses/1/misuse.yml
setErrorsCount("<example.CipherUsesBlowfishWithECBModeExample: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<example.CipherUsesBlowfishWithECBModeExample: void main(java.lang.String[])>", IncompleteOperationError.class, 1);
// This test case corresponds to the following project in MUBench having this misuse:
// https://github.com/akwick/MUBench/blob/master/data/chensun/misuses/1/misuse.yml
setErrorsCount("<example.CipherUsesDESExample: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<example.CipherUsesDESExample: void main(java.lang.String[])>", IncompleteOperationError.class, 1);
// This test case corresponds to the following project in MUBench having this misuse:
// https://github.com/akwick/MUBench/blob/master/data/secure-tcp/misuses/1/misuse.yml
setErrorsCount("<example.CipherUsesDSAExample: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<example.CipherUsesDSAExample: void main(java.lang.String[])>", IncompleteOperationError.class, 1);
// This test case corresponds to the following project in MUBench having the this misuse:
// https://github.com/akwick/MUBench/blob/master/data/corona-old/misuses/1/misuse.yml
setErrorsCount("<example.CipherUsesJustAESExample: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<example.CipherUsesJustAESExample: void main(java.lang.String[])>", IncompleteOperationError.class, 1);
// This test case corresponds to the following project in MUBench having this misuse:
// https://github.com/akwick/MUBench/blob/master/data/chensun/misuses/2/misuse.yml
setErrorsCount("<example.CipherUsesNonRandomKeyExample: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
// This test case corresponds to the following project in MUBench having this misuse:
// https://github.com/akwick/MUBench/blob/master/data/minecraft-launcher/misuses/1/misuse.yml
setErrorsCount("<example.CipherUsesPBEWithMD5AndDESExample: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<example.CipherUsesPBEWithMD5AndDESExample: void main(java.lang.String[])>", IncompleteOperationError.class, 1);
// This test case corresponds to the following project in MUBench having this misuse:
// https://github.com/akwick/MUBench/blob/master/data/dalvik/misuses/3/misuse.yml
// **MUBench hints that using RSA with PKCS1Padding is unsafe, which the Cipher CrySL rule
// does not agree, so added the test case of using RSA with CBC mode**
setErrorsCount("<example.CipherUsesRSAWithCBCExample: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<example.CipherUsesRSAWithCBCExample: void main(java.lang.String[])>", IncompleteOperationError.class, 1);
// This test case corresponds to the following project in MUBench having this misuse:
// https://github.com/akwick/MUBench/blob/master/data/pawotag/misuses/1/misuse.yml
setErrorsCount("<example.EmptyArrayUsedForCipherDoFinalExample: void main(java.lang.String[])>", ConstraintError.class, 1);
// This test case corresponds to the following project in MUBench having this misuse:
// https://github.com/akwick/MUBench/blob/master/data/red5-server/misuses/1/misuse.yml
setErrorsCount("<example.InitInMacCalledMoreThanOnceExample: void main(java.lang.String[])>", TypestateError.class, 2);
setErrorsCount("<example.InitInMacCalledMoreThanOnceExample: void main(java.lang.String[])>", IncompleteOperationError.class, 1);
scanner.exec();
assertErrors();
}
}
| 5,422 | 56.691489 | 133 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/tests/headless/MavenProject.java | package tests.headless;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import org.apache.commons.io.IOUtils;
import org.apache.maven.shared.invoker.DefaultInvocationRequest;
import org.apache.maven.shared.invoker.DefaultInvoker;
import org.apache.maven.shared.invoker.InvocationRequest;
import org.apache.maven.shared.invoker.InvocationResult;
import org.apache.maven.shared.invoker.Invoker;
import org.apache.maven.shared.invoker.MavenInvocationException;
import org.apache.maven.shared.invoker.PrintStreamHandler;
import com.google.common.collect.Lists;
public class MavenProject {
private String pathToProjectRoot;
private boolean compiled;
private String fullProjectClassPath;
public MavenProject(String pathToProjectRoot) {
File file = new File(pathToProjectRoot);
if(!file.exists())
throw new RuntimeException("The path " + pathToProjectRoot + " does not exist!");
this.pathToProjectRoot = new File(pathToProjectRoot).getAbsolutePath();
}
public void compile(){
InvocationRequest request = new DefaultInvocationRequest();
request.setPomFile( new File(pathToProjectRoot+File.separator+"pom.xml" ) );
ArrayList<String> goals = Lists.newArrayList();
goals.add("clean");
goals.add("compile");
request.setGoals(goals);
Invoker invoker = new DefaultInvoker();
try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream out = new PrintStream(baos)) {
request.setOutputHandler(new PrintStreamHandler(out, true));
InvocationResult res = invoker.execute( request );
if(res.getExitCode() != 0) {
throw new RuntimeException("Was not able to compile project " + pathToProjectRoot +".");
}
} catch (MavenInvocationException | IOException e) {
throw new RuntimeException("Was not able to invoke maven in path " + pathToProjectRoot +". Does a pom.xml exist?");
}
compiled = true;
computeClassPath();
}
private void computeClassPath() {
InvocationRequest request = new DefaultInvocationRequest();
request.setPomFile( new File(pathToProjectRoot+File.separator+"pom.xml" ) );
ArrayList<String> goals = Lists.newArrayList();
goals.add("dependency:build-classpath");
goals.add("-Dmdep.outputFile=\"classPath.temp\"");
try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream out = new PrintStream(baos)) {
request.setOutputHandler(new PrintStreamHandler(out, true));
request.setGoals(goals);
Invoker invoker = new DefaultInvoker();InvocationResult res = invoker.execute( request );
if(res.getExitCode() != 0) {
throw new RuntimeException("Was not able to compute dependencies " + pathToProjectRoot +".");
}
} catch (MavenInvocationException | IOException e) {
throw new RuntimeException("Was not able to invoke maven to compute depenencies");
}
try {
File classPathFile = new File(pathToProjectRoot+File.separator+"classPath.temp");
fullProjectClassPath = IOUtils.toString(new FileInputStream(classPathFile), "utf-8");
classPathFile.delete();
} catch (IOException e) {
throw new RuntimeException("Was not able to read in class path from file classPath.temp");
}
}
public String getBuildDirectory() {
if(!compiled) {
throw new RuntimeException("You first have to compile the project. Use method compile()");
}
String buildPath = pathToProjectRoot + File.separator +"target"+File.separator +"classes";
return buildPath;
}
public String getFullClassPath() {
return fullProjectClassPath;
}
}
| 3,690 | 38.265957 | 118 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/tests/headless/MessageDigestExampleTest.java | package tests.headless;
import java.io.File;
import org.junit.Test;
import crypto.HeadlessCryptoScanner;
import crypto.analysis.errors.IncompleteOperationError;
public class MessageDigestExampleTest extends AbstractHeadlessTest{
@Test
public void loadMessageDigestExample() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/MessageDigestExample").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
//false positive
setErrorsCount("<MessageDigestExample.MessageDigestExample.Main: java.lang.String getSHA256(java.io.InputStream)>", IncompleteOperationError.class, 2);
scanner.exec();
assertErrors();
}
}
| 738 | 27.423077 | 153 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/tests/headless/ReportFormatTest.java | package tests.headless;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Assert;
import org.junit.Test;
import crypto.HeadlessCryptoScanner;
import crypto.analysis.CryptoScannerSettings.ReportFormat;
public class ReportFormatTest extends AbstractHeadlessTest{
private static final String rootPath = "cognicrypt-output/";
private static final String txtReportPath = rootPath+"CryptoAnalysis-Report.txt";
private static final String csvReportPath = rootPath+"CryptoAnalysis-Report.csv";
private static final String sarifReportPath = rootPath+"CryptoAnalysis-Report.json";
@Test
public void TXTReportCreationTest() {
File report = new File(txtReportPath);
if(report.exists()) {
report.delete();
}
String mavenProjectPath = new File("../CryptoAnalysisTargets/ReportFormatExample").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
setReportFormat(ReportFormat.TXT);
setVISUALIZATION(true);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
scanner.exec();
Assert.assertTrue(report.exists());
}
@Test
public void CSVReportCreationTest() {
File report = new File(csvReportPath);
if(report.exists()) {
report.delete();
}
String mavenProjectPath = new File("../CryptoAnalysisTargets/ReportFormatExample").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
setReportFormat(ReportFormat.CSV);
setVISUALIZATION(true);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
scanner.exec();
Assert.assertTrue(report.exists());
}
@Test
public void SARIFReportCreationTest() {
File report = new File(sarifReportPath);
if(report.exists()) {
report.delete();
}
String mavenProjectPath = new File("../CryptoAnalysisTargets/ReportFormatExample").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
setReportFormat(ReportFormat.SARIF);
setVISUALIZATION(true);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
scanner.exec();
Assert.assertTrue(report.exists());
}
@After
public void tearDown() {
try {
FileUtils.deleteDirectory(new File(rootPath));
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 2,298 | 29.653333 | 103 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/tests/headless/ReportedIssueTest.java | package tests.headless;
import java.io.File;
import org.junit.Test;
import crypto.HeadlessCryptoScanner;
import crypto.analysis.errors.ConstraintError;
import crypto.analysis.errors.HardCodedError;
import crypto.analysis.errors.IncompleteOperationError;
import crypto.analysis.errors.NeverTypeOfError;
import crypto.analysis.errors.RequiredPredicateError;
public class ReportedIssueTest extends AbstractHeadlessTest {
@Test
public void reportedIssues() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/ReportedIssues").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
setErrorsCount("<issueseeds.Main: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
setErrorsCount("<issue81.Encryption: byte[] encrypt(byte[],javax.crypto.SecretKey)>", ConstraintError.class, 1);
setErrorsCount("<issue81.Encryption: byte[] encrypt(byte[],javax.crypto.SecretKey)>", RequiredPredicateError.class, 1);
setErrorsCount("<issue81.Encryption: javax.crypto.SecretKey generateKey(java.lang.String)>", IncompleteOperationError.class, 1);
setErrorsCount("<issue81.Encryption: javax.crypto.SecretKey generateKey(java.lang.String)>", RequiredPredicateError.class, 3);
setErrorsCount("<issue81.Encryption: javax.crypto.SecretKey generateKey(java.lang.String)>", NeverTypeOfError.class, 1);
setErrorsCount("<issue81.Encryption: javax.crypto.SecretKey generateKey(java.lang.String)>", ConstraintError.class, 1);
setErrorsCount("<issue81.Encryption: javax.crypto.SecretKey generateKey(java.lang.String)>", HardCodedError.class, 1);
setErrorsCount("<issue81.Main: void main(java.lang.String[])>", IncompleteOperationError.class, 1);
setErrorsCount("<issue81.Main: void main(java.lang.String[])>", NeverTypeOfError.class, 1);
setErrorsCount("<issue81.Main: void main(java.lang.String[])>", HardCodedError.class, 1);
setErrorsCount("<issuecognicrypt210.CogniCryptSecretKeySpec: void main(java.lang.String[])>", ConstraintError.class, 0);
setErrorsCount("<issuecognicrypt210.CogniCryptSecretKeySpec: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
setErrorsCount("<issuecognicrypt210.CogniCryptSecretKeySpec: void main(java.lang.String[])>", HardCodedError.class, 1);
setErrorsCount("<issue70.ClientProtocolDecoder: byte[] decryptAES(byte[])>", ConstraintError.class, 1);
setErrorsCount("<issue70.ClientProtocolDecoder: byte[] decryptAES(byte[])>", RequiredPredicateError.class, 3);
setErrorsCount("<issue68.Main: void main(java.lang.String[])>", IncompleteOperationError.class, 2);
setErrorsCount("<issue68.AESCryptor: byte[] getKey(java.lang.String)>", NeverTypeOfError.class, 1);
setErrorsCount("<issue68.AESCryptor: byte[] getKey(java.lang.String)>", RequiredPredicateError.class, 2);
setErrorsCount("<issue68.AESCryptor: byte[] getKey(java.lang.String)>", IncompleteOperationError.class, 1);
setErrorsCount("<issue68.AESCryptor: byte[] getKey(java.lang.String)>", HardCodedError.class, 1);
setErrorsCount("<issue68.AESCryptor: javax.crypto.SecretKeyFactory getFactory()>", ConstraintError.class, 1);
setErrorsCount("<issue68.AESCryptor: byte[] encryptImpl(byte[])>", RequiredPredicateError.class, 1);
setErrorsCount("<issue68.AESCryptor: void <init>(byte[])>", RequiredPredicateError.class, 1);
setErrorsCount("<issue68.AESCryptor: byte[] decryptImpl(byte[])>", RequiredPredicateError.class, 2);
setErrorsCount("<issue49.Main: java.security.PrivateKey getPrivateKey()>", ConstraintError.class, 1);
setErrorsCount("<issue49.Main: byte[] sign(java.lang.String)>", RequiredPredicateError.class, 1);
setErrorsCount("<issue103.Main: void main(java.lang.String[])>", RequiredPredicateError.class, 4);
setErrorsCount("<issue137.Program: void main(java.lang.String[])>", ConstraintError.class, 2);
setErrorsCount("<issue137.Program: void main(java.lang.String[])>", IncompleteOperationError.class, 0);
scanner.exec();
assertErrors();
}
}
| 4,036 | 60.166667 | 130 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/tests/headless/SootJava9ConfigurationTest.java | package tests.headless;
import static org.junit.Assume.assumeTrue;
import java.io.File;
import org.junit.Before;
import org.junit.Test;
import crypto.HeadlessCryptoScanner;
import crypto.analysis.CrySLRulesetSelector.Ruleset;
import crypto.analysis.errors.ConstraintError;
import crypto.analysis.errors.IncompleteOperationError;
import crypto.analysis.errors.RequiredPredicateError;
import crypto.analysis.errors.TypestateError;
public class SootJava9ConfigurationTest extends AbstractHeadlessTest {
@Before
public void checkJavaVersion() {
assumeTrue(getVersion() >= 9);
}
private static int getVersion() {
String version = System.getProperty("java.version");
if(version.startsWith("1.")) {
version = version.substring(2, 3);
} else {
int dot = version.indexOf(".");
if(dot != -1) { version = version.substring(0, dot); }
} return Integer.parseInt(version);
}
@Test
public void testJava9ClasspathProject() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/Java9ClasspathExample").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject, Ruleset.JavaCryptographicArchitecture);
setErrorsCount("<ConstraintErrorExample: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<ConstraintErrorExample: void main(java.lang.String[])>", IncompleteOperationError.class, 1);
scanner.exec();
assertErrors();
}
@Test
public void testJava8Project() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/CogniCryptDemoExample").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject, Ruleset.JavaCryptographicArchitecture);
setErrorsCount("<example.PredicateMissingExample: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
setErrorsCount("<example.PredicateMissingExample: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<example.IncompleOperationErrorExample: void main(java.lang.String[])>", IncompleteOperationError.class, 1);
setErrorsCount("<example.ConstraintErrorExample: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<example.ConstraintErrorExample: void main(java.lang.String[])>", IncompleteOperationError.class, 1);
setErrorsCount("<example.TypestateErrorExample: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<example.fixed.ConstraintErrorExample: void main(java.lang.String[])>", IncompleteOperationError.class, 1);
scanner.exec();
assertErrors();
}
@Test
public void testJava9ModularProject() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/Java9ModuleExample").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject, Ruleset.JavaCryptographicArchitecture);
setErrorsCount("<org.demo.jpms.MainClass: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<org.demo.jpms.MainClass: void main(java.lang.String[])>", IncompleteOperationError.class, 1);
scanner.exec();
assertErrors();
}
}
| 3,234 | 40.474359 | 126 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/tests/headless/StaticAnalysisDemoTest.java | package tests.headless;
import java.io.File;
import org.junit.Test;
import crypto.HeadlessCryptoScanner;
import crypto.analysis.errors.ConstraintError;
import crypto.analysis.errors.HardCodedError;
import crypto.analysis.errors.IncompleteOperationError;
import crypto.analysis.errors.NeverTypeOfError;
import crypto.analysis.errors.RequiredPredicateError;
import crypto.analysis.errors.TypestateError;
public class StaticAnalysisDemoTest extends AbstractHeadlessTest {
@Test
public void cogniCryptDemoExamples() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/CogniCryptDemoExample").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
setErrorsCount("<example.ConstraintErrorExample: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<example.ConstraintErrorExample: void main(java.lang.String[])>", IncompleteOperationError.class, 1);
setErrorsCount("<example.fixed.ConstraintErrorExample: void main(java.lang.String[])>", IncompleteOperationError.class, 1);
setErrorsCount("<example.PredicateMissingExample: void main(java.lang.String[])>", RequiredPredicateError.class, 1);
setErrorsCount("<example.PredicateMissingExample: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<example.TypestateErrorExample: void main(java.lang.String[])>", TypestateError.class, 1);
setErrorsCount("<example.IncompleOperationErrorExample: void main(java.lang.String[])>", IncompleteOperationError.class, 1);
scanner.exec();
assertErrors();
}
@Test
public void cryptoMisuseExampleProject() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/CryptoMisuseExamples").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
setErrorsCount("<main.Msg: byte[] sign(java.lang.String)>", ConstraintError.class, 1);
setErrorsCount("<main.Msg: byte[] sign(java.lang.String)>", RequiredPredicateError.class, 1);
setErrorsCount("<main.Msg: java.security.PrivateKey getPrivateKey()>", ConstraintError.class, 1);
setErrorsCount("<main.Msg: void encryptAlgFromField()>", ConstraintError.class, 1);
setErrorsCount("<main.Msg: void encryptAlgFromField()>", IncompleteOperationError.class, 1);
setErrorsCount("<main.Msg: void encrypt()>", ConstraintError.class, 1);
setErrorsCount("<main.Msg: void encrypt()>", IncompleteOperationError.class, 1);
setErrorsCount("<main.Msg: void encryptAlgFromVar()>", ConstraintError.class, 1);
setErrorsCount("<main.Msg: void encryptAlgFromVar()>", IncompleteOperationError.class, 1);
setErrorsCount("<main.Encrypt: void incorrectBigInteger()>", ConstraintError.class, 2);
setErrorsCount("<main.Encrypt: void incorrectBigInteger()>", RequiredPredicateError.class, 1);
setErrorsCount("<main.Encrypt: void incorrect()>", ConstraintError.class, 2);
setErrorsCount("<main.Encrypt: void incorrect()>", RequiredPredicateError.class, 1);
scanner.exec();
assertErrors();
}
@Test
public void glassfishExample() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/glassfish-embedded").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
setErrorsCount("<org.glassfish.grizzly.config.ssl.CustomClass: void init(javax.crypto.SecretKey,java.lang.String)>", RequiredPredicateError.class, 1);
setErrorsCount("<org.glassfish.grizzly.config.ssl.CustomClass: void init(javax.crypto.SecretKey,java.lang.String)>", ConstraintError.class, 1);
setErrorsCount("<org.glassfish.grizzly.config.ssl.JSSESocketFactory: java.security.KeyStore getStore(java.lang.String,java.lang.String,java.lang.String)>", NeverTypeOfError.class, 1);
setErrorsCount("<org.glassfish.grizzly.config.ssl.JSSESocketFactory: java.security.KeyStore getStore(java.lang.String,java.lang.String,java.lang.String)>", HardCodedError.class, 1);
scanner.exec();
assertErrors();
}
@Test
public void oracleExample() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/OracleExample").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
//
setErrorsCount("<main.Main: void main(java.lang.String[])>", ConstraintError.class, 1);
setErrorsCount("<main.Main: void main(java.lang.String[])>", TypestateError.class, 2);
setErrorsCount("<main.Main: void main(java.lang.String[])>", RequiredPredicateError.class, 2);
setErrorsCount("<main.Main: void keyStoreExample()>", ConstraintError.class, 1);
setErrorsCount("<main.Main: void keyStoreExample()>", NeverTypeOfError.class, 1);
setErrorsCount("<main.Main: void keyStoreExample()>", HardCodedError.class, 1);
setErrorsCount("<main.Main: void cipherUsageExample()>", ConstraintError.class, 1);
setErrorsCount("<main.Main: void use(javax.crypto.Cipher)>", TypestateError.class, 1);
//TODO this is a spurious finding. What happens here?
setErrorsCount("<Crypto.PWHasher: java.lang.Boolean verifyPWHash(char[],java.lang.String)>", RequiredPredicateError.class, 2);
setErrorsCount("<main.Main: void incorrectKeyForWrongCipher()>", ConstraintError.class, 1);
setErrorsCount("<main.Main: void incorrectKeyForWrongCipher()>", RequiredPredicateError.class, 1);
setErrorsCount("<main.Main: void useWrongDoFinal()>", TypestateError.class, 1);
setErrorsCount("<main.Main: void useWrongDoFinal()>", ConstraintError.class, 1);
setErrorsCount("<main.Main: void useCorrectDoFinal()>", ConstraintError.class, 1);
setErrorsCount("<main.Main: void useNoDoFinal()>", IncompleteOperationError.class, 1);
setErrorsCount("<main.Main: void useNoDoFinal()>", ConstraintError.class, 1);
//TODO: This is wrong.
setErrorsCount("<main.Main: void useDoFinalInLoop()>", TypestateError.class, 0);
setErrorsCount("<main.Main: void useDoFinalInLoop()>", IncompleteOperationError.class, 2);
setErrorsCount("<main.Main: void useDoFinalInLoop()>", ConstraintError.class, 1);
scanner.exec();
assertErrors();
}
@Test
public void sslExample() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/SSLMisuseExample").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
scanner.exec();
assertErrors();
}
}
| 6,533 | 48.12782 | 185 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/tests/headless/TLSRuleTest.java | package tests.headless;
import java.io.File;
import org.junit.Ignore;
import org.junit.Test;
import crypto.HeadlessCryptoScanner;
public class TLSRuleTest extends AbstractHeadlessTest{
@Ignore
@Test
public void secureFileTransmitter() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/SecureFileTransmitter").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
scanner.exec();
assertErrors();
}
}
| 522 | 22.772727 | 105 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/tests/headless/bugfixes/NullpointerPredicateForFields.java | package tests.headless.bugfixes;
import java.io.File;
import org.junit.Test;
import crypto.HeadlessCryptoScanner;
import crypto.analysis.errors.ConstraintError;
import tests.headless.AbstractHeadlessTest;
import tests.headless.MavenProject;
/**
* Refers to https://github.com/CROSSINGTUD/CryptoAnalysis/issues/270
*/
public class NullpointerPredicateForFields extends AbstractHeadlessTest {
@Test
public void issue270() {
String mavenProjectPath = new File("../CryptoAnalysisTargets/Bugfixes/issue270").getAbsolutePath();
MavenProject mavenProject = createAndCompile(mavenProjectPath);
HeadlessCryptoScanner scanner = createScanner(mavenProject);
setErrorsCount("<example.Launcher: void <init>()>", ConstraintError.class, 1);
// Must not throw NullPointerException in ConstraintSolver:init()!
scanner.exec();
assertErrors();
}
}
| 854 | 28.482759 | 101 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/tests/pattern/BouncyCastleTest.java | package tests.pattern;
import java.io.File;
import java.math.BigInteger;
import java.security.GeneralSecurityException;
import java.security.SecureRandom;
import java.util.Random;
import org.bouncycastle.crypto.AsymmetricBlockCipher;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.bouncycastle.crypto.engines.AESEngine;
import org.bouncycastle.crypto.engines.RSAEngine;
import org.bouncycastle.crypto.modes.GCMBlockCipher;
import org.bouncycastle.crypto.params.AEADParameters;
import org.bouncycastle.crypto.params.ECDomainParameters;
import org.bouncycastle.crypto.params.ECPublicKeyParameters;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.crypto.params.ParametersWithIV;
import org.bouncycastle.crypto.params.ParametersWithRandom;
import org.bouncycastle.crypto.params.RSAKeyParameters;
import org.bouncycastle.crypto.params.RSAPrivateCrtKeyParameters;
import org.bouncycastle.math.ec.ECConstants;
import org.bouncycastle.math.ec.ECCurve;
import org.bouncycastle.util.encoders.Hex;
import org.junit.Ignore;
import org.junit.Test;
import crypto.analysis.CrySLRulesetSelector.Ruleset;
import test.UsagePatternTestingFramework;
import test.assertions.Assertions;
public class BouncyCastleTest extends UsagePatternTestingFramework {
@Override
protected Ruleset getRuleSet() {
return Ruleset.BouncyCastle;
}
@Test
public void testEncryptTwo() throws InvalidCipherTextException {
String edgeInput = "ff6f77206973207468652074696d6520666f7220616c6c20676f6f64206d656e";
byte[] data = Hex.decode(edgeInput);
RSAKeyParameters pubParameters = new RSAKeyParameters(false, null, null);
AsymmetricBlockCipher eng = new RSAEngine();
// missing init()
// eng.init(true, pubParameters);
byte[] cipherText = eng.processBlock(data, 0, data.length);
Assertions.mustNotBeInAcceptingState(eng);
}
@Test
public void rsKeyParameters() {
BigInteger mod = new BigInteger("a0b8e8321b041acd40b7", 16);
BigInteger pub = new BigInteger("9f0783a49...da", 16);
BigInteger pri = new BigInteger("21231...cda7", 16);
RSAKeyParameters privParameters = new RSAKeyParameters(true, mod, pri); //<--- warning here
Assertions.mustBeInAcceptingState(privParameters);
Assertions.notHasEnsuredPredicate(privParameters);
RSAKeyParameters pubParameters = new RSAKeyParameters(false, mod, pub); //<--- but no warning here
Assertions.mustBeInAcceptingState(pubParameters);
Assertions.hasEnsuredPredicate(pubParameters);
}
@Test
public void testORingTwoPredicates1() throws GeneralSecurityException {
BigInteger mod = new BigInteger("a0b8e8321b041acd40b7", 16);
BigInteger pub = new BigInteger("9f0783a49...da", 16);
RSAKeyParameters params = new RSAKeyParameters(false, mod, pub);
Assertions.mustBeInAcceptingState(params);
Assertions.hasEnsuredPredicate(params);
ParametersWithRandom randomParam1 = new ParametersWithRandom(params);
Assertions.mustBeInAcceptingState(randomParam1);
Assertions.hasEnsuredPredicate(randomParam1);
BigInteger priv = new BigInteger("92e08f83...19", 16);
Random randomGenerator = SecureRandom.getInstance("SHA1PRNG");
Assertions.mustBeInAcceptingState(randomGenerator);
Assertions.hasEnsuredPredicate(randomGenerator);
BigInteger p = new BigInteger(1024, randomGenerator);
BigInteger q = new BigInteger(1024, randomGenerator);
BigInteger pExp = new BigInteger("1d1a2d3ca8...b5", 16);
BigInteger qExp = new BigInteger("6c929e4e816...ed", 16);
BigInteger crtCoef = new BigInteger("dae7651ee...39", 16);
RSAPrivateCrtKeyParameters privParam = new RSAPrivateCrtKeyParameters(mod, pub, priv, p, q, pExp, qExp, crtCoef);
Assertions.mustBeInAcceptingState(privParam);
Assertions.notHasEnsuredPredicate(privParam); // because p & q are of type BigInteger which cannot ensure randomized predicate
ParametersWithRandom randomParam2 = new ParametersWithRandom(privParam);
Assertions.mustBeInAcceptingState(randomParam2);
Assertions.notHasEnsuredPredicate(randomParam2);
}
@Ignore
@Test
public void testORingTwoPredicates2() throws GeneralSecurityException, IllegalStateException, InvalidCipherTextException {
SecureRandom random = new SecureRandom();
byte[] genSeed = random.generateSeed(128);
KeyParameter keyParam = new KeyParameter(genSeed);
byte[] nonce = random.generateSeed(128);
AEADParameters aeadParam = new AEADParameters(keyParam, 128, nonce);
Assertions.hasEnsuredPredicate(aeadParam);
Assertions.mustBeInAcceptingState(aeadParam);
AESEngine engine = new AESEngine();
Assertions.hasEnsuredPredicate(engine);
byte[] input = new byte[100];
byte[] output = new byte[100];
GCMBlockCipher cipher1 = new GCMBlockCipher(engine);
cipher1.init(false, aeadParam);
cipher1.processAADBytes(input, 0, input.length);
cipher1.doFinal(output, 0);
Assertions.hasEnsuredPredicate(cipher1);
Assertions.mustBeInAcceptingState(cipher1);
ParametersWithIV ivParam = new ParametersWithIV(keyParam, genSeed);
Assertions.hasEnsuredPredicate(ivParam);
Assertions.mustBeInAcceptingState(ivParam);
GCMBlockCipher cipher2 = new GCMBlockCipher(engine);
cipher2.init(false, ivParam);
// cipher2.processAADBytes(input, 0, input.length);
// cipher2.doFinal(output, 0);
Assertions.hasEnsuredPredicate(cipher2);
Assertions.mustNotBeInAcceptingState(cipher2);
}
@Test
public void testORingThreePredicates1() throws GeneralSecurityException {
BigInteger mod = new BigInteger("a0b8e8321b041acd40b7", 16);
BigInteger pub = new BigInteger("9f0783a49...da", 16);
RSAKeyParameters params = new RSAKeyParameters(false, mod, pub);
ParametersWithRandom randomParam1 = new ParametersWithRandom(params);
Assertions.mustBeInAcceptingState(randomParam1);
Assertions.hasEnsuredPredicate(randomParam1);
BigInteger priv = new BigInteger("92e08f83...19", 16);
Random randomGenerator = SecureRandom.getInstance("SHA1PRNG");
Assertions.mustBeInAcceptingState(randomGenerator);
Assertions.hasEnsuredPredicate(randomGenerator);
BigInteger p = new BigInteger(1024, randomGenerator);
BigInteger q = new BigInteger(1024, randomGenerator);
BigInteger pExp = new BigInteger("1d1a2d3ca8...b5", 16);
BigInteger qExp = new BigInteger("6c929e4e816...ed", 16);
BigInteger crtCoef = new BigInteger("dae7651ee...39", 16);
RSAPrivateCrtKeyParameters privParam = new RSAPrivateCrtKeyParameters(mod, pub, priv, p, q, pExp, qExp, crtCoef);
Assertions.mustBeInAcceptingState(privParam);
Assertions.notHasEnsuredPredicate(privParam); // because p & q are of type BigInteger which cannot ensure randomized predicate
ParametersWithRandom randomParam2 = new ParametersWithRandom(privParam);
Assertions.mustBeInAcceptingState(randomParam2);
Assertions.notHasEnsuredPredicate(randomParam2);
BigInteger n = new BigInteger("62771017353866");
ECCurve.Fp curve = new ECCurve.Fp(new BigInteger("2343"), new BigInteger("2343"), new BigInteger("2343"), n, ECConstants.ONE);
ECDomainParameters ecParams = new ECDomainParameters(curve, curve.decodePoint(Hex.decode("03188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012")), n);
Assertions.mustBeInAcceptingState(ecParams);
Assertions.hasEnsuredPredicate(ecParams);
ECPublicKeyParameters pubKeyValid = new ECPublicKeyParameters( curve.decodePoint(Hex.decode("0262b12d")), ecParams);
Assertions.mustBeInAcceptingState(pubKeyValid);
Assertions.hasEnsuredPredicate(pubKeyValid);
ParametersWithRandom randomParam3 = new ParametersWithRandom(pubKeyValid);
Assertions.mustBeInAcceptingState(randomParam3);
Assertions.hasEnsuredPredicate(randomParam3);
}
@Test
public void testORingThreePredicates2() throws GeneralSecurityException {
BigInteger mod = new BigInteger("a0b8e8321b041acd40b7", 16);
BigInteger pub = new BigInteger("9f0783a49...da", 16);
RSAKeyParameters params = new RSAKeyParameters(false, mod, pub);
Assertions.mustBeInAcceptingState(params);
Assertions.hasEnsuredPredicate(params);
byte[] message = new byte[100];
RSAEngine engine1 = new RSAEngine();
Assertions.hasEnsuredPredicate(engine1);
engine1.init(false, params);
byte[] cipherText1 = engine1.processBlock(message, 0, message.length);
Assertions.mustBeInAcceptingState(engine1);
Assertions.hasEnsuredPredicate(cipherText1);
BigInteger n = new BigInteger("62771017353866");
ECCurve.Fp curve = new ECCurve.Fp(new BigInteger("2343"), new BigInteger("2343"), new BigInteger("2343"), n, ECConstants.ONE);
ECDomainParameters ecParams = new ECDomainParameters(curve, curve.decodePoint(Hex.decode("03188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012")), n);
Assertions.mustBeInAcceptingState(ecParams);
Assertions.hasEnsuredPredicate(ecParams);
ECPublicKeyParameters pubKeyValid = new ECPublicKeyParameters( curve.decodePoint(Hex.decode("0262b12d")), ecParams);
Assertions.mustBeInAcceptingState(pubKeyValid);
Assertions.hasEnsuredPredicate(pubKeyValid);
RSAEngine engine2 = new RSAEngine();
Assertions.hasEnsuredPredicate(engine2);
engine2.init(false, pubKeyValid);
byte[] cipherText2 = engine2.processBlock(message, 0, message.length);
Assertions.mustBeInAcceptingState(engine2);
Assertions.hasEnsuredPredicate(cipherText2);
}
@Override
protected String getSootClassPath() {
String bouncyCastleJarPath = new File("src/test/resources/bcprov-jdk15on-1.60.jar").getAbsolutePath();
return super.getSootClassPath() +File.pathSeparator +bouncyCastleJarPath;
}
}
| 9,479 | 44.142857 | 150 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/tests/pattern/CipherTest.java | package tests.pattern;
import java.security.GeneralSecurityException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.junit.Test;
import crypto.analysis.CrySLRulesetSelector.Ruleset;
import test.UsagePatternTestingFramework;
import test.assertions.Assertions;
public class CipherTest extends UsagePatternTestingFramework {
@Override
protected Ruleset getRuleSet() {
return Ruleset.JavaCryptographicArchitecture;
}
@Test
public void noInit() throws GeneralSecurityException {
Cipher c = Cipher.getInstance("trololo");
Assertions.extValue(0);
Assertions.mustNotBeInAcceptingState(c);
Assertions.notHasEnsuredPredicate(c);
}
@Test
public void yesInit() throws GeneralSecurityException {
Cipher c = Cipher.getInstance("trololo");
c.init(1, new SecretKeySpec(null, "trololo"));
Assertions.extValue(0);
Assertions.mustNotBeInAcceptingState(c);
Assertions.notHasEnsuredPredicate(c);
}
@Test
public void useDoFinalInLoop() throws GeneralSecurityException {
KeyGenerator keygen = KeyGenerator.getInstance("AES");
Assertions.extValue(0);
keygen.init(128);
Assertions.extValue(0);
SecretKey key = keygen.generateKey();;
Assertions.hasEnsuredPredicate(key);
Cipher cCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
Assertions.extValue(0);
cCipher.init(Cipher.ENCRYPT_MODE, key);
Assertions.mustNotBeInAcceptingState(cCipher);
byte[] enc = null;
for (int i = 0; i < 42; i++) {
enc = cCipher.doFinal("".getBytes());
Assertions.mustBeInAcceptingState(cCipher);
Assertions.hasEnsuredPredicate(enc);
}
Assertions.mustNotBeInAcceptingState(cCipher);
Assertions.hasEnsuredPredicate(enc);
}
@Test
public void caseInsensitiveNames() throws GeneralSecurityException {
KeyGenerator keygen = KeyGenerator.getInstance("aes");
Assertions.extValue(0);
keygen.init(128);
Assertions.extValue(0);
SecretKey key = keygen.generateKey();
Assertions.hasEnsuredPredicate(key);
Cipher cCipher = Cipher.getInstance("Aes/CbC/pKCS5PADDING");
Assertions.extValue(0);
cCipher.init(Cipher.ENCRYPT_MODE, key);
byte[] enc = cCipher.doFinal("".getBytes());
Assertions.mustBeInAcceptingState(cCipher);
Assertions.hasEnsuredPredicate(enc);
}
@Test
public void cipherUsagePatternTest1() throws GeneralSecurityException {
KeyGenerator keygen = KeyGenerator.getInstance("AES");
Assertions.extValue(0);
keygen.init(128);
Assertions.extValue(0);
SecretKey key = keygen.generateKey();
Assertions.hasEnsuredPredicate(key);
Assertions.mustBeInAcceptingState(keygen);
String string = "AES/CBC/PKCS5Padding";
Cipher cCipher = Cipher.getInstance(string);
Assertions.extValue(0);
cCipher.init(Cipher.ENCRYPT_MODE, key);
Assertions.extValue(0);
byte[] encText = cCipher.doFinal("".getBytes());
Assertions.hasEnsuredPredicate(encText);
Assertions.mustBeInAcceptingState(cCipher);
cCipher.getIV();
}
@Test
public void cipherUsagePatternImprecise() throws GeneralSecurityException {
SecretKey key = KeyGenerator.getInstance("AES").generateKey();
Assertions.hasEnsuredPredicate(key);
Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
Assertions.extValue(0);
c.init(Cipher.ENCRYPT_MODE, key);
byte[] res = c.doFinal("message".getBytes(), 0, "message".getBytes().length);
Assertions.mustBeInAcceptingState(c);
Assertions.hasEnsuredPredicate(res);
}
@Test
public void cipherUsagePatternTestInsecureKey() throws GeneralSecurityException {
byte[] plaintext = "WHAT!?".getBytes();
SecretKeySpec encKey = new SecretKeySpec(new byte[1], "AES");
Assertions.notHasEnsuredPredicate(encKey);
Cipher c = Cipher.getInstance("AES/CBC");
c.init(1, encKey);
String ciphertext = new String(c.doFinal(plaintext));
Assertions.mustBeInAcceptingState(c);
Assertions.notHasEnsuredPredicate(ciphertext);
}
@Test
public void cipherUsagePatternTestInter1() throws GeneralSecurityException {
SecretKey key = generateKey();
Assertions.hasEnsuredPredicate(key);
encrypt(key);
}
@Test
public void cipherUsagePatternTestInter2() throws GeneralSecurityException {
SecretKey key = generateKey();
Assertions.hasEnsuredPredicate(key);
forward(key);
}
private void forward(SecretKey key) throws GeneralSecurityException {
SecretKey tmpKey = key;
encrypt(tmpKey);
}
@Test
public void cipherUsagePatternTestInter3() throws GeneralSecurityException {
SecretKey key = generateKey();
Assertions.hasEnsuredPredicate(key);
rebuild(key);
}
private void rebuild(SecretKey key) throws GeneralSecurityException {
SecretKey tmpKey = new SecretKeySpec(key.getEncoded(), "AES");
encrypt(tmpKey);
}
@Test
public void cipherUsagePatternTestInter4() throws GeneralSecurityException {
SecretKey key = generateKey();
Assertions.hasEnsuredPredicate(key);
wrongRebuild(key);
}
private void wrongRebuild(SecretKey key) throws GeneralSecurityException {
SecretKey tmpKey = new SecretKeySpec(key.getEncoded(), "DES");
Assertions.notHasEnsuredPredicate(tmpKey);
encryptWrong(tmpKey);
}
private void encryptWrong(SecretKey key) throws GeneralSecurityException {
Cipher cCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
Assertions.extValue(0);
cCipher.init(Cipher.ENCRYPT_MODE, key);
Assertions.extValue(0);
byte[] encText = cCipher.doFinal("".getBytes());
Assertions.notHasEnsuredPredicate(encText);
Assertions.mustBeInAcceptingState(cCipher);
cCipher.getIV();
}
private void encrypt(SecretKey key) throws GeneralSecurityException {
Cipher cCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
Assertions.extValue(0);
cCipher.init(Cipher.ENCRYPT_MODE, key);
Assertions.extValue(0);
byte[] encText = cCipher.doFinal("".getBytes());
Assertions.hasEnsuredPredicate(encText);
Assertions.mustBeInAcceptingState(cCipher);
cCipher.getIV();
}
private SecretKey generateKey() throws NoSuchAlgorithmException {
KeyGenerator keygen = KeyGenerator.getInstance("AES");
Assertions.extValue(0);
keygen.init(128);
Assertions.extValue(0);
SecretKey key = keygen.generateKey();
Assertions.mustBeInAcceptingState(keygen);
return key;
}
@Test
public void cipherUsagePatternTest1SilentForbiddenMethod() throws GeneralSecurityException {
KeyGenerator keygen = KeyGenerator.getInstance("AES");
Assertions.extValue(0);
keygen.init(128);
Assertions.extValue(0);
SecretKey key = keygen.generateKey();
Assertions.hasEnsuredPredicate(key);
Assertions.mustBeInAcceptingState(keygen);
Cipher cCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
Assertions.extValue(0);
cCipher.init(Cipher.DECRYPT_MODE, key);
Assertions.extValue(0);
Assertions.callToForbiddenMethod();
byte[] encText = cCipher.doFinal("".getBytes());
Assertions.mustBeInAcceptingState(cCipher);
Assertions.notHasEnsuredPredicate(cCipher);
cCipher.getIV();
}
@Test
public void cipherUsagePatternTest1a() throws GeneralSecurityException {
KeyGenerator keygen = KeyGenerator.getInstance("AES");
Assertions.extValue(0);
keygen.init(128);
Assertions.extValue(0);
SecretKey key = keygen.generateKey();
Assertions.hasEnsuredPredicate(key);
Assertions.mustBeInAcceptingState(keygen);
byte[] iv = new byte[32];
SecureRandom.getInstanceStrong().nextBytes(iv);
IvParameterSpec spec = new IvParameterSpec(iv);
Cipher cCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
Assertions.extValue(0);
int mode = 1;
if (Math.random() % 2 == 0) {
mode = 2;
}
cCipher.init(mode, key, spec);
Assertions.extValue(0);
byte[] encText = cCipher.doFinal("".getBytes());
Assertions.hasEnsuredPredicate(encText);
Assertions.mustBeInAcceptingState(cCipher);
cCipher.getIV();
}
@Test
public void cipherUsagePatternTestIVCor() throws GeneralSecurityException {
KeyGenerator keygen = KeyGenerator.getInstance("AES");
Assertions.extValue(0);
keygen.init(128);
Assertions.extValue(0);
SecretKey key = keygen.generateKey();
Assertions.hasEnsuredPredicate(key);
Assertions.mustBeInAcceptingState(keygen);
SecureRandom sr = SecureRandom.getInstanceStrong();
Assertions.hasEnsuredPredicate(sr);
byte[] ivbytes = new byte[12];
sr.nextBytes(ivbytes);
Assertions.hasEnsuredPredicate(ivbytes);
IvParameterSpec iv = new IvParameterSpec(ivbytes);
Assertions.mustBeInAcceptingState(iv);
Assertions.hasEnsuredPredicate(iv);
Cipher cCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
Assertions.extValue(0);
cCipher.init(Cipher.ENCRYPT_MODE, key, iv);
Assertions.extValue(0);
byte[] encText = cCipher.doFinal("".getBytes());
Assertions.hasEnsuredPredicate(encText);
Assertions.mustBeInAcceptingState(cCipher);
cCipher.getIV();
}
@Test
public void cipherUsagePatternTestIVInCor() throws GeneralSecurityException {
KeyGenerator keygen = KeyGenerator.getInstance("AES");
Assertions.extValue(0);
keygen.init(128);
Assertions.extValue(0);
SecretKey key = keygen.generateKey();
Assertions.hasEnsuredPredicate(key);
Assertions.mustBeInAcceptingState(keygen);
byte[] ivbytes = new byte[12];
Assertions.notHasEnsuredPredicate(ivbytes);
IvParameterSpec iv = new IvParameterSpec(ivbytes);
Assertions.mustBeInAcceptingState(iv);
Assertions.notHasEnsuredPredicate(iv);
Cipher cCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
Assertions.extValue(0);
cCipher.init(Cipher.ENCRYPT_MODE, key, iv);
Assertions.extValue(0);
byte[] encText = cCipher.doFinal("".getBytes());
Assertions.notHasEnsuredPredicate(encText);
Assertions.mustBeInAcceptingState(cCipher);
}
@Test
public void cipherUsagePatternTestWrongOffsetSize() throws GeneralSecurityException {
KeyGenerator keygen = KeyGenerator.getInstance("AES");
Assertions.extValue(0);
keygen.init(128);
Assertions.extValue(0);
SecretKey key = keygen.generateKey();
Assertions.hasEnsuredPredicate(key);
Assertions.mustBeInAcceptingState(keygen);
Cipher cCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
Assertions.extValue(0);
cCipher.init(Cipher.ENCRYPT_MODE, key);
Assertions.extValue(0);
final byte[] bytes = "test".getBytes();
byte[] encText = cCipher.doFinal(bytes, 200, bytes.length);
Assertions.extValue(0);
Assertions.extValue(1);
Assertions.extValue(2);
// TODO: Fails for reasons different from the ones I expected.
cCipher.getIV();
// Assertions.mustBeInAcceptingState(cCipher);
// Assertions.notasEnsuredPredicate(encText);
}
@Test
public void cipherUsagePatternTestMissingMode() throws GeneralSecurityException {
KeyGenerator keygen = KeyGenerator.getInstance("AES");
Assertions.extValue(0);
keygen.init(128);
Assertions.extValue(0);
SecretKey key = keygen.generateKey();
Assertions.hasEnsuredPredicate(key);
Assertions.mustBeInAcceptingState(keygen);
Cipher cCipher = Cipher.getInstance("AES");
Assertions.extValue(0);
cCipher.init(Cipher.ENCRYPT_MODE, key);
Assertions.extValue(0);
byte[] encText = cCipher.doFinal("".getBytes());
Assertions.notHasEnsuredPredicate(encText);
Assertions.mustBeInAcceptingState(cCipher);
}
@Test
public void cipherUsagePatternTestWrongPadding() throws GeneralSecurityException {
KeyGenerator keygen = KeyGenerator.getInstance("AES");
Assertions.extValue(0);
keygen.init(128);
Assertions.extValue(0);
SecretKey key = keygen.generateKey();
Assertions.hasEnsuredPredicate(key);
Assertions.mustBeInAcceptingState(keygen);
Cipher cCipher = Cipher.getInstance("AES/CBC/NoPadding");
Assertions.extValue(0);
cCipher.init(Cipher.ENCRYPT_MODE, key);
Assertions.extValue(0);
byte[] encText = cCipher.doFinal("".getBytes());
Assertions.notHasEnsuredPredicate(encText);
Assertions.mustBeInAcceptingState(cCipher);
}
@Test
public void cipherUsagePatternTest2() throws GeneralSecurityException {
KeyGenerator keygen = KeyGenerator.getInstance("AES");
Assertions.extValue(0);
keygen.init(129);
Assertions.extValue(0);
SecretKey key = keygen.generateKey();
Assertions.mustBeInAcceptingState(keygen);
Assertions.notHasEnsuredPredicate(key);
Cipher cCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
Assertions.extValue(0);
cCipher.init(Cipher.ENCRYPT_MODE, key);
Assertions.extValue(0);
byte[] encText = cCipher.doFinal("".getBytes());
Assertions.notHasEnsuredPredicate(encText);
}
@Test
public void cipherUsagePatternTest3() throws GeneralSecurityException {
KeyGenerator keygen = KeyGenerator.getInstance("AES");
Assertions.extValue(0);
keygen.init(128);
Assertions.extValue(0);
SecretKey key = keygen.generateKey();
Assertions.mustBeInAcceptingState(keygen);
Cipher cCipher = Cipher.getInstance("AES");
cCipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(new byte[18], "AES"));
Assertions.extValue(0);
byte[] encText = cCipher.doFinal("".getBytes());
Assertions.mustBeInAcceptingState(cCipher);
Assertions.notHasEnsuredPredicate(encText);
}
@Test
public void cipherUsagePatternTestWrongModeExtraVar() throws GeneralSecurityException {
String trans = "AES";
KeyGenerator keygen = KeyGenerator.getInstance("AES");
Assertions.extValue(0);
keygen.init(128);
Assertions.extValue(0);
SecretKey key = keygen.generateKey();
Assertions.mustBeInAcceptingState(keygen);
Cipher cCipher = Cipher.getInstance(trans);
Assertions.extValue(0);
cCipher.init(Cipher.ENCRYPT_MODE, key);
Assertions.extValue(0);
byte[] encText = cCipher.doFinal("".getBytes());
Assertions.mustBeInAcceptingState(cCipher);
Assertions.notHasEnsuredPredicate(encText);
}
@Test
public void cipherUsagePatternTest4() throws GeneralSecurityException {
KeyGenerator keygen = KeyGenerator.getInstance("AES");
Assertions.extValue(0);
keygen.init(128);
Assertions.extValue(0);
SecretKey key = keygen.generateKey();
Assertions.mustBeInAcceptingState(keygen);
Cipher cCipher = Cipher.getInstance("Blowfish");
Assertions.extValue(0);
cCipher.init(Cipher.ENCRYPT_MODE, key);
Assertions.extValue(0);
byte[] encText = cCipher.doFinal("".getBytes());
Assertions.mustBeInAcceptingState(cCipher);
Assertions.notHasEnsuredPredicate(encText);
}
@Test
public void cipherUsagePatternTest5() throws GeneralSecurityException {
final byte[] msgAsArray = "Message".getBytes();
KeyGenerator keygenEnc = KeyGenerator.getInstance("AES");
Assertions.extValue(0);
keygenEnc.init(128);
Assertions.extValue(0);
SecretKey keyEnc = keygenEnc.generateKey();
Assertions.mustBeInAcceptingState(keygenEnc);
Cipher cCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
Assertions.extValue(0);
cCipher.init(Cipher.ENCRYPT_MODE, keyEnc);
Assertions.extValue(0);
byte[] encText = cCipher.doFinal(msgAsArray);
cCipher.getIV();
Assertions.mustBeInAcceptingState(cCipher);
Assertions.hasEnsuredPredicate(encText);
KeyGenerator keygenMac = KeyGenerator.getInstance("HmacSHA256");
SecretKey keyMac = keygenMac.generateKey();
final Mac hMacSHA256 = Mac.getInstance("HmacSHA256");
Assertions.extValue(0);
hMacSHA256.init(keyMac);
byte[] macced = hMacSHA256.doFinal(msgAsArray);
Assertions.mustNotBeInAcceptingState(hMacSHA256);
Assertions.notHasEnsuredPredicate(macced);
}
@Test
public void cipherUsagePatternTest6() throws GeneralSecurityException {
SecureRandom keyRand = SecureRandom.getInstanceStrong();
KeyGenerator keygen = KeyGenerator.getInstance("AES");
Assertions.extValue(0);
Assertions.hasEnsuredPredicate(keyRand);
keygen.init(128, keyRand);
Assertions.extValue(0);
SecretKey key = keygen.generateKey();
Assertions.mustBeInAcceptingState(keygen);
SecureRandom encRand = SecureRandom.getInstanceStrong();
Cipher cCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
Assertions.extValue(0);
cCipher.init(Cipher.ENCRYPT_MODE, key, encRand);
Assertions.extValue(0);
byte[] encText = cCipher.doFinal("".getBytes());
Assertions.mustBeInAcceptingState(cCipher);
Assertions.hasEnsuredPredicate(encText);
cCipher.getIV();
}
@Test
public void cipherUsagePatternTest7() throws GeneralSecurityException {
SecureRandom rand = SecureRandom.getInstanceStrong();
KeyGenerator keygen = KeyGenerator.getInstance("AES");
Assertions.extValue(0);
keygen.init(128);
Assertions.extValue(0);
SecretKey key = keygen.generateKey();
Assertions.mustBeInAcceptingState(keygen);
Cipher cCipher = Cipher.getInstance("Blowfish");
Assertions.extValue(0);
cCipher.init(Cipher.ENCRYPT_MODE, key, rand);
Assertions.extValue(0);
byte[] encText = cCipher.doFinal("".getBytes());
Assertions.mustBeInAcceptingState(cCipher);
Assertions.notHasEnsuredPredicate(encText);
}
@Test
public void cipherUsagePatternTest7b() throws GeneralSecurityException {
SecureRandom encRand = SecureRandom.getInstanceStrong();
KeyGenerator keygen = KeyGenerator.getInstance("AES");
Assertions.extValue(0);
keygen.init(128, null);
Assertions.extValue(0);
SecretKey key = keygen.generateKey();
Assertions.mustBeInAcceptingState(keygen);
Assertions.notHasEnsuredPredicate(key);
Cipher cCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
Assertions.extValue(0);
cCipher.init(Cipher.ENCRYPT_MODE, key, encRand);
Assertions.extValue(0);
byte[] encText = cCipher.doFinal("".getBytes());
Assertions.mustBeInAcceptingState(cCipher);
Assertions.notHasEnsuredPredicate(encText);
}
@Test
public void cipherUsagePatternTest8() throws GeneralSecurityException {
String aesString = "AES";
KeyGenerator keygen = KeyGenerator.getInstance(aesString);
Assertions.extValue(0);
int keySize = 128;
int a = keySize;
keygen.init(a);
Assertions.extValue(0);
SecretKey key = keygen.generateKey();
Assertions.hasEnsuredPredicate(key);
Assertions.mustBeInAcceptingState(keygen);
Cipher cCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
Assertions.extValue(0);
cCipher.init(Cipher.ENCRYPT_MODE, key);
Assertions.extValue(0);
byte[] encText = cCipher.doFinal("".getBytes());
cCipher.getIV();
Assertions.hasEnsuredPredicate(encText);
Assertions.mustBeInAcceptingState(cCipher);
}
@Test
public void cipherUsagePatternTest9() throws GeneralSecurityException {
KeyGenerator keygen = KeyGenerator.getInstance("AES");
Assertions.extValue(0);
keygen.init(1);
Assertions.extValue(0);
SecretKey key = keygen.generateKey();
Assertions.notHasEnsuredPredicate(key);
Assertions.mustBeInAcceptingState(keygen);
Cipher cCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
Assertions.extValue(0);
cCipher.init(Cipher.ENCRYPT_MODE, key);
Assertions.extValue(0);
byte[] encText = cCipher.doFinal("".getBytes());
Assertions.notHasEnsuredPredicate(encText);
Assertions.mustBeInAcceptingState(cCipher);
}
}
| 18,902 | 30.876897 | 93 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/tests/pattern/CookiesTest.java | package tests.pattern;
import javax.servlet.http.Cookie;
import org.junit.Test;
import crypto.analysis.CrySLRulesetSelector.Ruleset;
import test.UsagePatternTestingFramework;
import test.assertions.Assertions;
public class CookiesTest extends UsagePatternTestingFramework{
@Override
protected Ruleset getRuleSet() {
return Ruleset.JavaCryptographicArchitecture;
}
@Test
public void testOne() {
Cookie ck= new Cookie("name","testing");
ck.setSecure(true); // constraint is satisfied
Assertions.hasEnsuredPredicate(ck);
Assertions.mustBeInAcceptingState(ck);
}
@Test
public void testTwo() {
Cookie ck= new Cookie("name","testing");
ck.setSecure(false); // constraint is violated
Assertions.notHasEnsuredPredicate(ck);
Assertions.mustBeInAcceptingState(ck);
}
@Test
public void testThree() {
Cookie ck= new Cookie("name","testing");
// setSecure call is unused
Assertions.notHasEnsuredPredicate(ck);
Assertions.mustNotBeInAcceptingState(ck);
}
} | 988 | 23.725 | 62 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/tests/pattern/ExtractValueTest.java | package tests.pattern;
import java.security.GeneralSecurityException;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.PBEKeySpec;
import org.junit.Test;
import crypto.analysis.CrySLRulesetSelector.Ruleset;
import test.UsagePatternTestingFramework;
import test.assertions.Assertions;
public class ExtractValueTest extends UsagePatternTestingFramework{
@Override
protected Ruleset getRuleSet() {
return Ruleset.JavaCryptographicArchitecture;
}
@Test
public void testInterproceduralStringFlow() throws GeneralSecurityException {
KeyGenerator keygen = KeyGenerator.getInstance(getAES());
Assertions.extValue(0);
keygen.init(0);
}
@Test
public void charArrayExtractionTest(){
char[] v = new char[] {'p'};
final PBEKeySpec pbekeyspec = new PBEKeySpec(v, null, 65000, 128);
Assertions.extValue(0);
}
@Test
public void testIntraproceduralStringFlow() throws GeneralSecurityException {
String aes = "AES";
KeyGenerator keygen = KeyGenerator.getInstance(aes);
Assertions.extValue(0);
keygen.init(0);
}
@Test
public void testInterproceduralStringFlowDirect() throws GeneralSecurityException {
KeyGenerator keygen = KeyGenerator.getInstance(getAESReturn());
Assertions.extValue(0);
keygen.init(0);
}
@Test
public void testIntraproceduralIntFlowDirect() throws GeneralSecurityException {
KeyGenerator keygen = KeyGenerator.getInstance("AES");
Assertions.extValue(0);
int val = 0;
keygen.init(val);
Assertions.extValue(0);
}
@Test
public void testIntraproceduralNativeNoCalleeIntFlow() throws GeneralSecurityException {
KeyGenerator keygen = KeyGenerator.getInstance("AES");
Assertions.extValue(0);
int val = noCallee();
keygen.init(val);
Assertions.extValue(0);
}
private String getAESReturn() {
int x = 222;
return "AES";
}
private String getAES() {
String var = "AES";
return var;
}
private static native int noCallee();
}
| 1,920 | 24.613333 | 89 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/tests/pattern/InputStreamTest.java | package tests.pattern;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.security.DigestInputStream;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import org.junit.Test;
import crypto.analysis.CrySLRulesetSelector.Ruleset;
import test.UsagePatternTestingFramework;
import test.assertions.Assertions;
public class InputStreamTest extends UsagePatternTestingFramework {
// Usage Pattern tests for CipherInputStream
@Test
public void UsagePatternTestCISDefaultUse()
throws GeneralSecurityException, UnsupportedEncodingException, FileNotFoundException, IOException {
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
Assertions.extValue(0);
keyGenerator.init(128);
Assertions.extValue(0);
SecretKey key = keyGenerator.generateKey();
Assertions.hasEnsuredPredicate(key);
Assertions.mustBeInAcceptingState(keyGenerator);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
Assertions.extValue(0);
cipher.init(Cipher.DECRYPT_MODE, key);
Assertions.extValue(0);
InputStream is = new FileInputStream(".\\resources\\cis.txt");
CipherInputStream cis = new CipherInputStream(is, cipher);
Assertions.extValue(0);
Assertions.extValue(1);
while (cis.read() != -1) {
}
cis.close();
Assertions.mustBeInAcceptingState(cis);
}
@Test
public void UsagePatternTestCISAdditionalUse1()
throws GeneralSecurityException, UnsupportedEncodingException, FileNotFoundException, IOException {
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
Assertions.extValue(0);
keyGenerator.init(128);
Assertions.extValue(0);
SecretKey key = keyGenerator.generateKey();
Assertions.hasEnsuredPredicate(key);
Assertions.mustBeInAcceptingState(keyGenerator);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
Assertions.extValue(0);
cipher.init(Cipher.DECRYPT_MODE, key);
Assertions.extValue(0);
InputStream is = new FileInputStream(".\\resources\\cis.txt");
CipherInputStream cis = new CipherInputStream(is, cipher);
Assertions.extValue(0);
Assertions.extValue(1);
cis.read("input".getBytes());
cis.close();
Assertions.mustBeInAcceptingState(cis);
}
@Test
public void UsagePatternTestCISAdditionalUse2()
throws GeneralSecurityException, UnsupportedEncodingException, FileNotFoundException, IOException {
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
Assertions.extValue(0);
keyGenerator.init(128);
Assertions.extValue(0);
SecretKey key = keyGenerator.generateKey();
Assertions.hasEnsuredPredicate(key);
Assertions.mustBeInAcceptingState(keyGenerator);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
Assertions.extValue(0);
cipher.init(Cipher.DECRYPT_MODE, key);
Assertions.extValue(0);
InputStream is = new FileInputStream(".\\resources\\cis.txt");
CipherInputStream cis = new CipherInputStream(is, cipher);
Assertions.extValue(0);
Assertions.extValue(1);
cis.read("input".getBytes(), 0, "input".getBytes().length);
cis.close();
Assertions.mustBeInAcceptingState(cis);
}
@Test
public void UsagePatternTestCISMissingCallToClose()
throws GeneralSecurityException, UnsupportedEncodingException, FileNotFoundException, IOException {
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
Assertions.extValue(0);
keyGenerator.init(128);
Assertions.extValue(0);
SecretKey key = keyGenerator.generateKey();
Assertions.hasEnsuredPredicate(key);
Assertions.mustBeInAcceptingState(keyGenerator);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
Assertions.extValue(0);
cipher.init(Cipher.DECRYPT_MODE, key);
Assertions.extValue(0);
InputStream is = new FileInputStream(".\\resources\\cis.txt");
CipherInputStream cis = new CipherInputStream(is, cipher);
Assertions.extValue(0);
Assertions.extValue(1);
while (cis.read() != -1) {
}
Assertions.mustNotBeInAcceptingState(cis);
cis.close();
}
@Test
public void UsagePatternTestCISViolatedConstraint()
throws GeneralSecurityException, UnsupportedEncodingException, FileNotFoundException, IOException {
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
Assertions.extValue(0);
keyGenerator.init(128);
Assertions.extValue(0);
SecretKey key = keyGenerator.generateKey();
Assertions.hasEnsuredPredicate(key);
Assertions.mustBeInAcceptingState(keyGenerator);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
Assertions.extValue(0);
cipher.init(Cipher.DECRYPT_MODE, key);
Assertions.extValue(0);
InputStream is = new FileInputStream(".\\resources\\cis.txt");
CipherInputStream cis = new CipherInputStream(is, cipher);
Assertions.extValue(0);
Assertions.extValue(1);
cis.read("input".getBytes(), 100, "input".getBytes().length);
// Assertions.violatedConstraint(cis);
Assertions.mustNotBeInAcceptingState(cis);
cis.close();
}
// Usage Pattern tests for DigestInputStream
@Test
public void UsagePatternTestDISDefaultUse()
throws GeneralSecurityException, UnsupportedEncodingException, FileNotFoundException, IOException {
InputStream is = new FileInputStream(".\\resources\\dis.txt");
MessageDigest md = MessageDigest.getInstance("SHA-256");
Assertions.extValue(0);
DigestInputStream dis = new DigestInputStream(is, md);
Assertions.extValue(0);
Assertions.extValue(1);
while (dis.read() != -1) {
}
dis.close();
Assertions.mustBeInAcceptingState(dis);
}
@Test
public void UsagePatternTestDISAdditionalUse()
throws GeneralSecurityException, UnsupportedEncodingException, FileNotFoundException, IOException {
InputStream is = new FileInputStream(".\\resources\\dis.txt");
MessageDigest md = MessageDigest.getInstance("SHA-256");
Assertions.extValue(0);
DigestInputStream dis = new DigestInputStream(is, md);
Assertions.extValue(0);
Assertions.extValue(1);
dis.read("input".getBytes(), 0, "input".getBytes().length);
dis.close();
Assertions.mustBeInAcceptingState(dis);
}
@Test
public void UsagePatternTestDISMissingCallToRead()
throws GeneralSecurityException, UnsupportedEncodingException, FileNotFoundException, IOException {
InputStream is = new FileInputStream(".\\resources\\dis.txt");
MessageDigest md = MessageDigest.getInstance("SHA-256");
Assertions.extValue(0);
DigestInputStream dis = new DigestInputStream(is, md);
Assertions.extValue(0);
Assertions.extValue(1);
Assertions.mustNotBeInAcceptingState(dis);
while (dis.read() != -1) {
}
}
@Test
public void UsagePatternTestDISViolatedConstraint()
throws GeneralSecurityException, UnsupportedEncodingException, FileNotFoundException, IOException {
InputStream is = new FileInputStream(".\\resources\\dis.txt");
MessageDigest md = MessageDigest.getInstance("SHA-256");
Assertions.extValue(0);
DigestInputStream dis = new DigestInputStream(is, md);
Assertions.extValue(0);
Assertions.extValue(1);
dis.read("input".getBytes(), 100, "input".getBytes().length);
Assertions.violatedConstraint(dis);
}
@Override
protected Ruleset getRuleSet() {
return Ruleset.JavaCryptographicArchitecture;
}
}
| 7,382 | 33.180556 | 102 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/tests/pattern/KeyPairTest.java | package tests.pattern;
import java.io.IOException;
import java.math.BigInteger;
import java.security.GeneralSecurityException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;
import java.security.spec.RSAKeyGenParameterSpec;
import org.junit.Test;
import crypto.analysis.CrySLRulesetSelector.Ruleset;
import test.UsagePatternTestingFramework;
import test.assertions.Assertions;
public class KeyPairTest extends UsagePatternTestingFramework {
@Override
protected Ruleset getRuleSet() {
return Ruleset.JavaCryptographicArchitecture;
}
@Test
public void negativeRsaParameterSpecTest() throws GeneralSecurityException, IOException {
Integer keySize = new Integer(102);
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
RSAKeyGenParameterSpec parameters = new RSAKeyGenParameterSpec(keySize, RSAKeyGenParameterSpec.F4);
Assertions.notHasEnsuredPredicate(parameters);
Assertions.extValue(0);
generator.initialize(parameters, new SecureRandom());
KeyPair keyPair = generator.generateKeyPair();
Assertions.notHasEnsuredPredicate(keyPair);
}
@Test
public void positiveRsaParameterSpecTest() throws GeneralSecurityException, IOException {
Integer keySize = new Integer(2048);
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
RSAKeyGenParameterSpec parameters = new RSAKeyGenParameterSpec(keySize, RSAKeyGenParameterSpec.F4);
Assertions.extValue(0);
Assertions.extValue(1);
Assertions.hasEnsuredPredicate(parameters);
generator.initialize(parameters, new SecureRandom());
KeyPair keyPair = generator.generateKeyPair();
Assertions.hasEnsuredPredicate(keyPair);
}
@Test
public void positiveRsaParameterSpecTestBigInteger() throws GeneralSecurityException, IOException {
Integer keySize = new Integer(2048);
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
RSAKeyGenParameterSpec parameters = new RSAKeyGenParameterSpec(keySize, BigInteger.valueOf(65537));
Assertions.extValue(0);
Assertions.extValue(1);
Assertions.hasEnsuredPredicate(parameters);
generator.initialize(parameters, new SecureRandom());
KeyPair keyPair = generator.generateKeyPair();
Assertions.hasEnsuredPredicate(keyPair);
}
}
| 2,263 | 34.936508 | 101 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/tests/pattern/MessageDigestTest.java | package tests.pattern;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.security.auth.DestroyFailedException;
import org.junit.Test;
import crypto.analysis.CrySLRulesetSelector.Ruleset;
import test.UsagePatternTestingFramework;
import test.assertions.Assertions;
public class MessageDigestTest extends UsagePatternTestingFramework {
@Override
protected Ruleset getRuleSet() {
return Ruleset.JavaCryptographicArchitecture;
}
@Test
public void mdUsagePatternTest1() throws GeneralSecurityException, UnsupportedEncodingException {
MessageDigest md = MessageDigest.getInstance("SHA-256");
Assertions.extValue(0);
final byte[] input = "input".getBytes("UTF-8");
byte[] output = md.digest(input);
Assertions.mustBeInAcceptingState(md);
Assertions.hasEnsuredPredicate(input);
Assertions.hasEnsuredPredicate(output);
}
@Test
public void mdUsagePatternTest2() throws GeneralSecurityException, UnsupportedEncodingException {
MessageDigest md = MessageDigest.getInstance("MD5");
Assertions.extValue(0);
final byte[] input = "input".getBytes("UTF-8");
byte[] output = md.digest(input);
Assertions.mustBeInAcceptingState(md);
Assertions.notHasEnsuredPredicate(input);
Assertions.notHasEnsuredPredicate(output);
Assertions.violatedConstraint(md);
}
@Test
public void mdUsagePatternTest3() throws GeneralSecurityException, UnsupportedEncodingException {
MessageDigest md = MessageDigest.getInstance("SHA-256");
Assertions.extValue(0);
final byte[] input = "input".getBytes("UTF-8");
md.update(input);
Assertions.mustNotBeInAcceptingState(md);
Assertions.notHasEnsuredPredicate(input);
md.digest();
}
@Test
public void mdUsagePatternTest4() throws GeneralSecurityException, UnsupportedEncodingException {
MessageDigest md = MessageDigest.getInstance("SHA-256");
Assertions.extValue(0);
final byte[] input = "input".getBytes("UTF-8");
md.update(input);
byte[] digest = md.digest();
Assertions.mustBeInAcceptingState(md);
Assertions.hasEnsuredPredicate(digest);
}
@Test
public void mdUsagePatternTest5() throws GeneralSecurityException, UnsupportedEncodingException {
MessageDigest md = MessageDigest.getInstance("SHA-256");
Assertions.extValue(0);
final String[] input = {"input1", "input2", "input3", "input4"};
int i = 0;
while (i < input.length) {
md.update(input[i].getBytes("UTF-8"));
}
byte[] digest = md.digest();
Assertions.mustBeInAcceptingState(md);
Assertions.hasEnsuredPredicate(digest);
}
@Test
public void mdUsagePatternTest6() throws GeneralSecurityException, UnsupportedEncodingException {
MessageDigest md = MessageDigest.getInstance("SHA-256");
Assertions.extValue(0);
final byte[] input = "input".getBytes("UTF-8");
byte[] output = md.digest(input);
md.reset();
Assertions.mustBeInAcceptingState(md);
Assertions.hasEnsuredPredicate(input);
Assertions.hasEnsuredPredicate(output);
md.digest();
}
@Test
public void mdUsagePatternTest7() throws GeneralSecurityException, UnsupportedEncodingException {
MessageDigest md = MessageDigest.getInstance("SHA-256");
Assertions.extValue(0);
final byte[] input = "input".getBytes("UTF-8");
byte[] output = md.digest(input);
Assertions.hasEnsuredPredicate(input);
Assertions.hasEnsuredPredicate(output);
output = null;
Assertions.notHasEnsuredPredicate(output);
md.reset();
output = md.digest(input);
Assertions.mustBeInAcceptingState(md);
Assertions.hasEnsuredPredicate(input);
Assertions.hasEnsuredPredicate(output);
}
@Test
public void mdUsagePatternTest8() throws GeneralSecurityException, UnsupportedEncodingException {
MessageDigest md = MessageDigest.getInstance("SHA-256");
Assertions.extValue(0);
final byte[] input = "input".getBytes("UTF-8");
final byte[] input2 = "input2".getBytes("UTF-8");
byte[] output = md.digest(input);
Assertions.hasEnsuredPredicate(input);
Assertions.hasEnsuredPredicate(output);
md.reset();
md.update(input2);
Assertions.mustNotBeInAcceptingState(md);
Assertions.notHasEnsuredPredicate(input2);
Assertions.hasEnsuredPredicate(output);
md.digest();
}
@Test
public void mdUsagePatternTest9() throws GeneralSecurityException, UnsupportedEncodingException {
MessageDigest md = MessageDigest.getInstance("SHA-256");
Assertions.extValue(0);
final byte[] input = "input".getBytes("UTF-8");
final byte[] input2 = "input2".getBytes("UTF-8");
byte[] output = md.digest(input);
Assertions.hasEnsuredPredicate(input);
Assertions.hasEnsuredPredicate(output);
Assertions.mustBeInAcceptingState(md);
md = MessageDigest.getInstance("MD5");
output = md.digest(input2);
Assertions.mustBeInAcceptingState(md);
Assertions.notHasEnsuredPredicate(input2);
Assertions.notHasEnsuredPredicate(output);
}
@Test
public void messageDigest() throws NoSuchAlgorithmException, DestroyFailedException {
while (true) {
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(new byte[] {});
md.update(new byte[] {});
byte[] digest = md.digest();
Assertions.hasEnsuredPredicate(digest);
}
}
@Test
public void messageDigestReturned() throws NoSuchAlgorithmException, DestroyFailedException {
MessageDigest d = createDigest();
byte[] digest = d.digest(new byte[] {});
Assertions.hasEnsuredPredicate(digest);
Assertions.typestateErrors(0);
}
private MessageDigest createDigest() throws NoSuchAlgorithmException {
return MessageDigest.getInstance("SHA-256");
}
}
| 5,619 | 31.865497 | 98 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/tests/pattern/OutputStreamTest.java | package tests.pattern;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.security.DigestOutputStream;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import javax.crypto.Cipher;
import javax.crypto.CipherOutputStream;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import org.junit.Ignore;
import org.junit.Test;
import crypto.analysis.CrySLRulesetSelector.Ruleset;
import test.UsagePatternTestingFramework;
import test.assertions.Assertions;
public class OutputStreamTest extends UsagePatternTestingFramework {
// Usage Pattern for CipherOutputStream
@Test
public void UsagePatternTestCOSDefaultUse()
throws GeneralSecurityException, UnsupportedEncodingException, FileNotFoundException, IOException {
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
Assertions.extValue(0);
keyGenerator.init(128);
Assertions.extValue(0);
SecretKey key = keyGenerator.generateKey();
Assertions.hasEnsuredPredicate(key);
Assertions.mustBeInAcceptingState(keyGenerator);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
Assertions.extValue(0);
cipher.init(Cipher.ENCRYPT_MODE, key);
Assertions.extValue(0);
OutputStream os = new FileOutputStream(".\\resources\\cos.txt");
CipherOutputStream cos = new CipherOutputStream(os, cipher);
Assertions.extValue(0);
Assertions.extValue(1);
cos.write(new String("Hello World\n").getBytes());
cos.close();
Assertions.mustBeInAcceptingState(cos);
}
@Test
public void UsagePatternTestCOSAdditionalUse()
throws GeneralSecurityException, UnsupportedEncodingException, FileNotFoundException, IOException {
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
Assertions.extValue(0);
keyGenerator.init(128);
Assertions.extValue(0);
SecretKey key = keyGenerator.generateKey();
Assertions.hasEnsuredPredicate(key);
Assertions.mustBeInAcceptingState(keyGenerator);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
Assertions.extValue(0);
cipher.init(Cipher.ENCRYPT_MODE, key);
Assertions.extValue(0);
OutputStream os = new FileOutputStream(".\\resources\\cos.txt");
CipherOutputStream cos = new CipherOutputStream(os, cipher);
Assertions.extValue(0);
Assertions.extValue(1);
cos.write("message".getBytes(), 0, "message".getBytes().length);
cos.close();
Assertions.mustBeInAcceptingState(cos);
}
@Test
public void UsagePatternTestCOSMissingCallToClose()
throws GeneralSecurityException, UnsupportedEncodingException, FileNotFoundException, IOException {
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
Assertions.extValue(0);
keyGenerator.init(128);
Assertions.extValue(0);
SecretKey key = keyGenerator.generateKey();
Assertions.hasEnsuredPredicate(key);
Assertions.mustBeInAcceptingState(keyGenerator);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
Assertions.extValue(0);
cipher.init(Cipher.ENCRYPT_MODE, key);
Assertions.extValue(0);
OutputStream os = new FileOutputStream(".\\resources\\cos.txt");
CipherOutputStream cos = new CipherOutputStream(os, cipher);
Assertions.extValue(0);
Assertions.extValue(1);
cos.write(new String("Hello World\n").getBytes());
Assertions.mustNotBeInAcceptingState(cos);
cos.close();
}
@Test
public void UsagePatternTestCOSViolatedConstraint()
throws GeneralSecurityException, UnsupportedEncodingException, FileNotFoundException, IOException {
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
Assertions.extValue(0);
keyGenerator.init(128);
Assertions.extValue(0);
SecretKey key = keyGenerator.generateKey();
Assertions.hasEnsuredPredicate(key);
Assertions.mustBeInAcceptingState(keyGenerator);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
Assertions.extValue(0);
cipher.init(Cipher.ENCRYPT_MODE, key);
Assertions.extValue(0);
OutputStream os = new FileOutputStream(".\\resources\\cos.txt");
CipherOutputStream cos = new CipherOutputStream(os, cipher);
Assertions.extValue(0);
Assertions.extValue(1);
cos.write("message".getBytes(), 100, "message".getBytes().length);
// Assertions.violatedConstraint(cos);
Assertions.mustNotBeInAcceptingState(cos);
cos.close();
}
// Usage Pattern tests for DigestOutputStream
@Test
@Ignore
public void UsagePatternTestDOSCallToForbiddenMethod()
throws GeneralSecurityException, UnsupportedEncodingException, FileNotFoundException, IOException {
OutputStream os = new FileOutputStream(".\\resources\\dos.txt");
MessageDigest md = MessageDigest.getInstance("SHA-256");
Assertions.extValue(0);
DigestOutputStream dos = new DigestOutputStream(os, md);
Assertions.extValue(0);
Assertions.extValue(1);
dos.on(false);
Assertions.callToForbiddenMethod();
dos.write(new String("Hello World\n").getBytes());
Assertions.mustBeInAcceptingState(dos);
}
@Test
public void UsagePatternTestDOSMissingCallToWrite()
throws GeneralSecurityException, UnsupportedEncodingException, FileNotFoundException, IOException {
OutputStream os = new FileOutputStream(".\\resources\\dos.txt");
MessageDigest md = MessageDigest.getInstance("SHA-256");
Assertions.extValue(0);
DigestOutputStream dos = new DigestOutputStream(os, md);
Assertions.extValue(0);
Assertions.extValue(1);
Assertions.mustNotBeInAcceptingState(dos);
dos.write(new String("Hello World").getBytes());
}
@Test
public void UsagePatternTestDOSAdditionalUse()
throws GeneralSecurityException, UnsupportedEncodingException, FileNotFoundException, IOException {
OutputStream os = new FileOutputStream(".\\resources\\dos.txt");
MessageDigest md = MessageDigest.getInstance("SHA-256");
Assertions.extValue(0);
DigestOutputStream dos = new DigestOutputStream(os, md);
Assertions.extValue(0);
Assertions.extValue(1);
dos.write("message".getBytes(), 0, "message".getBytes().length);
dos.close();
Assertions.mustBeInAcceptingState(dos);
}
@Test
public void UsagePatternTestDOSViolatedConstraint()
throws GeneralSecurityException, UnsupportedEncodingException, FileNotFoundException, IOException {
OutputStream os = new FileOutputStream(".\\resources\\dos.txt");
MessageDigest md = MessageDigest.getInstance("SHA-256");
Assertions.extValue(0);
DigestOutputStream dos = new DigestOutputStream(os, md);
Assertions.extValue(0);
Assertions.extValue(1);
dos.write("message".getBytes(), 100, "message".getBytes().length);
Assertions.violatedConstraint(dos);
// Assertions.mustNotBeInAcceptingState(dos);
}
@Override
protected Ruleset getRuleSet() {
return Ruleset.JavaCryptographicArchitecture;
}
}
| 6,778 | 35.058511 | 102 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/tests/pattern/PBETest.java | package tests.pattern;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.SecureRandom;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import org.junit.Test;
import crypto.analysis.CrySLRulesetSelector.Ruleset;
import test.UsagePatternTestingFramework;
import test.assertions.Assertions;
public class PBETest extends UsagePatternTestingFramework {
@Override
protected Ruleset getRuleSet() {
return Ruleset.JavaCryptographicArchitecture;
}
@Test
public void predictablePassword() throws GeneralSecurityException {
char[] defaultKey = new char[] {'s', 'a', 'a', 'g', 'a', 'r'};
byte[] salt = new byte[16];
SecureRandom sr = new SecureRandom();
sr.nextBytes(salt);
PBEKeySpec pbeKeySpec = new PBEKeySpec(defaultKey, salt, 11010, 16);
Assertions.notHasEnsuredPredicate(pbeKeySpec);
pbeKeySpec.clearPassword();
Assertions.mustBeInAcceptingState(pbeKeySpec);
}
@Test
public void unPredictablePassword() throws GeneralSecurityException {
char[] defaultKey = generateRandomPassword();
byte[] salt = new byte[16];
SecureRandom sr = new SecureRandom();
sr.nextBytes(salt);
PBEKeySpec pbeKeySpec = new PBEKeySpec(defaultKey, salt, 11010, 16);
Assertions.hasEnsuredPredicate(pbeKeySpec);
pbeKeySpec.clearPassword();
Assertions.mustBeInAcceptingState(pbeKeySpec);
}
@Test
public void pbeUsagePatternMinPBEIterationsMinimized() throws GeneralSecurityException, IOException {
final byte[] salt = new byte[32];
SecureRandom.getInstanceStrong().nextBytes(salt);
char[] corPwd = generateRandomPassword();;
PBEKeySpec pbekeyspec = new PBEKeySpec(corPwd, salt, 100000, 128);
Assertions.extValue(1);
}
@Test
public void pbeUsagePatternMinPBEIterations() throws GeneralSecurityException, IOException {
final byte[] salt = new byte[32];
SecureRandom.getInstanceStrong().nextBytes(salt);
char[] corPwd = generateRandomPassword();
PBEKeySpec pbekeyspec = new PBEKeySpec(corPwd, salt, 100000, 128);
Assertions.extValue(1);
Assertions.extValue(2);
Assertions.extValue(3);
Assertions.hasEnsuredPredicate(pbekeyspec);
Assertions.mustNotBeInAcceptingState(pbekeyspec);
pbekeyspec.clearPassword();
pbekeyspec = new PBEKeySpec(corPwd, salt, 9999, 128);
Assertions.extValue(1);
Assertions.extValue(2);
Assertions.extValue(3);
Assertions.notHasEnsuredPredicate(pbekeyspec);
Assertions.mustNotBeInAcceptingState(pbekeyspec);
pbekeyspec.clearPassword();
PBEParameterSpec pbeparspec = new PBEParameterSpec(salt, 10000);
Assertions.extValue(0);
Assertions.extValue(1);
Assertions.mustBeInAcceptingState(pbeparspec);
Assertions.hasEnsuredPredicate(pbeparspec);
pbeparspec = new PBEParameterSpec(salt, 9999);
Assertions.extValue(0);
Assertions.extValue(1);
Assertions.mustBeInAcceptingState(pbeparspec);
Assertions.notHasEnsuredPredicate(pbeparspec);
}
@Test
public void pbeUsagePattern1() throws GeneralSecurityException, IOException {
final byte[] salt = new byte[32];
SecureRandom.getInstanceStrong().nextBytes(salt);
Assertions.hasEnsuredPredicate(salt);
char[] corPwd = generateRandomPassword();;
final PBEKeySpec pbekeyspec = new PBEKeySpec(corPwd, salt, 65000, 128);
// Assertions.violatedConstraint(pbekeyspec);
Assertions.extValue(1);
Assertions.extValue(2);
Assertions.extValue(3);
Assertions.hasEnsuredPredicate(pbekeyspec);
Assertions.mustNotBeInAcceptingState(pbekeyspec);
pbekeyspec.clearPassword();
}
@Test
public void pbeUsagePattern2() throws GeneralSecurityException, IOException {
final byte[] salt = new byte[32];
SecureRandom.getInstanceStrong().nextBytes(salt);
Assertions.hasEnsuredPredicate(salt);
final PBEKeySpec pbekeyspec = new PBEKeySpec(generateRandomPassword(), salt, 65000, 128);
Assertions.extValue(2);
Assertions.extValue(3);
Assertions.mustNotBeInAcceptingState(pbekeyspec);
Assertions.hasEnsuredPredicate(pbekeyspec);
pbekeyspec.clearPassword();
Assertions.notHasEnsuredPredicate(pbekeyspec);
}
public char[] generateRandomPassword() {
SecureRandom rnd = new SecureRandom();
char[] defaultKey = new char[20];
for (int i = 0; i < 20; i++) {
defaultKey[i] = (char) (rnd.nextInt(26) + 'a');
}
return defaultKey;
}
@Test
public void pbeUsagePatternForbMeth() throws GeneralSecurityException, IOException {
char[] falsePwd = "password".toCharArray();
final PBEKeySpec pbekeyspec = new PBEKeySpec(falsePwd);
Assertions.callToForbiddenMethod();
}
}
| 4,531 | 31.371429 | 102 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/tests/pattern/SecretKeyTest.java | package tests.pattern;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.GeneralSecurityException;
import java.security.Key;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.List;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import javax.security.auth.DestroyFailedException;
import org.junit.Test;
import crypto.analysis.CrySLRulesetSelector.Ruleset;
import test.UsagePatternTestingFramework;
import test.assertions.Assertions;
public class SecretKeyTest extends UsagePatternTestingFramework {
@Override
protected Ruleset getRuleSet() {
return Ruleset.JavaCryptographicArchitecture;
}
@Test
public void secretKeyUsagePatternTestReqPredOr() throws GeneralSecurityException {
SecureRandom secRand = new SecureRandom();
Assertions.hasEnsuredPredicate(secRand);
KeyGenerator keygen = KeyGenerator.getInstance("AES");
Assertions.extValue(0);
keygen.init(128, secRand);
Assertions.extValue(0);
SecretKey key = keygen.generateKey();
Assertions.hasEnsuredPredicate(key);
}
@Test
public void secretKeyUsagePatternTest1Simple() throws GeneralSecurityException {
KeyGenerator keygen = KeyGenerator.getInstance("AES");
Assertions.extValue(0);
keygen.init(128);
Assertions.extValue(0);
SecretKey key = keygen.generateKey();
Assertions.hasEnsuredPredicate(key);
Assertions.mustBeInAcceptingState(keygen);
}
@Test
public void secretKeyUsagePattern2() throws GeneralSecurityException, IOException {
final byte[] salt = new byte[32];
SecureRandom.getInstanceStrong().nextBytes(salt);
char[] corPwd = generateRandomPassword();
final PBEKeySpec pbekeyspec = new PBEKeySpec(corPwd, salt, 65000, 128);
// Assertions.violatedConstraint(pbekeyspec);
Assertions.extValue(1);
Assertions.extValue(2);
Assertions.extValue(3);
Assertions.hasEnsuredPredicate(pbekeyspec);
Assertions.mustNotBeInAcceptingState(pbekeyspec);
final SecretKeyFactory secFac = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
Assertions.extValue(0);
final Cipher c = Cipher.getInstance("AES/GCM/NoPadding");
Assertions.extValue(0);
SecretKey tmpKey = secFac.generateSecret(pbekeyspec);
Assertions.mustBeInAcceptingState(secFac);
pbekeyspec.clearPassword();
byte[] keyMaterial = tmpKey.getEncoded();
final SecretKeySpec actKey = new SecretKeySpec(keyMaterial, "AES");
Assertions.extValue(1);
Assertions.hasEnsuredPredicate(actKey);
c.init(Cipher.ENCRYPT_MODE, actKey);
Assertions.extValue(0);
Assertions.mustBeInAcceptingState(actKey);
byte[] encText = c.doFinal("TESTPLAIN".getBytes("UTF-8"));
c.getIV();
Assertions.mustBeInAcceptingState(c);
Assertions.hasEnsuredPredicate(encText);
}
@Test
public void secretKeyUsagePattern3() throws GeneralSecurityException, IOException {
final byte[] salt = new byte[32];
SecureRandom.getInstanceStrong().nextBytes(salt);
final PBEKeySpec pbekeyspec = new PBEKeySpec(generateRandomPassword(), salt, 65000, 128);
Assertions.extValue(2);
Assertions.extValue(3);
Assertions.mustNotBeInAcceptingState(pbekeyspec);
final SecretKeyFactory secFac = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
Assertions.extValue(0);
SecretKey tmpKey = secFac.generateSecret(pbekeyspec);
Assertions.mustBeInAcceptingState(secFac);
pbekeyspec.clearPassword();
byte[] keyMaterial = tmpKey.getEncoded();
final SecretKeySpec actKey = new SecretKeySpec(keyMaterial, "AES");
Assertions.extValue(1);
Assertions.hasEnsuredPredicate(actKey);
}
public char[] generateRandomPassword() {
SecureRandom rnd = new SecureRandom();
char[] defaultKey = new char[20];
for (int i = 0; i < 20; i++) {
defaultKey[i] = (char) (rnd.nextInt(26) + 'a');
}
return defaultKey;
}
@Test
public void clearPasswordPredicateTest() throws NoSuchAlgorithmException, GeneralSecurityException {
Encryption encryption = new Encryption();
encryption.encryptData(new byte[] {}, "Test");
}
public static class Encryption {
byte[] salt = {15, -12, 94, 0, 12, 3, -65, 73, -1, -84, -35};
private SecretKey generateKey(String password) throws NoSuchAlgorithmException, GeneralSecurityException {
PBEKeySpec pBEKeySpec = new PBEKeySpec(password.toCharArray(), salt, 10000, 256);
SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("PBKDF2WithSHA256");
Assertions.notHasEnsuredPredicate(pBEKeySpec);
SecretKey generateSecret = secretKeyFactory.generateSecret(pBEKeySpec);
Assertions.notHasEnsuredPredicate(generateSecret);
byte[] keyMaterial = generateSecret.getEncoded();
Assertions.notHasEnsuredPredicate(keyMaterial);
SecretKey encryptionKey = new SecretKeySpec(keyMaterial, "AES");
// pBEKeySpec.clearPassword();
Assertions.notHasEnsuredPredicate(encryptionKey);
return encryptionKey;
}
private byte[] encrypt(byte[] plainText, SecretKey encryptionKey) throws GeneralSecurityException {
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, encryptionKey);
return cipher.doFinal(plainText);
}
public byte[] encryptData(byte[] plainText, String password) throws NoSuchAlgorithmException, GeneralSecurityException {
return encrypt(plainText, generateKey(password));
}
}
@Test
public void clearPasswordPredicateTest2() throws NoSuchAlgorithmException, GeneralSecurityException {
String password = "test";
byte[] salt = {15, -12, 94, 0, 12, 3, -65, 73, -1, -84, -35};
PBEKeySpec pBEKeySpec = new PBEKeySpec(password.toCharArray(), salt, 10000, 256);
SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("PBKDF2WithSHA256");
Assertions.extValue(0);
Assertions.notHasEnsuredPredicate(pBEKeySpec);
SecretKey generateSecret = secretKeyFactory.generateSecret(pBEKeySpec);
Assertions.notHasEnsuredPredicate(generateSecret);
byte[] keyMaterial = generateSecret.getEncoded();
Assertions.notHasEnsuredPredicate(keyMaterial);
}
@Test
public void secretKeyTest4() throws NoSuchAlgorithmException, DestroyFailedException {
KeyGenerator c = KeyGenerator.getInstance("AES");
Key key = c.generateKey();
Assertions.mustBeInAcceptingState(key);
byte[] enc = key.getEncoded();
Assertions.mustBeInAcceptingState(key);
enc = key.getEncoded();
Assertions.mustBeInAcceptingState(key);
((SecretKey) key).destroy();
Assertions.mustBeInAcceptingState(key);
}
@Test
public void setEntryKeyStore() throws GeneralSecurityException, IOException {
KeyStore keyStore = KeyStore.getInstance("PKCS12");
keyStore.load(null, null);
Assertions.mustBeInAcceptingState(keyStore);
// Add private and public key (certificate) to keystore
keyStore.setEntry("alias", null, null);
keyStore.store(null, "Password".toCharArray());
Assertions.mustBeInAcceptingState(keyStore);
}
@Test
public void secretKeyUsagePatternTest5() throws GeneralSecurityException {
KeyGenerator keygen = KeyGenerator.getInstance("AES");
Assertions.extValue(0);
keygen.init(1);
Assertions.extValue(0);
SecretKey key = keygen.generateKey();
Assertions.notHasEnsuredPredicate(key);
// Assertions.mustBeInAcceptingState(keygen);
// Cipher cCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
// Assertions.extValue(0);
// cCipher.init(Cipher.ENCRYPT_MODE, key);
//
// Assertions.extValue(0);
// byte[] encText = cCipher.doFinal("".getBytes());
// Assertions.notHasEnsuredPredicate(encText);
// Assertions.mustBeInAcceptingState(cCipher);
}
@Test
public void secretKeyUsagePatternTest6() throws GeneralSecurityException {
Encrypter enc = new Encrypter();
byte[] encText = enc.encrypt("Test");
Assertions.hasEnsuredPredicate(encText);
}
public static class Encrypter {
Cipher cipher;
public Encrypter() throws GeneralSecurityException {
KeyGenerator keygen = KeyGenerator.getInstance("AES");
keygen.init(128);
SecretKey key = keygen.generateKey();
this.cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
this.cipher.init(Cipher.ENCRYPT_MODE, key);
this.cipher.getIV();
}
public byte[] encrypt(String plainText) throws GeneralSecurityException {
byte[] encText = this.cipher.doFinal(plainText.getBytes());
Assertions.hasEnsuredPredicate(encText);
return encText;
}
}
@Test
public void secretKeyUsagePattern7() throws GeneralSecurityException, IOException {
final byte[] salt = new byte[32];
SecureRandom.getInstanceStrong().nextBytes(salt);
char[] falsePwd = "password".toCharArray();
final PBEKeySpec pbekeyspec = new PBEKeySpec(falsePwd, salt, 65000, 128);
Assertions.extValue(0);
Assertions.extValue(1);
Assertions.extValue(2);
Assertions.extValue(3);
Assertions.notHasEnsuredPredicate(pbekeyspec);
Assertions.mustNotBeInAcceptingState(pbekeyspec);
final SecretKeyFactory secFac = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
final Cipher c = Cipher.getInstance("AES/GCM/NoPadding");
Assertions.extValue(0);
SecretKey tmpKey = secFac.generateSecret(pbekeyspec);
pbekeyspec.clearPassword();
byte[] keyMaterial = tmpKey.getEncoded();
final SecretKeySpec actKey = new SecretKeySpec(keyMaterial, "AES");
Assertions.extValue(1);
Assertions.notHasEnsuredPredicate(actKey);
c.init(Cipher.ENCRYPT_MODE, actKey);
Assertions.extValue(0);
Assertions.mustBeInAcceptingState(actKey);
byte[] encText = c.doFinal("TESTPLAIN".getBytes("UTF-8"));
c.getIV();
Assertions.mustBeInAcceptingState(c);
Assertions.notHasEnsuredPredicate(encText);
}
@Test
public void exceptionFlowTest() {
KeyGenerator keygen = null;
try {
keygen = KeyGenerator.getInstance("AES");
Assertions.extValue(0);
}
catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
keygen.init(128);
Assertions.extValue(0);
SecretKey key = keygen.generateKey();
Assertions.mustBeInAcceptingState(keygen);
}
@Test
public void secretKeyUsagePatternTestConfigFile() throws GeneralSecurityException, IOException {
List<String> s = Files.readAllLines(Paths.get("../../../resources/config.txt"));
KeyGenerator keygen = KeyGenerator.getInstance(s.get(0));
Assertions.extValue(0);
keygen.init(128);
Assertions.extValue(0);
SecretKey key = keygen.generateKey();
Assertions.hasEnsuredPredicate(key);
Assertions.mustBeInAcceptingState(keygen);
}
}
| 10,545 | 32.059561 | 122 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/tests/pattern/SecureRandomTest.java | package tests.pattern;
import java.security.GeneralSecurityException;
import java.security.SecureRandom;
import org.junit.Test;
import crypto.analysis.CrySLRulesetSelector.Ruleset;
import test.UsagePatternTestingFramework;
import test.assertions.Assertions;
public class SecureRandomTest extends UsagePatternTestingFramework {
@Override
protected Ruleset getRuleSet() {
return Ruleset.JavaCryptographicArchitecture;
}
@Test
public void corSeed() throws GeneralSecurityException {
SecureRandom r3 = SecureRandom.getInstanceStrong();
Assertions.hasEnsuredPredicate(r3);
SecureRandom r4 = SecureRandom.getInstanceStrong();
Assertions.hasEnsuredPredicate(r4);
r4.setSeed(r3.nextInt());
}
@Test
public void fixedSeed() throws GeneralSecurityException {
final int fixedSeed = 10;
SecureRandom r3 = SecureRandom.getInstanceStrong();
r3.setSeed(fixedSeed);
Assertions.notHasEnsuredPredicate(r3);
SecureRandom r4 = SecureRandom.getInstanceStrong();
Assertions.notHasEnsuredPredicate(r4);
r4.setSeed(r3.nextInt());
}
@Test
public void dynSeed() throws GeneralSecurityException {
SecureRandom srPrep = new SecureRandom();
byte[] bytes = new byte[32];
srPrep.nextBytes(bytes);
Assertions.mustBeInAcceptingState(srPrep);
Assertions.hasEnsuredPredicate(bytes);
// sr.setSeed(456789L); // Noncompliant
SecureRandom sr = new SecureRandom();
sr.setSeed(bytes);
int v = sr.nextInt();
Assertions.hasEnsuredPredicate(v);
Assertions.mustBeInAcceptingState(sr);
}
@Test
public void staticSeed() throws GeneralSecurityException {
byte[] bytes = {(byte) 100, (byte) 200};
SecureRandom sr = new SecureRandom();
sr.setSeed(bytes);
int v = sr.nextInt();
Assertions.notHasEnsuredPredicate(v);
Assertions.mustBeInAcceptingState(sr);
}
}
| 1,802 | 25.514706 | 68 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/tests/pattern/SignatureTest.java | package tests.pattern;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import org.bouncycastle.util.encoders.Hex;
import org.junit.Test;
import crypto.analysis.CrySLRulesetSelector.Ruleset;
import test.UsagePatternTestingFramework;
import test.assertions.Assertions;
public class SignatureTest extends UsagePatternTestingFramework {
private static final byte[] tData = Hex.decode("355F697E8B868B65B25A04E18D782AFA");
@Override
protected Ruleset getRuleSet() {
return Ruleset.JavaCryptographicArchitecture;
}
@Test
public void testSignature2() throws InvalidKeyException, GeneralSecurityException {
Signature s = Signature.getInstance("SHA256withRSA");
/**
* The Signature API expects a call to update here. This call supplied the actual data to the signature instance.
* A call such as s.update(data); would resolve this finding.
*/
s.initSign(getPrivateKey());
s.update(tData);
s.sign();
Assertions.notHasEnsuredPredicate(s); // passing
Assertions.mustBeInAcceptingState(s);
}
@Test
public void testSignature1() throws InvalidKeyException, GeneralSecurityException {
Signature s = Signature.getInstance("SHA256withRSA");
// no initSign call
s.update("".getBytes());
s.sign();
Assertions.notHasEnsuredPredicate(s);
Assertions.mustNotBeInAcceptingState(s);
}
private static PrivateKey getPrivateKey() throws GeneralSecurityException {
KeyPairGenerator kpgen = KeyPairGenerator.getInstance("RSA");
kpgen.initialize(2048);
KeyPair gp = kpgen.generateKeyPair();
return gp.getPrivate();
}
@Test
public void signUsagePatternTest1() throws GeneralSecurityException, UnsupportedEncodingException {
String input = "TESTITESTiTEsTI";
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA");
Assertions.extValue(0);
keyGen.initialize(2048);
KeyPair kp = keyGen.generateKeyPair();
Assertions.mustBeInAcceptingState(keyGen);
Assertions.hasEnsuredPredicate(kp);
final PrivateKey privKey = kp.getPrivate();
Assertions.hasEnsuredPredicate(privKey);
Signature sign = Signature.getInstance("SHA256withDSA");
Assertions.extValue(0);
sign.initSign(privKey);
sign.update(input.getBytes("UTF-8"));
byte[] signature = sign.sign();
Assertions.mustBeInAcceptingState(sign);
Assertions.hasEnsuredPredicate(signature);
}
@Test
public void signUsagePatternTest2() throws GeneralSecurityException, UnsupportedEncodingException {
String input = "TESTITESTiTEsTI";
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA");
Assertions.extValue(0);
keyGen.initialize(2048);
KeyPair kp = keyGen.generateKeyPair();
Assertions.mustBeInAcceptingState(keyGen);
Assertions.hasEnsuredPredicate(kp);
final PrivateKey privKey = kp.getPrivate();
Assertions.hasEnsuredPredicate(privKey);
String algorithm = "SHA256withDSA";
if (Math.random() % 2 == 0) {
algorithm = "SHA256withECDSA";
}
Signature sign = Signature.getInstance(algorithm);
Assertions.extValue(0);
sign.initSign(privKey);
sign.update(input.getBytes("UTF-8"));
byte[] signature = sign.sign();
Assertions.mustBeInAcceptingState(sign);
Assertions.hasEnsuredPredicate(signature);
}
@Test
public void signUsagePatternTest3() throws GeneralSecurityException, UnsupportedEncodingException {
String input = "TESTITESTiTEsTI";
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA");
Assertions.extValue(0);
keyGen.initialize(2048);
KeyPair kp = keyGen.generateKeyPair();
Assertions.mustBeInAcceptingState(keyGen);
Assertions.hasEnsuredPredicate(kp);
final PrivateKey privKey = kp.getPrivate();
Assertions.mustBeInAcceptingState(kp);
Assertions.hasEnsuredPredicate(privKey);
Signature sign = Signature.getInstance("SHA256withDSA");
Assertions.extValue(0);
sign.initSign(privKey);
sign.update(input.getBytes("UTF-8"));
byte[] signature = sign.sign();
Assertions.mustBeInAcceptingState(sign);
Assertions.hasEnsuredPredicate(signature);
final PublicKey pubKey = kp.getPublic();
Assertions.mustBeInAcceptingState(kp);
Assertions.hasEnsuredPredicate(pubKey);
Signature ver = Signature.getInstance("SHA256withDSA");
Assertions.extValue(0);
//
ver.initVerify(pubKey);
ver.update(input.getBytes("UTF-8"));
ver.verify(signature);
Assertions.mustBeInAcceptingState(ver);
}
}
| 4,573 | 30.328767 | 115 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/tests/pattern/tink/TestAEADCipher.java | package tests.pattern.tink;
import java.security.GeneralSecurityException;
import org.junit.Ignore;
import org.junit.Test;
import com.google.crypto.tink.Aead;
import com.google.crypto.tink.KeysetHandle;
import com.google.crypto.tink.aead.AeadFactory;
import com.google.crypto.tink.aead.AeadKeyTemplates;
import com.google.crypto.tink.proto.KeyTemplate;
import crypto.analysis.CrySLRulesetSelector.Ruleset;
import test.assertions.Assertions;
@Ignore
public class TestAEADCipher extends TestTinkPrimitives {
@Override
protected Ruleset getRuleSet() {
return Ruleset.Tink;
}
@Test
public void generateNewAES128GCMKeySet() throws GeneralSecurityException {
KeyTemplate kt = AeadKeyTemplates.createAesGcmKeyTemplate(16);
KeysetHandle ksh = KeysetHandle.generateNew(kt);
Assertions.hasEnsuredPredicate(kt);
Assertions.mustBeInAcceptingState(kt);
Assertions.mustBeInAcceptingState(ksh);
}
@Test
public void generateNewAES256GCMKeySet() throws GeneralSecurityException {
KeyTemplate kt = AeadKeyTemplates.createAesGcmKeyTemplate(32);
KeysetHandle ksh = KeysetHandle.generateNew(kt);
Assertions.mustBeInAcceptingState(kt);
Assertions.mustBeInAcceptingState(ksh);
}
@Test
public void generateNewAES128EAXKeySet() throws GeneralSecurityException {
KeyTemplate kt = AeadKeyTemplates.createAesEaxKeyTemplate(16, 16);
KeysetHandle ksh = KeysetHandle.generateNew(kt);
Assertions.mustBeInAcceptingState(kt);
Assertions.mustBeInAcceptingState(ksh);
}
@Test
public void generateNewAES256EAXKeySet() throws GeneralSecurityException {
KeyTemplate kt = AeadKeyTemplates.createAesEaxKeyTemplate(32, 16);
KeysetHandle ksh = KeysetHandle.generateNew(kt);
Assertions.mustBeInAcceptingState(kt);
Assertions.mustBeInAcceptingState(ksh);
}
@Test
public void encryptUsingAES128GCM() throws GeneralSecurityException {
KeyTemplate kt = AeadKeyTemplates.createAesGcmKeyTemplate(16);
KeysetHandle ksh = KeysetHandle.generateNew(kt);
Assertions.hasEnsuredPredicate(kt); //this might look crazy, but sometimes Ok. in other executions, this line leads to a red bar.
final String plainText = "Just testing the encryption mode of AEAD";
final String aad = "crysl";
Aead aead = AeadFactory.getPrimitive(ksh);
byte[] out = aead.encrypt(plainText.getBytes(), aad.getBytes());
Assertions.hasEnsuredPredicate(aead);
Assertions.mustBeInAcceptingState(aead);
//Assertions.hasEnsuredPredicate(out); // this assertions still leads to a red bar.
}
}
| 2,519 | 31.727273 | 133 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/tests/pattern/tink/TestDeterministicAEADCipher.java | package tests.pattern.tink;
import java.security.GeneralSecurityException;
import org.junit.Ignore;
import org.junit.Test;
import com.google.crypto.tink.DeterministicAead;
import com.google.crypto.tink.KeysetHandle;
import com.google.crypto.tink.daead.DeterministicAeadFactory;
import com.google.crypto.tink.daead.DeterministicAeadKeyTemplates;
import com.google.crypto.tink.proto.KeyTemplate;
import crypto.analysis.CrySLRulesetSelector.Ruleset;
import test.assertions.Assertions;
@Ignore
public class TestDeterministicAEADCipher extends TestTinkPrimitives {
@Override
protected Ruleset getRuleSet() {
return Ruleset.Tink;
}
@Test
public void generateNewAES128GCMKeySet() throws GeneralSecurityException {
KeyTemplate kt = DeterministicAeadKeyTemplates.createAesSivKeyTemplate(64);
KeysetHandle ksh = KeysetHandle.generateNew(kt);
Assertions.hasEnsuredPredicate(kt);
Assertions.hasEnsuredPredicate(ksh);
Assertions.mustBeInAcceptingState(kt);
Assertions.mustBeInAcceptingState(ksh);
}
@Test
public void encryptUsingAES256_SIV() throws GeneralSecurityException {
KeyTemplate kt = DeterministicAeadKeyTemplates.createAesSivKeyTemplate(64);
KeysetHandle ksh = KeysetHandle.generateNew(kt);
Assertions.hasEnsuredPredicate(kt);
final String plainText = "Just testing the encryption mode of DAEAD";
final String aad = "crysl";
DeterministicAead daead = DeterministicAeadFactory.getPrimitive(ksh);
byte[] out = daead.encryptDeterministically(plainText.getBytes(), aad.getBytes());
Assertions.hasEnsuredPredicate(daead);
Assertions.mustBeInAcceptingState(daead);
//Assertions.hasEnsuredPredicate(out); // this assertions still leads to a red bar.
}
@Test
public void encryptUsingNullKeyTemplate() throws GeneralSecurityException {
KeyTemplate kt = null ;
KeysetHandle ksh = KeysetHandle.generateNew(kt);
Assertions.notHasEnsuredPredicate(kt);
Assertions.notHasEnsuredPredicate(kt);
}
@Test
public void encryptUsingInvalidKey() throws GeneralSecurityException {
KeyTemplate kt = DeterministicAeadKeyTemplates.createAesSivKeyTemplate(32);
Assertions.notHasEnsuredPredicate(kt);
}
}
| 2,181 | 29.732394 | 86 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/tests/pattern/tink/TestDigitalSignature.java | package tests.pattern.tink;
import java.security.GeneralSecurityException;
import org.junit.Ignore;
import org.junit.Test;
import com.google.crypto.tink.KeysetHandle;
import com.google.crypto.tink.PublicKeySign;
import com.google.crypto.tink.PublicKeyVerify;
import com.google.crypto.tink.proto.EcdsaSignatureEncoding;
import com.google.crypto.tink.proto.EllipticCurveType;
import com.google.crypto.tink.proto.HashType;
import com.google.crypto.tink.proto.KeyTemplate;
import com.google.crypto.tink.signature.PublicKeySignFactory;
import com.google.crypto.tink.signature.PublicKeyVerifyFactory;
import com.google.crypto.tink.signature.SignatureKeyTemplates;
import crypto.analysis.CrySLRulesetSelector.Ruleset;
import test.assertions.Assertions;
@SuppressWarnings("deprecation")
@Ignore
public class TestDigitalSignature extends TestTinkPrimitives {
@Override
protected Ruleset getRuleSet() {
return Ruleset.Tink;
}
@Test
public void generateNewECDSA_P256() throws GeneralSecurityException {
KeyTemplate kt = SignatureKeyTemplates.createEcdsaKeyTemplate(HashType.SHA256, EllipticCurveType.NIST_P256, EcdsaSignatureEncoding.DER, null);
KeysetHandle ksh = KeysetHandle.generateNew(kt);
Assertions.mustBeInAcceptingState(kt);
Assertions.mustBeInAcceptingState(ksh);
}
@Test
public void generateNewECDSA_P384() throws GeneralSecurityException {
KeyTemplate kt = SignatureKeyTemplates.createEcdsaKeyTemplate(HashType.SHA512, EllipticCurveType.NIST_P384, EcdsaSignatureEncoding.DER, null);
KeysetHandle ksh = KeysetHandle.generateNew(kt);
Assertions.mustBeInAcceptingState(kt);
Assertions.mustBeInAcceptingState(ksh);
}
@Test
public void generateNewECDSA_P521() throws GeneralSecurityException {
KeyTemplate kt = SignatureKeyTemplates.createEcdsaKeyTemplate(HashType.SHA512, EllipticCurveType.NIST_P521, EcdsaSignatureEncoding.DER, null);
KeysetHandle ksh = KeysetHandle.generateNew(kt);
Assertions.mustBeInAcceptingState(kt);
Assertions.mustBeInAcceptingState(ksh);
}
@Test
public void generateNewECDSA_P256_IEEE_P1363() throws GeneralSecurityException {
KeyTemplate kt = SignatureKeyTemplates.createEcdsaKeyTemplate(HashType.SHA256, EllipticCurveType.NIST_P256, EcdsaSignatureEncoding.IEEE_P1363, null);
KeysetHandle ksh = KeysetHandle.generateNew(kt);
Assertions.mustBeInAcceptingState(kt);
Assertions.mustBeInAcceptingState(ksh);
}
@Test
public void generateNewECDSA_P384_IEEE_P1363() throws GeneralSecurityException {
KeyTemplate kt = SignatureKeyTemplates.createEcdsaKeyTemplate(HashType.SHA512, EllipticCurveType.NIST_P384, EcdsaSignatureEncoding.IEEE_P1363, null);
KeysetHandle ksh = KeysetHandle.generateNew(kt);
Assertions.mustBeInAcceptingState(kt);
Assertions.mustBeInAcceptingState(ksh);
}
@Test
public void generateNewECDSA_P521_IEEE_P1363() throws GeneralSecurityException {
KeyTemplate kt = SignatureKeyTemplates.createEcdsaKeyTemplate(HashType.SHA512, EllipticCurveType.NIST_P521, EcdsaSignatureEncoding.IEEE_P1363, null);
KeysetHandle ksh = KeysetHandle.generateNew(kt);
Assertions.mustBeInAcceptingState(kt);
Assertions.mustBeInAcceptingState(ksh);
}
@Test
public void signUsingECDSA_P256() throws GeneralSecurityException {
KeyTemplate kt = SignatureKeyTemplates.createEcdsaKeyTemplate(HashType.SHA256, EllipticCurveType.NIST_P256, EcdsaSignatureEncoding.DER, null);;
KeysetHandle ksh = KeysetHandle.generateNew(kt);
Assertions.mustBeInAcceptingState(kt);
Assertions.mustBeInAcceptingState(ksh);
@SuppressWarnings("deprecation")
PublicKeySign pks = PublicKeySignFactory.getPrimitive(ksh);
pks.sign("this is just a test using digital signatures using Google Tink".getBytes());
Assertions.hasEnsuredPredicate(pks);
Assertions.mustBeInAcceptingState(pks);
}
@Test
public void signAndVerifyUsingECDSA_P256() throws GeneralSecurityException {
KeyTemplate kt = SignatureKeyTemplates.createEcdsaKeyTemplate(HashType.SHA256, EllipticCurveType.NIST_P256, EcdsaSignatureEncoding.DER, null);;
KeysetHandle ksh = KeysetHandle.generateNew(kt);
Assertions.mustBeInAcceptingState(kt);
Assertions.mustBeInAcceptingState(ksh);
@SuppressWarnings("deprecation")
PublicKeySign pks = PublicKeySignFactory.getPrimitive(ksh);
String data = "this is just a test using digital signatures using Google Tink";
byte[] signature = pks.sign(data.getBytes());
Assertions.hasEnsuredPredicate(pks);
Assertions.mustBeInAcceptingState(pks);
KeysetHandle publicKsh = ksh.getPublicKeysetHandle();
Assertions.hasEnsuredPredicate(publicKsh);
@SuppressWarnings("deprecation")
PublicKeyVerify pkv = PublicKeyVerifyFactory.getPrimitive(publicKsh);
Assertions.hasEnsuredPredicate(pkv);
pkv.verify(signature, data.getBytes());
}
}
| 4,783 | 37.580645 | 151 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/tests/pattern/tink/TestHybridEncryption.java | package tests.pattern.tink;
import java.security.GeneralSecurityException;
import org.junit.Ignore;
import org.junit.Test;
import com.google.crypto.tink.HybridDecrypt;
import com.google.crypto.tink.HybridEncrypt;
import com.google.crypto.tink.KeysetHandle;
import com.google.crypto.tink.aead.AeadKeyTemplates;
import com.google.crypto.tink.hybrid.HybridDecryptFactory;
import com.google.crypto.tink.hybrid.HybridEncryptFactory;
import com.google.crypto.tink.hybrid.HybridKeyTemplates;
import com.google.crypto.tink.proto.EcPointFormat;
import com.google.crypto.tink.proto.EllipticCurveType;
import com.google.crypto.tink.proto.HashType;
import com.google.crypto.tink.proto.KeyTemplate;
import crypto.analysis.CrySLRulesetSelector.Ruleset;
import test.assertions.Assertions;
@Ignore
public class TestHybridEncryption extends TestTinkPrimitives {
@Override
protected Ruleset getRuleSet() {
return Ruleset.Tink;
}
@Test
public void generateNewECIES_P256_HKDF_HMAC_SHA256_AES128_GCMKeySet() throws GeneralSecurityException {
KeyTemplate kt = HybridKeyTemplates.createEciesAeadHkdfKeyTemplate(EllipticCurveType.NIST_P256,
HashType.SHA256,
EcPointFormat.UNCOMPRESSED,
AeadKeyTemplates.AES128_GCM,
new byte[0]);
KeysetHandle ksh = KeysetHandle.generateNew(kt);
Assertions.hasEnsuredPredicate(kt);
Assertions.mustBeInAcceptingState(kt);
Assertions.mustBeInAcceptingState(ksh);
}
@Test
public void generateNewECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256KeySet() throws GeneralSecurityException {
KeyTemplate kt = HybridKeyTemplates.createEciesAeadHkdfKeyTemplate(
EllipticCurveType.NIST_P256,
HashType.SHA256,
EcPointFormat.UNCOMPRESSED,
AeadKeyTemplates.AES128_CTR_HMAC_SHA256,
new byte[0]);
KeysetHandle ksh = KeysetHandle.generateNew(kt);
Assertions.hasEnsuredPredicate(kt);
Assertions.mustBeInAcceptingState(kt);
Assertions.mustBeInAcceptingState(ksh);
}
@Test
public void generateInvalidKey() {
KeyTemplate kt = null;
Assertions.notHasEnsuredPredicate(kt);
}
@Test
public void encryptUsingECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256KeySet() throws GeneralSecurityException {
KeyTemplate kt = HybridKeyTemplates.createEciesAeadHkdfKeyTemplate(
EllipticCurveType.NIST_P256,
HashType.SHA256,
EcPointFormat.UNCOMPRESSED,
AeadKeyTemplates.AES128_CTR_HMAC_SHA256,
new byte[0]);
KeysetHandle ksh = KeysetHandle.generateNew(kt);
KeysetHandle publicKsh = ksh.getPublicKeysetHandle();
HybridEncrypt cipher = HybridEncryptFactory.getPrimitive(publicKsh);
byte[] cipherText = cipher.encrypt("just an hybrid encryption test".getBytes(), "".getBytes());
Assertions.hasEnsuredPredicate(kt);
Assertions.hasEnsuredPredicate(publicKsh);
Assertions.hasEnsuredPredicate(cipher);
Assertions.mustBeInAcceptingState(kt);
Assertions.mustBeInAcceptingState(ksh);
Assertions.mustBeInAcceptingState(publicKsh);
}
@Test
public void decryptUsingECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256KeySet() throws GeneralSecurityException {
KeyTemplate kt = HybridKeyTemplates.createEciesAeadHkdfKeyTemplate(
EllipticCurveType.NIST_P256,
HashType.SHA256,
EcPointFormat.UNCOMPRESSED,
AeadKeyTemplates.AES128_CTR_HMAC_SHA256,
new byte[0]);
KeysetHandle ksh = KeysetHandle.generateNew(kt);
HybridDecrypt cipher = HybridDecryptFactory.getPrimitive(ksh);
byte[] cipherText = cipher.decrypt("mxvw d sodlq whaw iru whvwlqj".getBytes(), "".getBytes());
Assertions.hasEnsuredPredicate(kt);
Assertions.hasEnsuredPredicate(ksh);
Assertions.hasEnsuredPredicate(cipher);
Assertions.mustBeInAcceptingState(kt);
Assertions.mustBeInAcceptingState(ksh);
}
}
| 3,924 | 33.429825 | 117 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/tests/pattern/tink/TestMAC.java | package tests.pattern.tink;
import java.security.GeneralSecurityException;
import org.junit.Ignore;
import org.junit.Test;
import com.google.crypto.tink.KeysetHandle;
import com.google.crypto.tink.Mac;
import com.google.crypto.tink.mac.MacFactory;
import com.google.crypto.tink.mac.MacKeyTemplates;
import com.google.crypto.tink.proto.HashType;
import com.google.crypto.tink.proto.KeyTemplate;
import crypto.analysis.CrySLRulesetSelector.Ruleset;
import test.assertions.Assertions;
@Ignore
public class TestMAC extends TestTinkPrimitives {
@Override
protected Ruleset getRuleSet() {
return Ruleset.Tink;
}
@Test
public void generateNewHMACSHA256_128BitTag() throws GeneralSecurityException {
KeyTemplate kt = MacKeyTemplates.createHmacKeyTemplate(32, 16, HashType.SHA256);
KeysetHandle ksh = KeysetHandle.generateNew(kt);
Assertions.mustBeInAcceptingState(kt);
Assertions.mustBeInAcceptingState(ksh);
}
@Test
public void generateNewHMACSHA256_256BitTag() throws GeneralSecurityException {
KeyTemplate kt = MacKeyTemplates.createHmacKeyTemplate(32, 32, HashType.SHA256);
KeysetHandle ksh = KeysetHandle.generateNew(kt);
Assertions.mustBeInAcceptingState(kt);
Assertions.mustBeInAcceptingState(ksh);
}
@Test
public void testGenerateMAC() throws GeneralSecurityException {
KeyTemplate kt = MacKeyTemplates.createHmacKeyTemplate(32, 16, HashType.SHA256);
KeysetHandle ksh = KeysetHandle.generateNew(kt);
Mac mac = MacFactory.getPrimitive(ksh);
final byte[] data = "This is just a sample text".getBytes();
final byte[] tag = mac.computeMac(data);
mac.verifyMac(tag, data);
Assertions.mustBeInAcceptingState(mac);
}
}
| 1,679 | 29 | 82 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/tests/pattern/tink/TestStreamingAEADCipher.java | package tests.pattern.tink;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;
import java.security.GeneralSecurityException;
import org.junit.Ignore;
import org.junit.Test;
import com.google.crypto.tink.KeysetHandle;
import com.google.crypto.tink.StreamingAead;
import com.google.crypto.tink.proto.HashType;
import com.google.crypto.tink.proto.KeyTemplate;
import com.google.crypto.tink.streamingaead.StreamingAeadFactory;
import com.google.crypto.tink.streamingaead.StreamingAeadKeyTemplates;
import crypto.analysis.CrySLRulesetSelector.Ruleset;
import test.assertions.Assertions;
@Ignore
public class TestStreamingAEADCipher extends TestTinkPrimitives {
@Override
protected Ruleset getRuleSet() {
return Ruleset.Tink;
}
@Test
public void generateNewAES128_CTR_HMAC_SHA256_4KBKeySet() throws GeneralSecurityException {
KeyTemplate kt = StreamingAeadKeyTemplates.createAesCtrHmacStreamingKeyTemplate(16, HashType.SHA256, 16, HashType.SHA256, 32, 4096);
KeysetHandle ksh = KeysetHandle.generateNew(kt);
Assertions.hasEnsuredPredicate(kt);
Assertions.mustBeInAcceptingState(kt);
Assertions.mustBeInAcceptingState(ksh);
}
@Test
public void generateNewAES256_CTR_HMAC_SHA256_4KBKeySet() throws GeneralSecurityException {
KeyTemplate kt = StreamingAeadKeyTemplates.createAesCtrHmacStreamingKeyTemplate(32, HashType.SHA256, 32, HashType.SHA256, 32, 4096);
KeysetHandle ksh = KeysetHandle.generateNew(kt);
Assertions.hasEnsuredPredicate(kt);
Assertions.mustBeInAcceptingState(kt);
Assertions.mustBeInAcceptingState(ksh);
}
@Test
public void generateNewAES128_GCM_HKDF_4KBKeySet() throws GeneralSecurityException {
KeyTemplate kt = StreamingAeadKeyTemplates.createAesGcmHkdfStreamingKeyTemplate(16, HashType.SHA256, 16, 4096);
KeysetHandle ksh = KeysetHandle.generateNew(kt);
Assertions.hasEnsuredPredicate(kt);
Assertions.mustBeInAcceptingState(kt);
Assertions.mustBeInAcceptingState(ksh);
}
@Test
public void generateNewAES256_GCM_HKDF_4KBKeySet() throws GeneralSecurityException {
KeyTemplate kt = StreamingAeadKeyTemplates.createAesGcmHkdfStreamingKeyTemplate(32, HashType.SHA256, 32, 4096);
KeysetHandle ksh = KeysetHandle.generateNew(kt);
Assertions.hasEnsuredPredicate(kt);
Assertions.mustBeInAcceptingState(kt);
Assertions.mustBeInAcceptingState(ksh);
}
@Test
public void generateNewInvalidKeySet() throws GeneralSecurityException {
KeyTemplate kt = null;
Assertions.notHasEnsuredPredicate(kt);
Assertions.mustNotBeInAcceptingState(kt);
}
@Test
public void encryptUsingAES128_CTR_HMAC_SHA256_4KB() throws GeneralSecurityException {
KeyTemplate kt = StreamingAeadKeyTemplates.createAesCtrHmacStreamingKeyTemplate(16, HashType.SHA256, 16, HashType.SHA256, 32, 4096);
KeysetHandle ksh = KeysetHandle.generateNew(kt);
Assertions.hasEnsuredPredicate(kt);
try(FileChannel destination = new FileOutputStream("file.tx").getChannel();) {
StreamingAead saead = StreamingAeadFactory.getPrimitive(ksh);
WritableByteChannel out = saead.newEncryptingChannel(destination, "crysl".getBytes());
Assertions.hasEnsuredPredicate(saead);
Assertions.mustBeInAcceptingState(saead);
}
catch(IOException e) {
e.printStackTrace();
}
}
}
| 3,344 | 35.758242 | 134 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/tests/pattern/tink/TestSuite.java | package tests.pattern.tink;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
@RunWith(Suite.class)
@SuiteClasses({
TestAEADCipher.class,
TestDeterministicAEADCipher.class,
TestDigitalSignature.class,
TestHybridEncryption.class,
TestMAC.class,
TestStreamingAEADCipher.class
})
public class TestSuite {
}
| 375 | 18.789474 | 44 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/tests/pattern/tink/TestTinkPrimitives.java | package tests.pattern.tink;
import java.io.File;
import org.junit.Ignore;
import test.UsagePatternTestingFramework;
@Ignore
public abstract class TestTinkPrimitives extends UsagePatternTestingFramework {
@Override
protected String getSootClassPath() {
String sootCp = super.getSootClassPath();
String userHome = System.getProperty("user.home");
sootCp += File.pathSeparator + userHome + "/.m2/repository/com/google/crypto/tink/tink/1.2.0/tink-1.2.0.jar";
return sootCp;
}
}
| 497 | 22.714286 | 115 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/tests/providerdetection/ProviderDetectionTestingFramework.java | package tests.providerdetection;
import java.io.File;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import boomerang.callgraph.ObservableDynamicICFG;
import boomerang.preanalysis.BoomerangPretransformer;
import crypto.analysis.CrySLRulesetSelector.Ruleset;
import crypto.providerdetection.ProviderDetection;
import soot.G;
import soot.PackManager;
import soot.Scene;
import soot.SceneTransformer;
import soot.SootClass;
import soot.Transform;
import soot.Transformer;
import soot.options.Options;
public class ProviderDetectionTestingFramework extends ProviderDetection {
private static final Ruleset defaultRuleset = Ruleset.JavaCryptographicArchitecture;
private static final String rootRulesDirectory = System.getProperty("user.dir")+File.separator+"src"+File.separator+"main"+File.separator+"resources";
private static final String defaultRulesDirectory = rootRulesDirectory+File.separator+defaultRuleset;
private static final String sootClassPath = System.getProperty("user.dir") + File.separator+"target"+File.separator+"test-classes";
/**
* This method is used to get the Soot classpath from `src/test/java`
* in order to run the JUnit test cases for Provider Detection
*/
public String getSootClassPath(){
//Assume target folder to be directly in user directory
File classPathDir = new File(sootClassPath);
if (!classPathDir.exists()){
throw new RuntimeException("Classpath for the test cases could not be found.");
}
return sootClassPath;
}
/**
* This method is used to setup Soot
*/
public void setupSoot(String sootClassPath, String mainClass) {
G.v().reset();
Options.v().set_whole_program(true);
Options.v().setPhaseOption("cg.cha", "on");
// Options.v().setPhaseOption("cg", "all-reachable:true");
Options.v().set_output_format(Options.output_format_none);
Options.v().set_no_bodies_for_excluded(true);
Options.v().set_allow_phantom_refs(true);
Options.v().set_keep_line_number(true);
Options.v().set_prepend_classpath(true);
Options.v().set_soot_classpath(sootClassPath);
SootClass c = Scene.v().forceResolve(mainClass, SootClass.BODIES);
if (c != null) {
c.setApplicationClass();
}
List<String> includeList = new LinkedList<String>();
includeList.add("java.lang.AbstractStringBuilder");
includeList.add("java.lang.Boolean");
includeList.add("java.lang.Byte");
includeList.add("java.lang.Class");
includeList.add("java.lang.Integer");
includeList.add("java.lang.Long");
includeList.add("java.lang.Object");
includeList.add("java.lang.String");
includeList.add("java.lang.StringCoding");
includeList.add("java.lang.StringIndexOutOfBoundsException");
Options.v().set_include(includeList);
Options.v().set_full_resolver(true);
Scene.v().loadNecessaryClasses();
}
public void analyze() {
Transform transform = new Transform("wjtp.ifds", createAnalysisTransformer());
PackManager.v().getPack("wjtp").add(transform);
PackManager.v().getPack("cg").apply();
PackManager.v().getPack("wjtp").apply();
}
private Transformer createAnalysisTransformer() {
return new SceneTransformer() {
@Override
protected void internalTransform(String phaseName, @SuppressWarnings("rawtypes") Map options) {
BoomerangPretransformer.v().reset();
BoomerangPretransformer.v().apply();
ObservableDynamicICFG observableDynamicICFG = new ObservableDynamicICFG(false);
setRulesDirectory(defaultRulesDirectory);
doAnalysis(observableDynamicICFG, rootRulesDirectory);
}
};
}
}
| 3,545 | 33.764706 | 151 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/tests/providerdetection/ProviderDetectionTests.java | package tests.providerdetection;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class ProviderDetectionTests {
// Checks if provider of type `java.security.Provider` is detected when given as a variable
@Test
public void providerDetectionTest1() {
ProviderDetectionTestingFramework providerDetection = new ProviderDetectionTestingFramework();
String sootClassPath = providerDetection.getSootClassPath();
String mainClass = "tests.providerdetection.examples.ProviderDetectionExample1";
providerDetection.setupSoot(sootClassPath, mainClass);
providerDetection.analyze();
String expected = "BouncyCastle-JCA";
String actual = providerDetection.getProvider();
assertEquals(expected, actual);
}
// Checks if provider of type `java.security.Provider` is detected when given directly
@Test
public void providerDetectionTest2() {
ProviderDetectionTestingFramework providerDetection = new ProviderDetectionTestingFramework();
String sootClassPath = providerDetection.getSootClassPath();
String mainClass = "tests.providerdetection.examples.ProviderDetectionExample2";
providerDetection.setupSoot(sootClassPath, mainClass);
providerDetection.analyze();
String expected = "BouncyCastle-JCA";
String actual = providerDetection.getProvider();
assertEquals(expected, actual);
}
// Checks if rules are correctly extracted, when provider is of type `java.security.Provider`,
// is given as a variable, and the rules for that provider exist
@Test
public void providerDetectionTest3() {
ProviderDetectionTestingFramework providerDetection = new ProviderDetectionTestingFramework();
String sootClassPath = providerDetection.getSootClassPath();
String mainClass = "tests.providerdetection.examples.ProviderDetectionExample1";
providerDetection.setupSoot(sootClassPath, mainClass);
providerDetection.analyze();
String rulesDirectory = providerDetection.getRulesDirectory();
assertEquals(true, rulesDirectory.endsWith("BouncyCastle-JCA"));
}
// Checks if rules are correctly extracted, when provider is of type `java.security.Provider`,
// is given directly, and the rules for that provider exist
@Test
public void providerDetectionTest4() {
ProviderDetectionTestingFramework providerDetection = new ProviderDetectionTestingFramework();
String sootClassPath = providerDetection.getSootClassPath();
String mainClass = "tests.providerdetection.examples.ProviderDetectionExample2";
providerDetection.setupSoot(sootClassPath, mainClass);
providerDetection.analyze();
String rulesDirectory = providerDetection.getRulesDirectory();
assertEquals(true, rulesDirectory.endsWith("BouncyCastle-JCA"));
}
// Checks if rules are correctly extracted, when provider is of type `java.security.Provider`,
// is given as a variable, and the rules for that provider exist
@Test
public void providerDetectionTest5() {
ProviderDetectionTestingFramework providerDetection = new ProviderDetectionTestingFramework();
String sootClassPath = providerDetection.getSootClassPath();
String mainClass = "tests.providerdetection.examples.ProviderDetectionExample3";
providerDetection.setupSoot(sootClassPath, mainClass);
providerDetection.analyze();
String rulesDirectory = providerDetection.getRulesDirectory();
assertEquals(true, rulesDirectory.endsWith("BouncyCastle-JCA"));
}
// Checks if rules are correctly extracted, when provider is of type `java.security.Provider`,
// is given directly, and the rules for that provider exist
@Test
public void providerDetectionTest6() {
ProviderDetectionTestingFramework providerDetection = new ProviderDetectionTestingFramework();
String sootClassPath = providerDetection.getSootClassPath();
String mainClass = "tests.providerdetection.examples.ProviderDetectionExample4";
providerDetection.setupSoot(sootClassPath, mainClass);
providerDetection.analyze();
String rulesDirectory = providerDetection.getRulesDirectory();
assertEquals(true, rulesDirectory.endsWith("BouncyCastle-JCA"));
}
// Checks if provider of type `java.lang.String` is detected when given as a variable
@Test
public void providerDetectionTest7() {
ProviderDetectionTestingFramework providerDetection = new ProviderDetectionTestingFramework();
String sootClassPath = providerDetection.getSootClassPath();
String mainClass = "tests.providerdetection.examples.ProviderDetectionExample5";
providerDetection.setupSoot(sootClassPath, mainClass);
providerDetection.analyze();
String expected = "BouncyCastle-JCA";
String actual = providerDetection.getProvider();
assertEquals(expected, actual);
}
// Checks if provider of type `java.lang.String` is detected when given directly
@Test
public void providerDetectionTest8() {
ProviderDetectionTestingFramework providerDetection = new ProviderDetectionTestingFramework();
String sootClassPath = providerDetection.getSootClassPath();
String mainClass = "tests.providerdetection.examples.ProviderDetectionExample6";
providerDetection.setupSoot(sootClassPath, mainClass);
providerDetection.analyze();
String expected = "BouncyCastle-JCA";
String actual = providerDetection.getProvider();
assertEquals(expected, actual);
}
// Checks if rules are correctly extracted, when provider is of type `java.lang.String`,
// is given as a variable, and the rules for that provider exist
@Test
public void providerDetectionTest9() {
ProviderDetectionTestingFramework providerDetection = new ProviderDetectionTestingFramework();
String sootClassPath = providerDetection.getSootClassPath();
String mainClass = "tests.providerdetection.examples.ProviderDetectionExample5";
providerDetection.setupSoot(sootClassPath, mainClass);
providerDetection.analyze();
String rulesDirectory = providerDetection.getRulesDirectory();
assertEquals(true, rulesDirectory.endsWith("BouncyCastle-JCA"));
}
// Checks if rules are correctly extracted, when provider is of type `java.lang.String`,
// is given directly, and the rules for that provider exist
@Test
public void providerDetectionTest10() {
ProviderDetectionTestingFramework providerDetection = new ProviderDetectionTestingFramework();
String sootClassPath = providerDetection.getSootClassPath();
String mainClass = "tests.providerdetection.examples.ProviderDetectionExample6";
providerDetection.setupSoot(sootClassPath, mainClass);
providerDetection.analyze();
String rulesDirectory = providerDetection.getRulesDirectory();
assertEquals(true, rulesDirectory.endsWith("BouncyCastle-JCA"));
}
// Checks if rules are correctly extracted, when provider is of type `java.lang.String`,
// is given as a variable, and the rules for that provider exist
@Test
public void providerDetectionTest11() {
ProviderDetectionTestingFramework providerDetection = new ProviderDetectionTestingFramework();
String sootClassPath = providerDetection.getSootClassPath();
String mainClass = "tests.providerdetection.examples.ProviderDetectionExample7";
providerDetection.setupSoot(sootClassPath, mainClass);
providerDetection.analyze();
String rulesDirectory = providerDetection.getRulesDirectory();
assertEquals(true, rulesDirectory.endsWith("BouncyCastle-JCA"));
}
// Checks if rules are correctly extracted, when provider is of type `java.lang.String`,
// is given directly, and the rules for that provider exist
@Test
public void providerDetectionTest12() {
ProviderDetectionTestingFramework providerDetection = new ProviderDetectionTestingFramework();
String sootClassPath = providerDetection.getSootClassPath();
String mainClass = "tests.providerdetection.examples.ProviderDetectionExample8";
providerDetection.setupSoot(sootClassPath, mainClass);
providerDetection.analyze();
String rulesDirectory = providerDetection.getRulesDirectory();
assertEquals(true, rulesDirectory.endsWith("BouncyCastle-JCA"));
}
// Checks if the default ruleset is chosen when provider of type `java.security.Provider`
// flows through TERNARY operators
@Test
public void providerDetectionTest13() {
ProviderDetectionTestingFramework providerDetection = new ProviderDetectionTestingFramework();
String sootClassPath = providerDetection.getSootClassPath();
String mainClass = "tests.providerdetection.examples.ProviderDetectionExample9";
providerDetection.setupSoot(sootClassPath, mainClass);
providerDetection.analyze();
String rulesDirectory = providerDetection.getRulesDirectory();
assertEquals(true, rulesDirectory.endsWith("JavaCryptographicArchitecture"));
}
// Checks if the default ruleset is chosen when provider of type `java.security.Provider`
// flows through IF-ELSE statements
@Test
public void providerDetectionTest14() {
ProviderDetectionTestingFramework providerDetection = new ProviderDetectionTestingFramework();
String sootClassPath = providerDetection.getSootClassPath();
String mainClass = "tests.providerdetection.examples.ProviderDetectionExample10";
providerDetection.setupSoot(sootClassPath, mainClass);
providerDetection.analyze();
String rulesDirectory = providerDetection.getRulesDirectory();
assertEquals(true, rulesDirectory.endsWith("JavaCryptographicArchitecture"));
}
// Checks if the default ruleset is chosen when provider of type `java.security.Provider`
// flows through SWITCH statements
@Test
public void providerDetectionTest15() {
ProviderDetectionTestingFramework providerDetection = new ProviderDetectionTestingFramework();
String sootClassPath = providerDetection.getSootClassPath();
String mainClass = "tests.providerdetection.examples.ProviderDetectionExample11";
providerDetection.setupSoot(sootClassPath, mainClass);
providerDetection.analyze();
String rulesDirectory = providerDetection.getRulesDirectory();
assertEquals(true, rulesDirectory.endsWith("JavaCryptographicArchitecture"));
}
// Checks if the default ruleset is chosen when provider of type `java.lang.String`
// flows through TERNARY operators
@Test
public void providerDetectionTest16() {
ProviderDetectionTestingFramework providerDetection = new ProviderDetectionTestingFramework();
String sootClassPath = providerDetection.getSootClassPath();
String mainClass = "tests.providerdetection.examples.ProviderDetectionExample12";
providerDetection.setupSoot(sootClassPath, mainClass);
providerDetection.analyze();
String rulesDirectory = providerDetection.getRulesDirectory();
assertEquals(true, rulesDirectory.endsWith("JavaCryptographicArchitecture"));
}
// Checks if the default ruleset is chosen when provider of type `java.lang.String`
// flows through IF-ELSE statements
@Test
public void providerDetectionTest17() {
ProviderDetectionTestingFramework providerDetection = new ProviderDetectionTestingFramework();
String sootClassPath = providerDetection.getSootClassPath();
String mainClass = "tests.providerdetection.examples.ProviderDetectionExample13";
providerDetection.setupSoot(sootClassPath, mainClass);
providerDetection.analyze();
String rulesDirectory = providerDetection.getRulesDirectory();
assertEquals(true, rulesDirectory.endsWith("JavaCryptographicArchitecture"));
}
// Checks if the default ruleset is chosen when provider of type `java.lang.String`
// flows through SWITCH statements
@Test
public void providerDetectionTest18() {
ProviderDetectionTestingFramework providerDetection = new ProviderDetectionTestingFramework();
String sootClassPath = providerDetection.getSootClassPath();
String mainClass = "tests.providerdetection.examples.ProviderDetectionExample14";
providerDetection.setupSoot(sootClassPath, mainClass);
providerDetection.analyze();
String rulesDirectory = providerDetection.getRulesDirectory();
assertEquals(true, rulesDirectory.endsWith("JavaCryptographicArchitecture"));
}
}
| 11,902 | 44.258555 | 96 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/tests/providerdetection/examples/ProviderDetectionExample1.java | package tests.providerdetection.examples;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Provider;
import javax.crypto.KeyGenerator;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
public class ProviderDetectionExample1 {
public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchProviderException {
Provider p1 = new BouncyCastleProvider();
KeyGenerator keygenerator = KeyGenerator.getInstance("AES", p1);
keygenerator.generateKey();
}
}
| 550 | 28 | 98 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/tests/providerdetection/examples/ProviderDetectionExample10.java | package tests.providerdetection.examples;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Provider;
import java.util.Random;
import javax.crypto.KeyGenerator;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.pqc.jcajce.provider.BouncyCastlePQCProvider;
public class ProviderDetectionExample10 {
public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchProviderException {
Random rand = new Random();
int n = rand.nextInt(2);
Provider p1 = new BouncyCastleProvider();
if(n%2==0) {
p1 = new BouncyCastleProvider();
}
else {
p1 = new BouncyCastlePQCProvider();
}
KeyGenerator keygenerator = KeyGenerator.getInstance("AES", p1);
keygenerator.generateKey();
}
}
| 819 | 23.848485 | 98 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/tests/providerdetection/examples/ProviderDetectionExample11.java | package tests.providerdetection.examples;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Provider;
import java.util.Random;
import javax.crypto.KeyGenerator;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.pqc.jcajce.provider.BouncyCastlePQCProvider;
public class ProviderDetectionExample11 {
public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchProviderException {
Random rand = new Random();
int n = rand.nextInt(2);
Provider p1 = new BouncyCastleProvider();
switch(n) {
case 0:
p1 = new BouncyCastleProvider();
break;
case 1:
p1 = new BouncyCastlePQCProvider();
break;
case 2:
p1 = new BouncyCastleProvider();
break;
default:
p1 = new BouncyCastlePQCProvider();
break;
}
KeyGenerator keygenerator = KeyGenerator.getInstance("AES", p1);
keygenerator.generateKey();
}
}
| 962 | 22.487805 | 98 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/tests/providerdetection/examples/ProviderDetectionExample12.java | package tests.providerdetection.examples;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.Random;
import javax.crypto.KeyGenerator;
public class ProviderDetectionExample12 {
public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchProviderException {
Random rand = new Random();
int n = rand.nextInt(2);
String pString1 = "BC";
String pString2 = "BCPQC";
KeyGenerator keygenerator = KeyGenerator.getInstance("AES", ((n%2==0) ? pString1 : pString2));
keygenerator.generateKey();
}
}
| 590 | 24.695652 | 98 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/tests/providerdetection/examples/ProviderDetectionExample13.java | package tests.providerdetection.examples;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.Random;
import javax.crypto.KeyGenerator;
public class ProviderDetectionExample13 {
public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchProviderException {
Random rand = new Random();
int n = rand.nextInt(2);
String pString1 = "BC";
if(n%2==0) {
pString1 = "BC";
}
else {
pString1 = "BCPQC";
}
KeyGenerator keygenerator = KeyGenerator.getInstance("AES", pString1);
keygenerator.generateKey();
}
}
| 615 | 20.241379 | 98 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/tests/providerdetection/examples/ProviderDetectionExample14.java | package tests.providerdetection.examples;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.Random;
import javax.crypto.KeyGenerator;
public class ProviderDetectionExample14 {
public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchProviderException {
Random rand = new Random();
int n = rand.nextInt(2);
String pString1 = "BC";
switch(n) {
case 0:
pString1="BC";
break;
case 1:
pString1="BCPQC";
break;
case 2:
pString1="BC";
break;
default:
pString1="BCPQC";
break;
}
KeyGenerator keygenerator = KeyGenerator.getInstance("AES", pString1);
keygenerator.generateKey();
}
}
| 718 | 18.432432 | 98 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/tests/providerdetection/examples/ProviderDetectionExample2.java | package tests.providerdetection.examples;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import javax.crypto.KeyGenerator;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
public class ProviderDetectionExample2 {
public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchProviderException {
KeyGenerator keygenerator = KeyGenerator.getInstance("AES", new BouncyCastleProvider());
keygenerator.generateKey();
}
}
| 499 | 28.411765 | 98 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/tests/providerdetection/examples/ProviderDetectionExample3.java | package tests.providerdetection.examples;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Provider;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
public class ProviderDetectionExample3 {
public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchProviderException {
Provider p1 = new BouncyCastleProvider();
MessageDigest md = MessageDigest.getInstance("AES", p1);
byte[] input = "message".getBytes();
md.digest(input);
}
}
| 573 | 27.7 | 98 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/tests/providerdetection/examples/ProviderDetectionExample4.java | package tests.providerdetection.examples;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
public class ProviderDetectionExample4 {
public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchProviderException {
MessageDigest md = MessageDigest.getInstance("AES", new BouncyCastleProvider());
byte[] input = "message".getBytes();
md.digest(input);
}
}
| 522 | 28.055556 | 98 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/tests/providerdetection/examples/ProviderDetectionExample5.java | package tests.providerdetection.examples;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import javax.crypto.KeyGenerator;
public class ProviderDetectionExample5 {
public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchProviderException {
String p1 = "BC";
KeyGenerator keygenerator = KeyGenerator.getInstance("AES", p1);
keygenerator.generateKey();
}
}
| 435 | 26.25 | 98 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/tests/providerdetection/examples/ProviderDetectionExample6.java | package tests.providerdetection.examples;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import javax.crypto.KeyGenerator;
public class ProviderDetectionExample6 {
public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchProviderException {
KeyGenerator keygenerator = KeyGenerator.getInstance("AES", "BC");
keygenerator.generateKey();
}
}
| 418 | 25.1875 | 98 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/tests/providerdetection/examples/ProviderDetectionExample7.java | package tests.providerdetection.examples;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
public class ProviderDetectionExample7 {
public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchProviderException {
String p1 = "BC";
MessageDigest md = MessageDigest.getInstance("AES", p1);
byte[] input = "message".getBytes();
md.digest(input);
}
}
| 458 | 26 | 98 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/tests/providerdetection/examples/ProviderDetectionExample8.java | package tests.providerdetection.examples;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
public class ProviderDetectionExample8 {
public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchProviderException {
MessageDigest md = MessageDigest.getInstance("AES", "BC");
byte[] input = "message".getBytes();
md.digest(input);
}
}
| 440 | 26.5625 | 98 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysis/src/test/java/tests/providerdetection/examples/ProviderDetectionExample9.java | package tests.providerdetection.examples;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Provider;
import java.util.Random;
import javax.crypto.KeyGenerator;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.pqc.jcajce.provider.BouncyCastlePQCProvider;
public class ProviderDetectionExample9 {
public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchProviderException {
Random rand = new Random();
int n = rand.nextInt(2);
Provider p1 = new BouncyCastleProvider();
Provider p2 = new BouncyCastlePQCProvider();
KeyGenerator keygenerator = KeyGenerator.getInstance("AES", ((n%2==0) ? p1 : p2));
keygenerator.generateKey();
}
}
| 773 | 27.666667 | 98 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/BCAsymmetricCipherExamples/src/main/java/constants/Constants.java | package constants;
import java.math.BigInteger;
public class Constants {
public static BigInteger publicExponent = new BigInteger("10001", 16);
public static int strength = 768;
public static int certainty = 25;
public static BigInteger mod = new BigInteger("b259d2d6e627a768c94be36164c2d9fc79d97aab9253140e5bf17751197731d6f7540d2509e7b9ffee0a70a6e26d56e92d2edd7f85aba85600b69089f35f6bdbf3c298e05842535d9f064e6b0391cb7d306e0a2d20c4dfb4e7b49a9640bdea26c10ad69c3f05007ce2513cee44cfe01998e62b6c3637d3fc0391079b26ee36d5", 16);;
public static BigInteger pubExp = new BigInteger("11", 16);
public static BigInteger privExp = new BigInteger("92e08f83cc9920746989ca5034dcb384a094fb9c5a6288fcc4304424ab8f56388f72652d8fafc65a4b9020896f2cde297080f2a540e7b7ce5af0b3446e1258d1dd7f245cf54124b4c6e17da21b90a0ebd22605e6f45c9f136d7a13eaac1c0f7487de8bd6d924972408ebb58af71e76fd7b012a8d0e165f3ae2e5077a8648e619", 16);
// public static BigInteger modulus = new BigInteger(1, Hex.decode("CDCBDABBF93BE8E8294E32B055256BBD0397735189BF75816341BB0D488D05D627991221DF7D59835C76A4BB4808ADEEB779E7794504E956ADC2A661B46904CDC71337DD29DDDD454124EF79CFDD7BC2C21952573CEFBA485CC38C6BD2428809B5A31A898A6B5648CAA4ED678D9743B589134B7187478996300EDBA16271A861"));
// public static BigInteger pubExp = new BigInteger(1, Hex.decode("010001"));
// public static BigInteger privExp = new BigInteger(1, Hex.decode("4BA6432AD42C74AA5AFCB6DF60FD57846CBC909489994ABD9C59FE439CC6D23D6DE2F3EA65B8335E796FD7904CA37C248367997257AFBD82B26F1A30525C447A236C65E6ADE43ECAAF7283584B2570FA07B340D9C9380D88EAACFFAEEFE7F472DBC9735C3FF3A3211E8A6BBFD94456B6A33C17A2C4EC18CE6335150548ED126D"));
public static BigInteger p = new BigInteger("f75e80839b9b9379f1cf1128f321639757dba514642c206bbbd99f9a4846208b3e93fbbe5e0527cc59b1d4b929d9555853004c7c8b30ee6a213c3d1bb7415d03", 16);
public static BigInteger q = new BigInteger("b892d9ebdbfc37e397256dd8a5d3123534d1f03726284743ddc6be3a709edb696fc40c7d902ed804c6eee730eee3d5b20bf6bd8d87a296813c87d3b3cc9d7947", 16);
public static BigInteger pExp = new BigInteger("1d1a2d3ca8e52068b3094d501c9a842fec37f54db16e9a67070a8b3f53cc03d4257ad252a1a640eadd603724d7bf3737914b544ae332eedf4f34436cac25ceb5", 16);
public static BigInteger qExp = new BigInteger("6c929e4e81672fef49d9c825163fec97c4b7ba7acb26c0824638ac22605d7201c94625770984f78a56e6e25904fe7db407099cad9b14588841b94f5ab498dded", 16);
public static BigInteger crtCoef = new BigInteger("dae7651ee69ad1d081ec5e7188ae126f6004ff39556bde90e0b870962fa7b926d070686d8244fe5a9aa709a95686a104614834b0ada4b10f53197a5cb4c97339", 16);
}
| 2,598 | 107.291667 | 331 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/BCAsymmetricCipherExamples/src/main/java/crypto/RSAEngineTest.java | package crypto;
import org.bouncycastle.crypto.AsymmetricBlockCipher;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.bouncycastle.crypto.engines.RSAEngine;
import org.bouncycastle.crypto.params.RSAKeyParameters;
import org.bouncycastle.crypto.params.RSAPrivateCrtKeyParameters;
import org.bouncycastle.util.encoders.Hex;
import constants.Constants;
public class RSAEngineTest {
public void testEncryptOne() throws InvalidCipherTextException {
String edgeInput = "ff6f77206973207468652074696d6520666f7220616c6c20676f6f64206d656e";
byte[] data = Hex.decode(edgeInput);
RSAKeyParameters pubParameters = new RSAKeyParameters(false, Constants.mod, Constants.pubExp);
AsymmetricBlockCipher eng = new RSAEngine();
eng.init(true, pubParameters);
byte[] cipherText = eng.processBlock(data, 0, data.length);
}
public void testEncryptTwo() throws InvalidCipherTextException {
String edgeInput = "ff6f77206973207468652074696d6520666f7220616c6c20676f6f64206d656e";
byte[] data = Hex.decode(edgeInput);
RSAKeyParameters pubParameters = new RSAKeyParameters(false, Constants.mod, Constants.pubExp);
AsymmetricBlockCipher eng = new RSAEngine();
// missing init()
byte[] cipherText = eng.processBlock(data, 0, data.length);
}
public void testDecryptOne(byte[] data) throws InvalidCipherTextException {
RSAKeyParameters privParameters = new RSAPrivateCrtKeyParameters(Constants.mod, Constants.pubExp, Constants.privExp, Constants.p, Constants.q, Constants.pExp, Constants.qExp, Constants.crtCoef);
AsymmetricBlockCipher eng = new RSAEngine();
eng.init(false, privParameters);
byte[] plainText = eng.processBlock(data, 0, data.length);
}
public void testDecryptTwo(byte[] data) throws InvalidCipherTextException {
RSAKeyParameters privParameters = new RSAPrivateCrtKeyParameters(Constants.mod, Constants.pubExp, Constants.privExp, Constants.p, Constants.q, Constants.pExp, Constants.qExp, Constants.crtCoef);
AsymmetricBlockCipher eng = new RSAEngine();
// missing init()
byte[] plainText = eng.processBlock(data, 0, data.length);
}
}
| 2,157 | 45.913043 | 202 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/BCAsymmetricCipherExamples/src/main/java/generators/RSAKeyPairGeneratorTest.java | package generators;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import org.bouncycastle.crypto.KeyGenerationParameters;
import org.bouncycastle.crypto.generators.RSAKeyPairGenerator;
import org.bouncycastle.crypto.params.RSAKeyGenerationParameters;
import constants.Constants;
public class RSAKeyPairGeneratorTest {
public void testOne() throws NoSuchAlgorithmException {
RSAKeyPairGenerator generator = new RSAKeyPairGenerator();
KeyGenerationParameters params = new RSAKeyGenerationParameters(
Constants.publicExponent,
SecureRandom.getInstance("SHA1PRNG"),
Constants.strength,
Constants.certainty
);
generator.init(params);;
generator.generateKeyPair();
}
public void testTwo() {
RSAKeyPairGenerator generator = new RSAKeyPairGenerator();
generator.init(null);
generator.generateKeyPair();
}
public void testThree() {
RSAKeyPairGenerator generator = new RSAKeyPairGenerator();
// missing init()
generator.generateKeyPair();
}
public void testFour() throws NoSuchAlgorithmException {
RSAKeyPairGenerator generator = new RSAKeyPairGenerator();
KeyGenerationParameters params = new RSAKeyGenerationParameters(
Constants.publicExponent,
SecureRandom.getInstance("SHA1PRNG"),
Constants.strength,
Constants.certainty
);
generator.init(params);;
// missing generateKeyPair()
}
}
| 1,400 | 27.02 | 66 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/BCAsymmetricCipherExamples/src/main/java/params/ParametersWithRandomTest.java | package params;
import org.bouncycastle.crypto.params.ParametersWithRandom;
import org.bouncycastle.crypto.params.RSAKeyParameters;
import constants.Constants;
@SuppressWarnings("unused")
public class ParametersWithRandomTest {
public void testOne() {
RSAKeyParameters pubKey = new RSAKeyParameters(false, Constants.mod, Constants.pubExp);
ParametersWithRandom pubKeyRand = new ParametersWithRandom(pubKey);
}
public void testTwo() {
RSAKeyParameters pubKey = new RSAKeyParameters(false, Constants.mod, Constants.pubExp);
ParametersWithRandom pubKeyRand = new ParametersWithRandom(pubKey, null);
}
}
| 621 | 27.272727 | 89 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/BCAsymmetricCipherExamples/src/main/java/params/RSAKeyGenerationParametersTest.java | package params;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import org.bouncycastle.crypto.params.RSAKeyGenerationParameters;
import constants.Constants;
@SuppressWarnings("unused")
public class RSAKeyGenerationParametersTest {
public void testOne() throws NoSuchAlgorithmException {
RSAKeyGenerationParameters params = new RSAKeyGenerationParameters(
Constants.publicExponent,
SecureRandom.getInstance("SHA1PRNG"),
Constants.strength,
Constants.certainty);
}
}
| 530 | 22.086957 | 69 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/BCAsymmetricCipherExamples/src/main/java/params/RSAKeyParametersTest.java | package params;
import org.bouncycastle.crypto.params.RSAKeyParameters;
import constants.Constants;
@SuppressWarnings("unused")
public class RSAKeyParametersTest {
public void testOne() {
RSAKeyParameters params = new RSAKeyParameters(
true,
Constants.mod,
Constants.privExp);
}
public void testTwo() {
RSAKeyParameters params = new RSAKeyParameters(
false,
Constants.mod,
Constants.pubExp);
}
}
| 437 | 17.25 | 55 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/BCAsymmetricCipherExamples/src/main/java/params/RSAPrivateCrtKeyParametersTest.java | package params;
import org.bouncycastle.crypto.params.RSAKeyParameters;
import org.bouncycastle.crypto.params.RSAPrivateCrtKeyParameters;
import constants.Constants;
//@SuppressWarnings("unused")
public class RSAPrivateCrtKeyParametersTest {
public void testOne() {
RSAKeyParameters privParameters = new RSAPrivateCrtKeyParameters(
Constants.mod,
Constants.pubExp,
Constants.privExp,
Constants.p,
Constants.q,
Constants.pExp,
Constants.qExp,
Constants.crtCoef);
}
}
| 513 | 21.347826 | 67 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/BCAsymmetricCipherExamples/src/main/java/rsa_misuse/RSATest.java | package rsa_misuse;
import java.math.BigInteger;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.Security;
import org.bouncycastle.crypto.AsymmetricBlockCipher;
import org.bouncycastle.crypto.AsymmetricCipherKeyPair;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.bouncycastle.crypto.engines.RSAEngine;
import org.bouncycastle.crypto.generators.RSAKeyPairGenerator;
import org.bouncycastle.crypto.params.AsymmetricKeyParameter;
import org.bouncycastle.crypto.params.RSAKeyGenerationParameters;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
public class RSATest {
public static String getHexString(byte[] b) throws Exception {
String result = "";
for (int i=0; i < b.length; i++) {
result +=
Integer.toString( ( b[i] & 0xff ) + 0x100, 16).substring( 1 );
}
return result;
}
public static byte[] hexStringToByteArray(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i+1), 16));
}
return data;
}
public static AsymmetricCipherKeyPair GenerateKeys() throws NoSuchAlgorithmException{
RSAKeyPairGenerator generator = new RSAKeyPairGenerator();
generator.init(new RSAKeyGenerationParameters
(
new BigInteger("10001", 16),//publicExponent
SecureRandom.getInstance("SHA1PRNG"),//pseudorandom number generator
4096,//strength
80//certainty
));
return generator.generateKeyPair();
}
public static String Encrypt(byte[] data, AsymmetricKeyParameter publicKey) throws Exception{
RSAEngine engine = new RSAEngine();
// engine.init(true, publicKey); // init() is skipped
byte[] hexEncodedCipher = engine.processBlock(data, 0, data.length);
return getHexString(hexEncodedCipher);
}
public static String Decrypt(String encrypted, AsymmetricKeyParameter privateKey) throws InvalidCipherTextException{
AsymmetricBlockCipher engine = new RSAEngine();
engine.init(false, privateKey);
byte[] encryptedBytes = hexStringToByteArray(encrypted);
byte[] hexEncodedCipher = engine.processBlock(encryptedBytes, 0, encryptedBytes.length);
return new String (hexEncodedCipher);
}
public static void main(String[] args) throws Exception {
AsymmetricCipherKeyPair keyPair = GenerateKeys();
String plainMessage = "plaintext";
// Encryption
String encryptedMessage = Encrypt(plainMessage.getBytes("UTF-8"), keyPair.getPublic());
// Decryption
String decryptedMessage = Decrypt(encryptedMessage, keyPair.getPrivate());
}
}
| 2,723 | 30.674419 | 117 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/BCAsymmetricCipherExamples/src/main/java/rsa_nomisuse/RSATest.java | package rsa_nomisuse;
import java.math.BigInteger;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.Security;
import org.bouncycastle.crypto.AsymmetricBlockCipher;
import org.bouncycastle.crypto.AsymmetricCipherKeyPair;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.bouncycastle.crypto.engines.RSAEngine;
import org.bouncycastle.crypto.generators.RSAKeyPairGenerator;
import org.bouncycastle.crypto.params.AsymmetricKeyParameter;
import org.bouncycastle.crypto.params.RSAKeyGenerationParameters;
public class RSATest {
public static String getHexString(byte[] b) throws Exception {
String result = "";
for (int i=0; i < b.length; i++) {
result +=
Integer.toString( ( b[i] & 0xff ) + 0x100, 16).substring( 1 );
}
return result;
}
public static byte[] hexStringToByteArray(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i+1), 16));
}
return data;
}
public static AsymmetricCipherKeyPair GenerateKeys() throws NoSuchAlgorithmException{
RSAKeyPairGenerator generator = new RSAKeyPairGenerator();
generator.init(new RSAKeyGenerationParameters
(
new BigInteger("10001", 16),//publicExponent
SecureRandom.getInstance("SHA1PRNG"),//pseudorandom number generator
4096,//strength
80//certainty
));
return generator.generateKeyPair();
}
public static String Encrypt(byte[] data, AsymmetricKeyParameter publicKey) throws Exception{
RSAEngine engine = new RSAEngine();
engine.init(true, publicKey); //true for encryption
byte[] hexEncodedCipher = engine.processBlock(data, 0, data.length);
return getHexString(hexEncodedCipher);
}
public static String Decrypt(String encrypted, AsymmetricKeyParameter privateKey) throws InvalidCipherTextException{
AsymmetricBlockCipher engine = new RSAEngine();
engine.init(false, privateKey); //false for decryption
byte[] encryptedBytes = hexStringToByteArray(encrypted);
byte[] hexEncodedCipher = engine.processBlock(encryptedBytes, 0, encryptedBytes.length);
return new String (hexEncodedCipher);
}
public static void main(String[] args) throws Exception {
AsymmetricCipherKeyPair keyPair = GenerateKeys();
String plainMessage = "plaintext";
// Encryption
String encryptedMessage = Encrypt(plainMessage.getBytes("UTF-8"), keyPair.getPublic());
// Decryption
String decryptedMessage = Decrypt(encryptedMessage, keyPair.getPrivate());
}
}
| 2,684 | 30.588235 | 117 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/BCDigestExamples/src/main/java/fabric_api_archieve/Crypto.java | package fabric_api_archieve;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import org.bouncycastle.asn1.ASN1Integer;
import org.bouncycastle.asn1.DERSequenceGenerator;
import org.bouncycastle.asn1.sec.SECNamedCurves;
import org.bouncycastle.asn1.x9.X9ECParameters;
import org.bouncycastle.crypto.digests.SHA256Digest;
import org.bouncycastle.crypto.params.ECDomainParameters;
import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
import org.bouncycastle.crypto.signers.ECDSASigner;
import org.bouncycastle.crypto.signers.HMacDSAKCalculator;
public class Crypto {
static final X9ECParameters curve = SECNamedCurves.getByName("secp256k1");
static final ECDomainParameters domain = new ECDomainParameters(curve.getCurve(), curve.getG(), curve.getN(), curve.getH());
static final BigInteger HALF_CURVE_ORDER = curve.getN().shiftRight(1);
public byte[] sign(byte[] hash, byte[] privateKey) {
ECDSASigner signer = new ECDSASigner(new HMacDSAKCalculator(new SHA256Digest()));
signer.init(true, new ECPrivateKeyParameters(new BigInteger(privateKey), domain));
BigInteger[] signature = signer.generateSignature(hash);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
DERSequenceGenerator seq = new DERSequenceGenerator(baos);
seq.addObject(new ASN1Integer(signature[0]));
seq.addObject(new ASN1Integer(toCanonicalS(signature[1])));
seq.close();
return baos.toByteArray();
} catch (IOException e) {
return new byte[0];
}
}
private BigInteger toCanonicalS(BigInteger s) {
if (s.compareTo(HALF_CURVE_ORDER) <= 0) {
return s;
} else {
return curve.getN().subtract(s);
}
}
}
| 1,732 | 35.87234 | 125 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/BCDigestExamples/src/main/java/inflatable_donkey/KeyBlobCurve25519Unwrap.java | package inflatable_donkey;
import java.util.Optional;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.bouncycastle.crypto.digests.SHA256Digest;
import org.bouncycastle.crypto.engines.AESFastEngine;
import org.bouncycastle.crypto.engines.RFC3394WrapEngine;
import org.bouncycastle.crypto.params.KeyParameter;
@SuppressWarnings("deprecation")
public class KeyBlobCurve25519Unwrap {
public static Optional<byte[]> curve25519Unwrap(
byte[] myPublicKey,
byte[] myPrivateKey,
byte[] otherPublicKey,
byte[] wrappedKey) {
SHA256Digest sha256 = new SHA256Digest();
byte[] shared = new byte[32];
// Stripped down NIST SP 800-56A KDF.
byte[] counter = new byte[]{0x00, 0x00, 0x00, 0x01};
byte[] hash = new byte[sha256.getDigestSize()];
sha256.reset();
sha256.update(counter, 0, counter.length);
sha256.update(shared, 0, shared.length);
sha256.update(otherPublicKey, 0, otherPublicKey.length);
sha256.update(myPublicKey, 0, myPublicKey.length);
sha256.doFinal(hash, 0);
return unwrapAES(hash, wrappedKey);
}
public static Optional<byte[]> unwrapAES(byte[] keyEncryptionKey, byte[] wrappedKey) {
try {
RFC3394WrapEngine engine = new RFC3394WrapEngine(new AESFastEngine());
engine.init(false, new KeyParameter(keyEncryptionKey));
return Optional.of(engine.unwrap(wrappedKey, 0, wrappedKey.length));
} catch (InvalidCipherTextException ex) {
return Optional.empty();
}
}
public static byte[] wrapAES(byte[] keyEncryptionKey, byte[] unwrappedKey) {
RFC3394WrapEngine engine = new RFC3394WrapEngine(new AESFastEngine());
engine.init(true, new KeyParameter(keyEncryptionKey));
return engine.wrap(unwrappedKey, 0, unwrappedKey.length);
}
}
| 1,722 | 29.767857 | 87 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/BCDigestExamples/src/main/java/ipack/JPAKEExample.java | package ipack;
import java.math.BigInteger;
import org.bouncycastle.crypto.digests.SHA256Digest;
public class JPAKEExample {
private static BigInteger deriveSessionKey(BigInteger keyingMaterial)
{
/*
* You should use a secure key derivation function (KDF) to derive the session key.
*
* For the purposes of this example, I'm just going to use a hash of the keying material.
*/
SHA256Digest digest = new SHA256Digest();
byte[] keyByteArray = keyingMaterial.toByteArray();
byte[] output = new byte[digest.getDigestSize()];
digest.update(keyByteArray, 0, keyByteArray.length);
digest.doFinal(output, 0);
return new BigInteger(output);
}
}
| 676 | 22.344828 | 91 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/BCDigestExamples/src/main/java/pattern/DigestTest.java | package pattern;
import java.io.File;
import java.io.UnsupportedEncodingException;
import org.bouncycastle.crypto.Digest;
import org.bouncycastle.crypto.digests.SHA256Digest;
import org.bouncycastle.crypto.digests.SHA512Digest;
public class DigestTest {
public void digestDefaultUsage() throws UnsupportedEncodingException {
SHA256Digest digest = new SHA256Digest();
final byte[] input = "input".getBytes("UTF-8");
digest.update(input, 0, input.length);
byte[] resBuf = new byte[digest.getDigestSize()];
digest.doFinal(resBuf, 0);
}
public void digestWithMultipleUpdates() throws UnsupportedEncodingException {
Digest digest = new SHA256Digest();
final String[] input = { "input1", "input2", "input3", "input4" };
int i = 0;
while (i < input.length) {
digest.update(input[i].getBytes("UTF-8"), 0, input[i].length());
}
byte[] resBuf = new byte[digest.getDigestSize()];
digest.doFinal(resBuf, 0);
}
public void digestWithoutUpdate() throws UnsupportedEncodingException {
SHA256Digest digest = new SHA256Digest();
final byte[] input = "input".getBytes("UTF-8");
byte[] resBuf = new byte[digest.getDigestSize()];
digest.doFinal(resBuf, 0);
}
public void multipleDigests() throws UnsupportedEncodingException {
Digest digest = new SHA256Digest();
final byte[] input1 = "input1".getBytes("UTF-8");
final byte[] input2 = "input2".getBytes("UTF-8");
digest.update(input1, 0, input1.length);
byte[] resBuf1 = new byte[digest.getDigestSize()];
digest.doFinal(resBuf1, 0);
digest = new SHA512Digest();
digest.update(input2, 0, input2.length);
byte[] resBuf2 = new byte[digest.getDigestSize()];
digest.doFinal(resBuf2, 0);
}
public void digestWithReset() throws UnsupportedEncodingException {
SHA256Digest digest = new SHA256Digest();
final byte[] input = "input".getBytes("UTF-8");
final byte[] input2 = "input2".getBytes("UTF-8");
digest.update(input, 0, input.length);
byte[] resBuf = new byte[digest.getDigestSize()];
digest.doFinal(resBuf, 0);
digest.reset();
digest.update(input2, 0, input2.length);
digest.doFinal(resBuf, 0);
}
}
| 2,128 | 30.776119 | 78 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/BCDigestExamples/src/main/java/pluotsorbet/BouncyCastleSHA256.java | package pluotsorbet;
import org.bouncycastle.crypto.digests.SHA256Digest;
public class BouncyCastleSHA256 {
// Try to mimic a popular midlet that commonly does around
// 170 update calls on 4096 bytes at a time.
private static final int UPDATES = 170;
public void TestSHA256DigestOne() {
byte[] digest = new byte[4096];
for (int i = 0; i < digest.length; i++) {
digest[i] = (byte)i;
}
long start = System.currentTimeMillis();
for (int i = 0; i < 20; i++) {
SHA256Digest digester = new SHA256Digest();
byte[] retValue = new byte[digester.getDigestSize()];
for (int j = 0; j < UPDATES; j++) {
digester.update(digest, 0, digest.length);
}
digester.doFinal(retValue, 0);
}
long time = System.currentTimeMillis() - start;
System.out.println("BouncyCastleSHA256: " + time);
}
private static final String[] messages = {
"",
"a",
"abc",
"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
"message digest",
"secure hash algorithm"
};
public void testSHA256DigestTwo() {
SHA256Digest md = new SHA256Digest();
byte[] retValue = new byte[md.getDigestSize()];
for (int i = 0; i < messages.length; i++) {
byte[] bytes = messages[i].getBytes();
md.update(bytes, 0, bytes.length);
md.doFinal(retValue, 0);
}
for (int i = 0; i < 1000000; i++) {
md.update((byte)'a');
}
md.doFinal(retValue, 0);
}
}
| 1,557 | 27.327273 | 68 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/BCDigestExamples/src/main/java/ximix/PackedBallotTableBuilder.java | package ximix;
import java.math.BigInteger;
import java.util.Map;
import org.bouncycastle.crypto.digests.SHA256Digest;
import org.bouncycastle.crypto.params.ECDomainParameters;
import org.bouncycastle.math.ec.ECPoint;
public class PackedBallotTableBuilder {
// replaced with dummy values
private final byte[] seed = new byte[32];
private final ECDomainParameters domainParameters = new ECDomainParameters(null, null, null);
private final Map<ECPoint, byte[]> packMap = null;
public ECPoint generatePackPoint(SHA256Digest digest, byte[] ballot, byte[] hash)
{
BigInteger element;
ECPoint point;
do
{
digest.update(seed, 0, seed.length);
for (int b = 0; b != ballot.length; b++)
{
digest.update(ballot[b]);
}
digest.doFinal(hash, 0);
digest.update(hash, 0, hash.length);
element = new BigInteger(1, hash).mod(domainParameters.getN());
point = domainParameters.getG().multiply(element).normalize();
}
while (element.equals(BigInteger.ZERO) || packMap.containsKey(point));
return point;
}
}
| 1,125 | 26.463415 | 94 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/BCEllipticCurveExamples/src/main/java/constants/Constants.java | package constants;
import java.math.BigInteger;
import org.bouncycastle.crypto.params.ECDomainParameters;
import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
import org.bouncycastle.crypto.params.ECPublicKeyParameters;
import org.bouncycastle.math.ec.ECConstants;
import org.bouncycastle.math.ec.ECCurve;
import org.bouncycastle.util.encoders.Hex;
public class Constants {
public static BigInteger n = new BigInteger("62771017353866");
public static ECCurve.Fp curve = new ECCurve.Fp(
new BigInteger("2343"),
new BigInteger("2343"),
new BigInteger("2343"),
n, ECConstants.ONE);
public static ECDomainParameters params = new ECDomainParameters(
curve,
curve.decodePoint(Hex.decode("03188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012")), // G
n);
public static ECPublicKeyParameters pubKeyValid = new ECPublicKeyParameters(
curve.decodePoint(Hex.decode("0262b12d")), // Q
params);
public static ECPrivateKeyParameters priKey = new ECPrivateKeyParameters(
new BigInteger("6510567709"), // d
params);
}
| 1,161 | 31.277778 | 101 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/BCEllipticCurveExamples/src/main/java/crypto/ECElGamalDecryptorTest.java | package crypto;
import org.bouncycastle.crypto.ec.ECElGamalDecryptor;
import org.bouncycastle.crypto.ec.ECPair;
import org.bouncycastle.math.ec.ECPoint;
import org.bouncycastle.util.encoders.Hex;
import constants.Constants;
@SuppressWarnings("unused")
public class ECElGamalDecryptorTest {
public void testOne(String point) {
ECElGamalDecryptor decryptor = new ECElGamalDecryptor();
decryptor.init(Constants.priKey);
ECPair pair = new ECPair(Constants.curve.decodePoint(Hex.decode(point)), Constants.curve.decodePoint(Hex.decode(point)));
ECPoint plainText = decryptor.decrypt(pair);
}
public void testTwo(String point) {
ECElGamalDecryptor decryptor = new ECElGamalDecryptor();
decryptor.init(null);
ECPair pair = new ECPair(Constants.curve.decodePoint(Hex.decode(point)), Constants.curve.decodePoint(Hex.decode(point)));
ECPoint plainText = decryptor.decrypt(pair);
}
public void testThree() {
ECElGamalDecryptor decryptor = new ECElGamalDecryptor();
decryptor.init(Constants.priKey);
ECPair pair2 = new ECPair(null, null);
ECPoint plainText = decryptor.decrypt(pair2);
}
public void testFour() {
ECElGamalDecryptor decryptor = new ECElGamalDecryptor();
ECPair pair2 = new ECPair(null, null);
ECPoint plainText = decryptor.decrypt(pair2);
}
}
| 1,381 | 33.55 | 129 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/BCEllipticCurveExamples/src/main/java/crypto/ECElGamalEncryptorTest.java | package crypto;
import java.security.SecureRandom;
import org.bouncycastle.crypto.ec.ECElGamalEncryptor;
import org.bouncycastle.crypto.ec.ECPair;
import org.bouncycastle.crypto.params.ECDomainParameters;
import org.bouncycastle.crypto.params.ECPublicKeyParameters;
import org.bouncycastle.crypto.params.ParametersWithRandom;
import org.bouncycastle.math.ec.ECPoint;
import org.bouncycastle.util.encoders.Hex;
import constants.Constants;
@SuppressWarnings("unused")
public class ECElGamalEncryptorTest {
public void testOne() {
ECPoint data = Constants.pubKeyValid.getParameters().getG().multiply(Constants.n);
ECElGamalEncryptor encryptor = new ECElGamalEncryptor();
encryptor.init(Constants.pubKeyValid);
ECPair cipherText = encryptor.encrypt(data);
}
public void testTwo() {
ECPoint data = Constants.pubKeyValid.getParameters().getG().multiply(Constants.n);
ECElGamalEncryptor encryptor = new ECElGamalEncryptor();
ECPair cipherText = encryptor.encrypt(data);
}
public void testThree(String point) {
ECDomainParameters params = new ECDomainParameters(Constants.curve, Constants.curve.decodePoint(Hex.decode(point)), Constants.n);
ECPublicKeyParameters pubKey = new ECPublicKeyParameters(Constants.curve.decodePoint(Hex.decode(point)), params);
ECPoint data = pubKey.getParameters().getG().multiply(Constants.n);
ECElGamalEncryptor encryptor = new ECElGamalEncryptor();
encryptor.init(pubKey);
ECPair cipherText = encryptor.encrypt(data);
}
public void testFour(String point) {
ECDomainParameters params = new ECDomainParameters(Constants.curve, Constants.curve.decodePoint(Hex.decode(point)), Constants.n);
ECPublicKeyParameters pubKey = new ECPublicKeyParameters(Constants.curve.decodePoint(Hex.decode(point)), params);
ParametersWithRandom parRand = new ParametersWithRandom(pubKey, new SecureRandom());
ECPoint data = pubKey.getParameters().getG().multiply(Constants.n);
ECElGamalEncryptor encryptor = new ECElGamalEncryptor();
encryptor.init(parRand);
ECPair cipherText = encryptor.encrypt(data);
}
}
| 2,073 | 39.666667 | 131 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/BCEllipticCurveExamples/src/main/java/generators/ECKeyPairGeneratorTest.java | package generators;
import java.security.SecureRandom;
import org.bouncycastle.crypto.generators.ECKeyPairGenerator;
import org.bouncycastle.crypto.params.ECDomainParameters;
import org.bouncycastle.crypto.params.ECKeyGenerationParameters;
import org.bouncycastle.util.encoders.Hex;
import constants.Constants;
public class ECKeyPairGeneratorTest {
/**
* Correct usage */
public void testOne(String point) {
ECDomainParameters params = new ECDomainParameters(Constants.curve,
Constants.curve.decodePoint(Hex.decode(point)),
Constants.n);
ECKeyGenerationParameters ecGenParams = new ECKeyGenerationParameters(params, new SecureRandom());
ECKeyPairGenerator keyPairGen = new ECKeyPairGenerator();
keyPairGen.init(ecGenParams);
keyPairGen.generateKeyPair();
}
/**
* With TypestateError */
public void testTwo(String point) {
ECKeyPairGenerator keyPairGen = new ECKeyPairGenerator();
keyPairGen.generateKeyPair();
}
/**
* With IncompleteOperationError */
public void testThree(String point) {
ECDomainParameters params = new ECDomainParameters(Constants.curve,
Constants.curve.decodePoint(Hex.decode(point)),
Constants.n);
ECKeyGenerationParameters ecGenParams = new ECKeyGenerationParameters(params, new SecureRandom());
ECKeyPairGenerator keyPairGen = new ECKeyPairGenerator();
keyPairGen.init(ecGenParams);
}
}
| 1,376 | 29.6 | 100 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/BCEllipticCurveExamples/src/main/java/params/ECDomainParametersTest.java | package params;
import org.bouncycastle.crypto.params.ECDomainParameters;
import org.bouncycastle.util.encoders.Hex;
import constants.Constants;
@SuppressWarnings("unused")
public class ECDomainParametersTest {
public void testOne(String point) {
ECDomainParameters params = new ECDomainParameters(Constants.curve,
Constants.curve.decodePoint(Hex.decode(point)),
Constants.n);
}
public void testTwo(String point) {
ECDomainParameters params = new ECDomainParameters(Constants.curve,
Constants.curve.decodePoint(Hex.decode(point)),
Constants.n,
Constants.n);
}
public void testThree(String point) {
ECDomainParameters params = new ECDomainParameters(Constants.curve,
Constants.curve.decodePoint(Hex.decode(point)),
Constants.n,
Constants.n,
Hex.decode(point));
}
}
| 822 | 25.548387 | 70 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/BCEllipticCurveExamples/src/main/java/params/ECKeyGenerationParametersTest.java | package params;
import java.security.SecureRandom;
import org.bouncycastle.crypto.params.ECDomainParameters;
import org.bouncycastle.crypto.params.ECKeyGenerationParameters;
import org.bouncycastle.util.encoders.Hex;
import constants.Constants;
public class ECKeyGenerationParametersTest {
/**
* Correct usage */
public void testOne(String point) {
ECDomainParameters params = new ECDomainParameters(Constants.curve,
Constants.curve.decodePoint(Hex.decode(point)),
Constants.n);
@SuppressWarnings("unused")
ECKeyGenerationParameters ecGenParams = new ECKeyGenerationParameters(params, new SecureRandom());
}
/**
* With incorrect random */
public void testTwo(String point) {
ECDomainParameters params = new ECDomainParameters(Constants.curve,
Constants.curve.decodePoint(Hex.decode(point)),
Constants.n);
@SuppressWarnings("unused")
ECKeyGenerationParameters ecGenParams = new ECKeyGenerationParameters(params, null);
}
/**
* With incorrect ECDomainParameters */
public void testThree(String point) {
@SuppressWarnings("unused")
ECKeyGenerationParameters ecGenParams = new ECKeyGenerationParameters(null, new SecureRandom());
}
}
| 1,189 | 28.75 | 100 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/BCEllipticCurveExamples/src/main/java/params/ECPrivateKeyParametersTest.java | package params;
import java.math.BigInteger;
import java.security.SecureRandom;
import org.bouncycastle.crypto.params.ECDomainParameters;
import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
import org.bouncycastle.util.encoders.Hex;
import constants.Constants;
@SuppressWarnings("unused")
public class ECPrivateKeyParametersTest {
public void testOne(String point) {
ECDomainParameters params = new ECDomainParameters(Constants.curve,
Constants.curve.decodePoint(Hex.decode(point)),
Constants.n,
Constants.n,
Hex.decode(point));
ECPrivateKeyParameters priKey = new ECPrivateKeyParameters(
new BigInteger(point),
params);
}
public void testTwo(String point) {
ECDomainParameters params = new ECDomainParameters(Constants.curve,
Constants.curve.decodePoint(Hex.decode(point)),
Constants.n,
Constants.n,
new SecureRandom().generateSeed(10));
ECPrivateKeyParameters priKey = new ECPrivateKeyParameters(new BigInteger(point), params);
}
}
| 1,018 | 28.114286 | 92 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/BCEllipticCurveExamples/src/main/java/params/ECPublicKeyParametersTest.java | package params;
import java.math.BigInteger;
import java.security.SecureRandom;
import org.bouncycastle.crypto.params.ECDomainParameters;
import org.bouncycastle.crypto.params.ECPublicKeyParameters;
import org.bouncycastle.math.ec.ECConstants;
import org.bouncycastle.math.ec.ECCurve;
import org.bouncycastle.util.encoders.Hex;
import constants.Constants;
@SuppressWarnings("unused")
public class ECPublicKeyParametersTest {
public void testOne(String point) {
ECDomainParameters params = new ECDomainParameters(Constants.curve,
Constants.curve.decodePoint(Hex.decode(point)),
Constants.n,
Constants.n,
Hex.decode(point));
ECPublicKeyParameters pubKey = new ECPublicKeyParameters(Constants.curve.decodePoint(Hex.decode(point)), params);
}
public void testTwo(String point) {
ECDomainParameters params = new ECDomainParameters(Constants.curve,
Constants.curve.decodePoint(Hex.decode(point)),
Constants.n,
Constants.n,
new SecureRandom().generateSeed(10));
ECPublicKeyParameters pubKey = new ECPublicKeyParameters(Constants.curve.decodePoint(Hex.decode(point)), params);
}
}
| 1,134 | 31.428571 | 115 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/BCEllipticCurveExamples/src/main/java/params/ParametersWithRandomTest.java | package params;
import java.security.SecureRandom;
import org.bouncycastle.crypto.params.ECDomainParameters;
import org.bouncycastle.crypto.params.ECPublicKeyParameters;
import org.bouncycastle.crypto.params.ParametersWithRandom;
import org.bouncycastle.util.encoders.Hex;
import constants.Constants;
@SuppressWarnings("unused")
public class ParametersWithRandomTest {
public void testOne(String point) {
ECDomainParameters params = new ECDomainParameters(Constants.curve, Constants.curve.decodePoint(Hex.decode(point)), Constants.n, Constants.n, Hex.decode(point));
ECPublicKeyParameters pubKey = new ECPublicKeyParameters(Constants.curve.decodePoint(Hex.decode(point)), params);
ParametersWithRandom pubKeyRand = new ParametersWithRandom(pubKey);
}
public void testTwo(String point) {
ECDomainParameters params = new ECDomainParameters(Constants.curve, Constants.curve.decodePoint(Hex.decode(point)), Constants.n, Constants.n, new SecureRandom().generateSeed(10));
ECPublicKeyParameters pubKey = new ECPublicKeyParameters(Constants.curve.decodePoint(Hex.decode(point)), params);
ParametersWithRandom pubKeyRand = new ParametersWithRandom(pubKey);
}
public void testThree(String point) {
ECDomainParameters params = new ECDomainParameters(Constants.curve, Constants.curve.decodePoint(Hex.decode(point)), Constants.n, Constants.n, Hex.decode(point));
ECPublicKeyParameters pubKey = new ECPublicKeyParameters(Constants.curve.decodePoint(Hex.decode(point)), params);
ParametersWithRandom pubKeyRand = new ParametersWithRandom(pubKey, null);
}
}
| 1,578 | 46.848485 | 181 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/BCEllipticCurveExamples/src/main/java/transforms/ECFixedTransformTest.java | package transforms;
import org.bouncycastle.crypto.ec.ECFixedTransform;
import org.bouncycastle.crypto.ec.ECPair;
import org.bouncycastle.crypto.params.ECDomainParameters;
import org.bouncycastle.crypto.params.ECPublicKeyParameters;
import org.bouncycastle.math.ec.ECPoint;
import org.bouncycastle.util.encoders.Hex;
import constants.Constants;
public class ECFixedTransformTest {
public void testOne(String point) {
ECDomainParameters params = new ECDomainParameters(Constants.curve,
Constants.curve.decodePoint(Hex.decode(point)),
Constants.n,
Constants.n,
Hex.decode(point));
ECPoint data = Constants.priKey.getParameters().getG().multiply(Constants.n);
ECPair cipherText = new ECPair(data, data);
ECPublicKeyParameters pubKey = new ECPublicKeyParameters(Constants.curve.decodePoint(Hex.decode(point)), params);
ECFixedTransform ecTrans = new ECFixedTransform(Constants.n);
ecTrans.init(pubKey);
ecTrans.transform(cipherText);
}
public void testTwo(String point) {
ECDomainParameters params = new ECDomainParameters(Constants.curve,
Constants.curve.decodePoint(Hex.decode(point)),
Constants.n,
Constants.n,
Hex.decode(point));
ECPoint data = Constants.priKey.getParameters().getG().multiply(Constants.n);
ECPair cipherText = new ECPair(data, data);
ECPublicKeyParameters pubKey = new ECPublicKeyParameters(Constants.curve.decodePoint(Hex.decode(point)), params);
ECFixedTransform ecTrans = new ECFixedTransform(Constants.n);
ecTrans.init(pubKey);
ecTrans.transform(cipherText);
ecTrans.transform(cipherText);
ecTrans.transform(cipherText);
}
public void testThree(String point) {
ECPoint data = Constants.priKey.getParameters().getG().multiply(Constants.n);
ECPair cipherText = new ECPair(data, data);
ECPublicKeyParameters pubKey = new ECPublicKeyParameters(Constants.curve.decodePoint(Hex.decode(point)), null);
ECFixedTransform ecTrans = new ECFixedTransform(Constants.n);
ecTrans.init(pubKey);
ecTrans.transform(cipherText);
}
public void testFour(String point) {
ECDomainParameters params = new ECDomainParameters(Constants.curve,
Constants.curve.decodePoint(Hex.decode(point)),
Constants.n,
Constants.n,
Hex.decode(point));
ECPoint data = Constants.priKey.getParameters().getG().multiply(Constants.n);
ECPair cipherText = new ECPair(data, data);
ECPublicKeyParameters pubKey = new ECPublicKeyParameters(Constants.curve.decodePoint(Hex.decode(point)), params);
ECFixedTransform ecTrans = new ECFixedTransform(null);
ecTrans.init(pubKey);
ecTrans.transform(cipherText);
}
/**
* With TypestateError */
public void testFive(String point) {
ECPoint data = Constants.priKey.getParameters().getG().multiply(Constants.n);
ECPair cipherText = new ECPair(data, data);
ECFixedTransform ecTrans = new ECFixedTransform(Constants.n);
ecTrans.transform(cipherText);
}
/**
* With IncompleteOperationError */
public void testSix(String point) {
ECDomainParameters params = new ECDomainParameters(Constants.curve,
Constants.curve.decodePoint(Hex.decode(point)),
Constants.n,
Constants.n,
Hex.decode(point));
ECPublicKeyParameters pubKey = new ECPublicKeyParameters(Constants.curve.decodePoint(Hex.decode(point)), params);
ECFixedTransform ecTrans = new ECFixedTransform(Constants.n);
ecTrans.init(pubKey);
}
}
| 3,390 | 36.677778 | 115 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/BCEllipticCurveExamples/src/main/java/transforms/ECNewPublicKeyTransformTest.java | package transforms;
import org.bouncycastle.crypto.ec.ECNewPublicKeyTransform;
import org.bouncycastle.crypto.ec.ECPair;
import org.bouncycastle.crypto.params.ECDomainParameters;
import org.bouncycastle.crypto.params.ECPublicKeyParameters;
import org.bouncycastle.crypto.params.ParametersWithRandom;
import org.bouncycastle.math.ec.ECPoint;
import org.bouncycastle.util.encoders.Hex;
import constants.Constants;
public class ECNewPublicKeyTransformTest {
/**
* With ECPublicKeyParameters in init*/
public void testOne(String point) {
ECDomainParameters params = new ECDomainParameters(Constants.curve,
Constants.curve.decodePoint(Hex.decode(point)),
Constants.n,
Constants.n,
Hex.decode(point));
ECPublicKeyParameters pubKey = new ECPublicKeyParameters(Constants.curve.decodePoint(Hex.decode(point)), params);
ECPoint data = Constants.priKey.getParameters().getG().multiply(Constants.n);
ECPair cipherText = new ECPair(data, data);
ECNewPublicKeyTransform ecr = new ECNewPublicKeyTransform();
ecr.init(pubKey);
ecr.transform(cipherText);
}
/**
* With ParametersWithRandom in init*/
public void testTwo(String point) {
ECDomainParameters params = new ECDomainParameters(Constants.curve, Constants.curve.decodePoint(Hex.decode(point)), Constants.n, Constants.n, Hex.decode(point));
ECPublicKeyParameters pubKey = new ECPublicKeyParameters(Constants.curve.decodePoint(Hex.decode(point)), params);
ParametersWithRandom pubKeyRand = new ParametersWithRandom(pubKey);
ECPoint data = Constants.priKey.getParameters().getG().multiply(Constants.n);
ECPair cipherText = new ECPair(data, data);
ECNewPublicKeyTransform ecr = new ECNewPublicKeyTransform();
ecr.init(pubKeyRand);
ecr.transform(cipherText);
ecr.transform(cipherText);
ecr.transform(cipherText);
}
/**
* With TypestateError*/
public void testThree(String point) {
ECPoint data = Constants.priKey.getParameters().getG().multiply(Constants.n);
ECPair cipherText = new ECPair(data, data);
ECNewPublicKeyTransform ecr = new ECNewPublicKeyTransform();
ecr.transform(cipherText);
}
/**
* With IncompleteOperationError in init*/
public void testFour(String point) {
ECDomainParameters params = new ECDomainParameters(Constants.curve, Constants.curve.decodePoint(Hex.decode(point)), Constants.n, Constants.n, Hex.decode(point));
ECPublicKeyParameters pubKey = new ECPublicKeyParameters(Constants.curve.decodePoint(Hex.decode(point)), params);
ParametersWithRandom pubKeyRand = new ParametersWithRandom(pubKey);
ECNewPublicKeyTransform ecr = new ECNewPublicKeyTransform();
ecr.init(pubKeyRand);
}
public void testFive(String point) {
ECDomainParameters params = new ECDomainParameters(Constants.curve, Constants.curve.decodePoint(Hex.decode(point)), Constants.n, Constants.n, Hex.decode(point));
ECPublicKeyParameters pubKey = new ECPublicKeyParameters(Constants.curve.decodePoint(Hex.decode(point)), params);
ParametersWithRandom pubKeyRand = new ParametersWithRandom(pubKey);
ECPair cipherText = new ECPair(null, null);
ECNewPublicKeyTransform ecr = new ECNewPublicKeyTransform();
ecr.init(pubKeyRand);
ecr.transform(cipherText);
}
public void testSix(String point) {
ParametersWithRandom pubKeyRand = new ParametersWithRandom(null);
ECPoint data = Constants.priKey.getParameters().getG().multiply(Constants.n);
ECPair cipherText = new ECPair(data, data);
ECNewPublicKeyTransform ecr = new ECNewPublicKeyTransform();
ecr.init(pubKeyRand);
ecr.transform(cipherText);
}
}
| 3,552 | 41.297619 | 163 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/BCEllipticCurveExamples/src/main/java/transforms/ECNewRandomessTransformTest.java | package transforms;
import org.bouncycastle.crypto.ec.ECNewRandomnessTransform;
import org.bouncycastle.crypto.ec.ECPair;
import org.bouncycastle.crypto.params.ECDomainParameters;
import org.bouncycastle.crypto.params.ECPublicKeyParameters;
import org.bouncycastle.crypto.params.ParametersWithRandom;
import org.bouncycastle.math.ec.ECPoint;
import org.bouncycastle.util.encoders.Hex;
import constants.Constants;
public class ECNewRandomessTransformTest {
/**
* With ECPublicKeyParameters in init*/
public void testOne(String point) {
ECDomainParameters params = new ECDomainParameters(Constants.curve,
Constants.curve.decodePoint(Hex.decode(point)),
Constants.n,
Constants.n,
Hex.decode(point));
ECPublicKeyParameters pubKey = new ECPublicKeyParameters(Constants.curve.decodePoint(Hex.decode(point)), params);
ECPoint data = Constants.priKey.getParameters().getG().multiply(Constants.n);
ECPair cipherText = new ECPair(data, data);
ECNewRandomnessTransform ecr = new ECNewRandomnessTransform();
ecr.init(pubKey);
ecr.transform(cipherText);
}
/**
* With ParametersWithRandom in init*/
public void testTwo(String point) {
ECDomainParameters params = new ECDomainParameters(Constants.curve, Constants.curve.decodePoint(Hex.decode(point)), Constants.n, Constants.n, Hex.decode(point));
ECPublicKeyParameters pubKey = new ECPublicKeyParameters(Constants.curve.decodePoint(Hex.decode(point)), params);
ParametersWithRandom pubKeyRand = new ParametersWithRandom(pubKey);
ECPoint data = Constants.priKey.getParameters().getG().multiply(Constants.n);
ECPair cipherText = new ECPair(data, data);
ECNewRandomnessTransform ecr = new ECNewRandomnessTransform();
ecr.init(pubKeyRand);
ecr.transform(cipherText);
ecr.transform(cipherText);
ecr.transform(cipherText);
}
/**
* With TypestateError*/
public void testThree(String point) {
ECPoint data = Constants.priKey.getParameters().getG().multiply(Constants.n);
ECPair cipherText = new ECPair(data, data);
ECNewRandomnessTransform ecr = new ECNewRandomnessTransform();
ecr.transform(cipherText);
}
/**
* With IncompleteOperationError in init*/
public void testFour(String point) {
ECDomainParameters params = new ECDomainParameters(Constants.curve, Constants.curve.decodePoint(Hex.decode(point)), Constants.n, Constants.n, Hex.decode(point));
ECPublicKeyParameters pubKey = new ECPublicKeyParameters(Constants.curve.decodePoint(Hex.decode(point)), params);
ParametersWithRandom pubKeyRand = new ParametersWithRandom(pubKey);
ECNewRandomnessTransform ecr = new ECNewRandomnessTransform();
ecr.init(pubKeyRand);
}
public void testFive(String point) {
ECDomainParameters params = new ECDomainParameters(Constants.curve, Constants.curve.decodePoint(Hex.decode(point)), Constants.n, Constants.n, Hex.decode(point));
ECPublicKeyParameters pubKey = new ECPublicKeyParameters(Constants.curve.decodePoint(Hex.decode(point)), params);
ParametersWithRandom pubKeyRand = new ParametersWithRandom(pubKey);
ECPair cipherText = new ECPair(null, null);
ECNewRandomnessTransform ecr = new ECNewRandomnessTransform();
ecr.init(pubKeyRand);
ecr.transform(cipherText);
}
public void testSix(String point) {
ParametersWithRandom pubKeyRand = new ParametersWithRandom(null);
ECPoint data = Constants.priKey.getParameters().getG().multiply(Constants.n);
ECPair cipherText = new ECPair(data, data);
ECNewRandomnessTransform ecr = new ECNewRandomnessTransform();
ecr.init(pubKeyRand);
ecr.transform(cipherText);
}
}
| 3,565 | 41.452381 | 163 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/BCMacExamples/src/main/java/animamea/AmAESCrypto.java | package animamea;
import org.bouncycastle.crypto.BlockCipher;
import org.bouncycastle.crypto.Mac;
import org.bouncycastle.crypto.engines.AESFastEngine;
import org.bouncycastle.crypto.macs.CMac;
import org.bouncycastle.crypto.paddings.ISO7816d4Padding;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.util.encoders.Hex;
@SuppressWarnings("deprecation")
public class AmAESCrypto {
private KeyParameter keyP = new KeyParameter(Hex.decode("cb41f1706cde09651203c2d0efbaddf847a0d315cb2e53ff8bac41da0002672e"));
private byte[] sscBytes = Hex.decode("d3090c72");
public static int blockSize = 16;
public byte[] getMACOne(byte[] data) {
byte[] n = new byte[sscBytes.length + data.length];
System.arraycopy(sscBytes, 0, n, 0, sscBytes.length);
System.arraycopy(data, 0, n, sscBytes.length, data.length);
n = addPadding(n);
BlockCipher cipher = new AESFastEngine();
Mac mac = new CMac(cipher, 64);
mac.init(keyP);
mac.update(n, 0, n.length);
byte[] out = new byte[mac.getMacSize()];
mac.doFinal(out, 0);
return out;
}
public byte[] getMACTwo(byte[] key, byte[] data) {
BlockCipher cipher = new AESFastEngine();
Mac mac = new CMac(cipher, 64); // TODO Padding der Daten
KeyParameter keyP = new KeyParameter(key);
mac.init(keyP);
mac.update(data, 0, data.length);
byte[] out = new byte[8];
mac.doFinal(out, 0);
return out;
}
public byte[] addPadding(byte[] data) {
int len = data.length;
int nLen = ((len / blockSize) + 1) * blockSize;
byte[] n = new byte[nLen];
System.arraycopy(data, 0, n, 0, data.length);
new ISO7816d4Padding().addPadding(n, len);
return n;
}
}
| 1,659 | 25.774194 | 126 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/BCMacExamples/src/main/java/bunkr/PBKDF2Descriptor.java | package bunkr;
import org.bouncycastle.crypto.digests.SHA256Digest;
import org.bouncycastle.crypto.macs.HMac;
public class PBKDF2Descriptor {
public static final int MINIMUM_PBKD2_ITERS = 4096;
public static int calculateRounds(int milliseconds)
{
HMac mac = new HMac(new SHA256Digest());
byte[] state = new byte[mac.getMacSize()];
long startTime = System.currentTimeMillis();
int pbkdf2Iterations = 0;
while((System.currentTimeMillis() - startTime) < milliseconds)
{
mac.update(state, 0, state.length);
mac.doFinal(state, 0);
pbkdf2Iterations++;
}
pbkdf2Iterations = Math.max(pbkdf2Iterations, PBKDF2Descriptor.MINIMUM_PBKD2_ITERS);
return pbkdf2Iterations;
}
}
| 745 | 27.692308 | 89 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/BCMacExamples/src/main/java/gwt_crypto/GMacTest.java | package gwt_crypto;
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.Mac;
import org.bouncycastle.crypto.engines.AESFastEngine;
import org.bouncycastle.crypto.macs.GMac;
import org.bouncycastle.crypto.modes.GCMBlockCipher;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.crypto.params.ParametersWithIV;
import org.bouncycastle.util.encoders.Hex;
public class GMacTest {
public void performTestOne()
{
byte[] key = Hex.decode("11754cd72aec309bf52f7687212e8957");
byte[] iv = Hex.decode("3c819d9a9bed087615030b65");
byte[] tag = Hex.decode("250327c674aaf477aef2675748cf6971");
Mac mac = new GMac(new GCMBlockCipher(new AESFastEngine()), tag.length * 8);
CipherParameters param = new KeyParameter(key);
mac.init(new ParametersWithIV(param, iv));
}
}
| 824 | 33.375 | 78 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/BCMacExamples/src/main/java/gwt_crypto/SkeinMacTest.java | package gwt_crypto;
import org.bouncycastle.crypto.Mac;
import org.bouncycastle.crypto.macs.SkeinMac;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.util.Arrays;
import org.bouncycastle.util.encoders.Hex;
public class SkeinMacTest {
private byte[] msg = Hex.decode("d3090c72");
private byte[] key = Hex.decode("cb41f1706cde09651203c2d0efbaddf847a0d315cb2e53ff8bac41da0002672e");
private byte[] digest1 = Hex.decode("1d658372cbea2f9928493cc47599d6f4ad8ce33536bedfa20b739f07516519d5");
private int blockSize = 256;
private int outputSize = 256;
public void performTestOne()
{
Mac digest = new SkeinMac(blockSize, outputSize);
digest.init(new KeyParameter(key));
byte[] message = msg;
digest.update(message, 0, message.length);
byte[] output = new byte[digest.getMacSize()];
digest.doFinal(output, 0);
if (!Arrays.areEqual(output, digest1))
{
System.out.println(digest.getAlgorithmName() + " message " + (digest1.length * 8) + " mismatch.\n Message " + new String(Hex.encode(message))
+ "\n Key " + new String(Hex.encode(key)) + "\n Expected "
+ new String(Hex.encode(digest1)) + "\n Actual " + new String(Hex.encode(output)));
}
}
}
| 1,268 | 33.297297 | 151 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/BCMacExamples/src/main/java/pattern/MacTest.java | package pattern;
import org.bouncycastle.crypto.BlockCipher;
import org.bouncycastle.crypto.Mac;
import org.bouncycastle.crypto.engines.DESEngine;
import org.bouncycastle.crypto.macs.CBCBlockCipherMac;
import org.bouncycastle.crypto.paddings.PKCS7Padding;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.crypto.params.ParametersWithIV;
import org.bouncycastle.util.encoders.Hex;
public class MacTest {
public void testMac1() {
byte[] keyBytes = Hex.decode("0123456789abcdef");
byte[] input1 = Hex.decode("37363534333231204e6f77206973207468652074696d6520666f7220");
KeyParameter key = new KeyParameter(keyBytes);
BlockCipher cipher = new DESEngine();
// CBCBlockCipherMac mac = new CBCBlockCipherMac(cipher); //works
Mac mac = new CBCBlockCipherMac(cipher); //doesn't work
mac.init(key);
mac.update(input1, 0, input1.length);
byte[] out = new byte[4];
mac.doFinal(out, 0);
}
public void testMac2() {
byte[] keyBytes = Hex.decode("0123456789abcdef");
byte[] input2 = Hex.decode("3736353433323120");
byte[] ivBytes = Hex.decode("1234567890abcdef");
KeyParameter key = new KeyParameter(keyBytes);
BlockCipher cipher = new DESEngine();
PKCS7Padding padding = new PKCS7Padding();
CBCBlockCipherMac mac = new CBCBlockCipherMac(cipher, padding);
ParametersWithIV param = new ParametersWithIV(key, ivBytes);
mac.init(param);
mac.update(input2, 0, input2.length);
//missing doFinal call
}
}
| 1,547 | 29.352941 | 89 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/BCSignerExamples/src/main/java/bop_bitcoin_client/ECKeyPair.java | package bop_bitcoin_client;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.SecureRandom;
import javax.xml.bind.ValidationException;
import org.bouncycastle.asn1.ASN1Integer;
import org.bouncycastle.asn1.DERSequenceGenerator;
import org.bouncycastle.asn1.sec.SECNamedCurves;
import org.bouncycastle.asn1.x9.X9ECParameters;
import org.bouncycastle.crypto.AsymmetricCipherKeyPair;
import org.bouncycastle.crypto.digests.SHA256Digest;
import org.bouncycastle.crypto.generators.ECKeyPairGenerator;
import org.bouncycastle.crypto.params.ECDomainParameters;
import org.bouncycastle.crypto.params.ECKeyGenerationParameters;
import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
import org.bouncycastle.crypto.params.ECPublicKeyParameters;
import org.bouncycastle.crypto.signers.ECDSASigner;
import org.bouncycastle.crypto.signers.HMacDSAKCalculator;
public class ECKeyPair {
private static final X9ECParameters curve = SECNamedCurves.getByName ("secp256k1");
private static final ECDomainParameters domain = new ECDomainParameters (curve.getCurve (), curve.getG (), curve.getN (), curve.getH ());
private static final SecureRandom secureRandom = new SecureRandom ();
private BigInteger priv;
@SuppressWarnings("unused")
private byte[] pub;
public byte[] sign (byte[] hash) throws ValidationException
{
if ( priv == null )
{
throw new ValidationException ("Need private key to sign");
}
ECDSASigner signer = new ECDSASigner (new HMacDSAKCalculator (new SHA256Digest ()));
signer.init (true, new ECPrivateKeyParameters (priv, domain));
BigInteger[] signature = signer.generateSignature (hash);
ByteArrayOutputStream s = new ByteArrayOutputStream ();
try
{
DERSequenceGenerator seq = new DERSequenceGenerator (s);
seq.addObject (new ASN1Integer (signature[0]));
seq.addObject (new ASN1Integer (signature[1]));
seq.close ();
return s.toByteArray ();
}
catch ( IOException e )
{
}
return null;
}
public static ECKeyPair createNew (boolean compressed)
{
ECKeyPairGenerator generator = new ECKeyPairGenerator ();
ECKeyGenerationParameters keygenParams = new ECKeyGenerationParameters (domain, secureRandom);
generator.init (keygenParams);
AsymmetricCipherKeyPair keypair = generator.generateKeyPair ();
ECPrivateKeyParameters privParams = (ECPrivateKeyParameters) keypair.getPrivate ();
ECPublicKeyParameters pubParams = (ECPublicKeyParameters) keypair.getPublic ();
ECKeyPair k = new ECKeyPair ();
k.priv = privParams.getD ();
k.pub = pubParams.getQ ().getEncoded (compressed);
return k;
}
}
| 2,641 | 36.742857 | 138 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/BCSignerExamples/src/main/java/diqube/TicketSignatureService.java | package diqube;
import java.nio.ByteBuffer;
import java.util.List;
import org.bouncycastle.crypto.CryptoException;
import org.bouncycastle.crypto.DataLengthException;
import org.bouncycastle.crypto.digests.SHA256Digest;
import org.bouncycastle.crypto.params.RSAKeyParameters;
import org.bouncycastle.crypto.params.RSAPrivateCrtKeyParameters;
import org.bouncycastle.crypto.signers.RSADigestSigner;
public class TicketSignatureService {
/**
* Checks if a {@link Ticket} has a valid signature.
*
* @param deserializedTicket
* The result of {@link TicketUtil#deserialize(ByteBuffer)} of the serialized {@link Ticket}.
* @return true if {@link Ticket} signature is valid.
*/
public boolean isValidTicketSignature(byte[] deserializedTicket) {
for (RSAKeyParameters pubKey : getPublicValidationKeys()) {
RSADigestSigner signer = new RSADigestSigner(new SHA256Digest());
signer.init(false, pubKey);
signer.update(deserializedTicket, 0, deserializedTicket.length);
if (signer.verifySignature(deserializedTicket))
return true;
}
return false;
}
private List<RSAKeyParameters> getPublicValidationKeys() {
// TODO Auto-generated method stub
return null;
}
/**
* Calculates the signature of a ticket and updates the given {@link Ticket} object directly.
*
* @throws IllegalStateException
* If ticket cannot be signed.
*/
public void signTicket() throws IllegalStateException {
byte[] serialized = new byte[32]; // replaced actual method here
byte[] claimBytes = new byte[32]; // replaced actual method here
RSAPrivateCrtKeyParameters signingKey = getPrivateSigningKey();
if (signingKey == null)
throw new IllegalStateException("Cannot sign ticket because there is no private signing key available.");
RSADigestSigner signer = new RSADigestSigner(new SHA256Digest());
signer.init(true, signingKey);
signer.update(claimBytes, 0, claimBytes.length);
try {
byte[] signature = signer.generateSignature();
setSignature(signature);
} catch (DataLengthException | CryptoException e) {
throw new IllegalStateException("Cannot sign ticket", e);
}
}
private RSAPrivateCrtKeyParameters getPrivateSigningKey() {
// TODO Auto-generated method stub
// replaced actual method here
return null;
}
private void setSignature(byte[] signature) {
// TODO Auto-generated method stub
// replaced actual method here
}
}
| 2,488 | 31.324675 | 110 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/BCSignerExamples/src/main/java/gwt_crypto/ISO9796SignerTest.java | package gwt_crypto;
import java.math.BigInteger;
import java.util.Arrays;
import org.bouncycastle.crypto.AsymmetricBlockCipher;
import org.bouncycastle.crypto.digests.SHA1Digest;
import org.bouncycastle.crypto.digests.SHA256Digest;
import org.bouncycastle.crypto.engines.RSABlindedEngine;
import org.bouncycastle.crypto.engines.RSAEngine;
import org.bouncycastle.crypto.params.AsymmetricKeyParameter;
import org.bouncycastle.crypto.params.RSAKeyParameters;
import org.bouncycastle.crypto.signers.ISO9796d2PSSSigner;
import org.bouncycastle.util.encoders.Base64;
import org.bouncycastle.util.encoders.Hex;
public class ISO9796SignerTest {
private static final byte[] shortPartialSig = Base64.decode(
"sb8yyKk6HM1cJhICScMx7QRQunRyrZ1fbI42+T+TBGNjOknvzKuvG7aftGX7"
+ "O/RXuYgk6LTxpXv7+O5noUhMBsR2PKaHveuylU1WSPmDxDCui3kp4frqVH0w"
+ "8Vjpl5CsKqBsmKkbGCKE+smM0xFXhYxV8QUTB2XsWNCQiFiHPgwbpfWzZUNY"
+ "QPWd0A99P64EuUIYz1tkkDnLFmwQ19/PJu1a8orIQInmkVYWSsBsZ/7Ks6lx"
+ "nDHpAvgiRe+OXmJ/yuQy1O3FJYdyoqvjYRPBu3qYeBK9+9L3lExLilImH5aD"
+ "nJznaXcO8QFOxVPbrF2s4GdPIMDonEyAHdrnzoghlg==");
private static final byte[] longMessage = Base64.decode(
"VVNIKzErU0U2ODAxNTMyOTcxOSsyKzErNisyKzErMTo6OTk5OTk5OTk5OTk5"
+ "OTo6OSsyOjo3Nzc3Nzc3Nzc3Nzc3Ojo5Kys1OjIwMTMwNDA1OjExMzUyMCdV"
+ "U0ErMTo6OjE2OjEnVVNDKzRmYjk3YzFhNDI5ZGIyZDYnVVNBKzY6MTY6MTox"
+ "MDoxKzE0OjIwNDgrMTI6/vn3S0h96eNhfmPN6OZUxXhd815h0tP871Hl+V1r"
+ "fHHUXvrPXmjHV0vdb8fYY1zxwvnQUcFBWXT43PFi7Xbow0/9e9l6/mhs1UJq"
+ "VPvp+ELbeXfn4Nj02ttk0e3H5Hfa69NYRuHv1WBO6lfizNnM9m9XYmh9TOrg"
+ "f9rDRtd+ZNbf4lz9fPTt9OXyxOJWRPr/0FLzxUVsddplfHxM3ndETFD7ffjI"
+ "/mhRYuL8WXZ733LeWFRCeOzKzmDz/HvT3GZx/XJMbFpqyOZjedzh6vZr1vrD"
+ "615TQfN7wtJJ29bN2Hvzb2f1xGHaXl7af0/w9dpR2dr7/HzuZEJKYc7JSkv4"
+ "/k37yERIbcrfbVTeVtR+dcVoeeRT41fmzMfzf8RnWOX4YMNifl0rMTM68EFA"
+ "QSdCR00rMzgwKzk5OTk5OTk5J0RUTSsxMzc6MjAxMzA0MDU6MTAyJ0ZUWCtB"
+ "QUkrKytJTlZPSUNFIFRFU1QnUkZGK09OOjEyMzQ1NidSRkYrRFE6MjIyMjIy"
+ "MjIyJ0RUTSsxNzE6MjAxMzA0MDE6MTAyJ05BRCtTVSs5OTk5OTk5OTk5OTk5"
+ "Ojo5KytURVNUIFNVUFBMSUVSOjpUcmFzZSByZWdpc3RlciBYWFhYWFhYK1Rl"
+ "c3QgYWRkcmVzcyBzdXBwbGllcitDaXR5KysxMjM0NStERSdSRkYrVkE6QTEy"
+ "MzQ1Njc4J05BRCtTQ08rOTk5OTk5OTk5OTk5OTo6OSsrVEVTVCBTVVBQTElF"
+ "Ujo6VHJhc2UgcmVnaXN0ZXIgWFhYWFhYWCtUZXN0IGFkZHJlc3Mgc3VwcGxp"
+ "ZXIrQ2l0eSsrMTIzNDUrREUnUkZGK1ZBOkExMjM0NTY3OCdOQUQrQlkrODg4"
+ "ODg4ODg4ODg4ODo6OSdOQUQrSVYrNzc3Nzc3Nzc3Nzc3Nzo6OSsrVEVTVCBC"
+ "VVlFUitUZXN0IGFkZHJlc3MgYnV5ZXIrQ2l0eTIrKzU0MzIxK0RFJ1JGRitW"
+ "QTpKODc2NTQzMjEnTkFEK0JDTys3Nzc3Nzc3Nzc3Nzc3Ojo5KytURVNUIEJV"
+ "WUVSK1Rlc3QgYWRkcmVzcyBidXllcitDaXR5MisrNTQzMjErREUnUkZGK1ZB"
+ "Oko4NzY1NDMyMSdOQUQrRFArODg4ODg4ODg4ODg4ODo6OSdOQUQrUFIrNzc3"
+ "Nzc3Nzc3Nzc3Nzo6OSdDVVgrMjpFVVI6NCdQQVQrMzUnRFRNKzEzOjIwMTMw"
+ "NjI0OjEwMidMSU4rMSsrMTExMTExMTExMTExMTpFTidQSUErMStBQUFBQUFB"
+ "OlNBJ0lNRCtGK00rOjo6UFJPRFVDVCBURVNUIDEnUVRZKzQ3OjEwLjAwMCdN"
+ "T0ErNjY6Ny4wMCdQUkkrQUFCOjEuMDAnUFJJK0FBQTowLjcwJ1JGRitPTjox"
+ "MjM0NTYnUkZGK0RROjIyMjIyMjIyMidUQVgrNytWQVQrKys6OjoyMS4wMDAn"
+ "QUxDK0ErKysxK1REJ1BDRCsxOjMwLjAwMCdNT0ErMjA0OjMuMDAnTElOKzIr"
+ "KzIyMjIyMjIyMjIyMjI6RU4nUElBKzErQkJCQkJCQjpTQSdJTUQrRitNKzo6"
+ "OlBST0RVQ1QgVEVTVCAyJ1FUWSs0NzoyMC4wMDAnTU9BKzY2OjgwLjAwJ1BS"
+ "SStBQUI6NS4wMCdQUkkrQUFBOjQuMDAnUkZGK09OOjEyMzQ1NidSRkYrRFE6"
+ "MjIyMjIyMjIyJ1RBWCs3K1ZBVCsrKzo6OjIxLjAwMCdBTEMrQSsrKzErVEQn"
+ "UENEKzE6MjAuMDAwJ01PQSsyMDQ6MjAuMDAnVU5TK1MnQ05UKzI6MidNT0Er"
+ "Nzk6ODcuMDAnTU9BKzEzOToxMDUuMjcnTU9BKzEyNTo4Ny4wMCdNT0ErMjYw"
+ "OjAuMDAnTU9BKzI1OTowLjAwJ01PQSsxNzY6MTguMjcnVEFYKzcrVkFUKysr"
+ "Ojo6MjEuMDAwJ01PQSsxNzY6MTguMjcnTU9BKzEyNTo4Ny4wMCc=");
public void doShortPartialTest()
throws Exception
{
byte[] recovered = Hex.decode("5553482b312b534536383031353332393731392b322b312b362b322b312b313a3a393939393939393939393939393a3a392b323a3a373737373737373737373737373a3a392b2b353a32303133303430353a313133");
BigInteger exp = new BigInteger("10001", 16);
BigInteger mod = new BigInteger("b9b70b083da9e37e23cde8e654855db31e21d2d3fc11a5f91d2b3c311efa8f5e28c757dd6fc798631cb1b9d051c14119749cb122ad76e8c3fd7bd93abe282c026a14fba9f8023977a7a0d8b49a24d1ad87e4379a931846a1ef9520ea57e28c998cf65722683d0caaa0da8306973e2496a25cbd3cb4adb4b284e25604fabf12f385456c75da7c3c4cde37440cfb7db8c8fe6851e2bc59767b9f7218540238ac8acef3bc7bd3dc6671320c2c1a2ac8a6799ce1eaf62b9683ab1e1341b37b9249dbd6cd987b2f27b5c4619a1eda7f0fb0b59a519afbbc3cee640261cec90a4bb8fefbc844082dca9f549e56943e758579a453a357e6ccb37fc46718a5b8c3227e5d", 16);
AsymmetricKeyParameter pubKey = new RSAKeyParameters(false, mod, exp);
ISO9796d2PSSSigner pssSign = new ISO9796d2PSSSigner(new RSAEngine(), new SHA1Digest(), 20);
pssSign.init(false, pubKey);
pssSign.updateWithRecoveredMessage(shortPartialSig);
pssSign.update(longMessage, pssSign.getRecoveredMessage().length, longMessage.length - pssSign.getRecoveredMessage().length);
if (!pssSign.verifySignature(shortPartialSig))
{
System.out.println("short partial PSS sig verification failed.");
}
byte[] mm = pssSign.getRecoveredMessage();
if (!Arrays.equals(recovered, mm))
{
System.out.println("short partial PSS recovery failed");
}
}
private void doFullMessageTest()
throws Exception
{
BigInteger modulus = new BigInteger(1, Hex.decode("CDCBDABBF93BE8E8294E32B055256BBD0397735189BF75816341BB0D488D05D627991221DF7D59835C76A4BB4808ADEEB779E7794504E956ADC2A661B46904CDC71337DD29DDDD454124EF79CFDD7BC2C21952573CEFBA485CC38C6BD2428809B5A31A898A6B5648CAA4ED678D9743B589134B7187478996300EDBA16271A861"));
BigInteger pubExp = new BigInteger(1, Hex.decode("010001"));
BigInteger privExp = new BigInteger(1, Hex.decode("4BA6432AD42C74AA5AFCB6DF60FD57846CBC909489994ABD9C59FE439CC6D23D6DE2F3EA65B8335E796FD7904CA37C248367997257AFBD82B26F1A30525C447A236C65E6ADE43ECAAF7283584B2570FA07B340D9C9380D88EAACFFAEEFE7F472DBC9735C3FF3A3211E8A6BBFD94456B6A33C17A2C4EC18CE6335150548ED126D"));
RSAKeyParameters pubParams = new RSAKeyParameters(false, modulus, pubExp);
RSAKeyParameters privParams = new RSAKeyParameters(true, modulus, privExp);
AsymmetricBlockCipher rsaEngine = new RSABlindedEngine();
// set challenge to all zero's for verification
byte[] challenge = new byte[8];
ISO9796d2PSSSigner pssSign = new ISO9796d2PSSSigner(new RSAEngine(), new SHA256Digest(), 20, true);
pssSign.init(true, privParams);
pssSign.update(challenge, 0, challenge.length);
byte[] sig = pssSign.generateSignature();
pssSign.init(false, pubParams);
pssSign.updateWithRecoveredMessage(sig);
if (!pssSign.verifySignature(sig))
{
System.out.println("challenge PSS sig verification failed.");
}
byte[] mm = pssSign.getRecoveredMessage();
if (!Arrays.equals(challenge, mm))
{
System.out.println("challenge partial PSS recovery failed");
}
}
}
| 7,099 | 51.205882 | 554 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/BCSignerExamples/src/main/java/gwt_crypto/PSSBlindTest.java | package gwt_crypto;
import java.math.BigInteger;
import java.util.Arrays;
import org.bouncycastle.crypto.digests.SHA1Digest;
import org.bouncycastle.crypto.engines.RSABlindingEngine;
import org.bouncycastle.crypto.engines.RSAEngine;
import org.bouncycastle.crypto.generators.RSABlindingFactorGenerator;
import org.bouncycastle.crypto.params.ParametersWithRandom;
import org.bouncycastle.crypto.params.RSABlindingParameters;
import org.bouncycastle.crypto.params.RSAKeyParameters;
import org.bouncycastle.crypto.prng.FixedSecureRandom;
import org.bouncycastle.crypto.signers.PSSSigner;
public class PSSBlindTest {
public void testSig(
int id,
RSAKeyParameters pub,
RSAKeyParameters prv,
byte[] slt,
byte[] msg,
byte[] sig)
throws Exception
{
RSABlindingFactorGenerator blindFactorGen = new RSABlindingFactorGenerator();
RSABlindingEngine blindingEngine = new RSABlindingEngine();
PSSSigner blindSigner = new PSSSigner(blindingEngine, new SHA1Digest(), 20);
PSSSigner signer = new PSSSigner(new RSAEngine(), new SHA1Digest(), 20);
blindFactorGen.init(pub);
BigInteger blindFactor = blindFactorGen.generateBlindingFactor();
RSABlindingParameters params = new RSABlindingParameters(pub, blindFactor);
// generate a blind signature
blindSigner.init(true, new ParametersWithRandom(params, new FixedSecureRandom(slt)));
blindSigner.update(msg, 0, msg.length);
byte[] blindedData = blindSigner.generateSignature();
RSAEngine signerEngine = new RSAEngine();
signerEngine.init(true, prv);
byte[] blindedSig = signerEngine.processBlock(blindedData, 0, blindedData.length);
// unblind the signature
blindingEngine.init(false, params);
byte[] s = blindingEngine.processBlock(blindedSig, 0, blindedSig.length);
//signature verification
if (!Arrays.equals(s, sig))
{
System.out.println("test " + id + " failed generation");
}
//verify signature with PSSSigner
signer.init(false, pub);
signer.update(msg, 0, msg.length);
if (!signer.verifySignature(s))
{
System.out.println("test " + id + " failed PSSSigner verification");
}
}
}
| 2,327 | 31.788732 | 91 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/BCSignerExamples/src/main/java/gwt_crypto/PSSTest.java | package gwt_crypto;
import java.util.Arrays;
import org.bouncycastle.crypto.digests.SHA1Digest;
import org.bouncycastle.crypto.engines.RSAEngine;
import org.bouncycastle.crypto.params.ParametersWithRandom;
import org.bouncycastle.crypto.params.RSAKeyParameters;
import org.bouncycastle.crypto.signers.PSSSigner;
import org.bouncycastle.util.test.FixedSecureRandom;
public class PSSTest {
public void testSig(
int id,
RSAKeyParameters pub,
RSAKeyParameters prv,
byte[] slt,
byte[] msg,
byte[] sig)
throws Exception
{
PSSSigner eng = new PSSSigner(new RSAEngine(), new SHA1Digest(), 20);
eng.init(true, new ParametersWithRandom(prv, new FixedSecureRandom(slt)));
eng.update(msg, 0, msg.length);
byte[] s = eng.generateSignature();
if (!Arrays.equals(s, sig))
{
System.out.println("test " + id + " failed generation");
}
eng.init(false, pub);
eng.update(msg, 0, msg.length);
if (!eng.verifySignature(s))
{
System.out.println("test " + id + " failed verification");
}
}
}
| 1,187 | 24.826087 | 85 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/BCSignerExamples/src/main/java/gwt_crypto/X931SignerTest.java | package gwt_crypto;
import java.math.BigInteger;
import org.bouncycastle.crypto.digests.SHA1Digest;
import org.bouncycastle.crypto.engines.RSAEngine;
import org.bouncycastle.crypto.params.RSAKeyParameters;
import org.bouncycastle.crypto.params.RSAPrivateCrtKeyParameters;
import org.bouncycastle.crypto.signers.X931Signer;
import org.bouncycastle.util.encoders.Base64;
import org.bouncycastle.util.encoders.Hex;
public class X931SignerTest {
public void shouldPassSignatureTestOne()
throws Exception
{
BigInteger n = new BigInteger("c9be1b28f8caccca65d86cc3c9bbcc13eccc059df3b80bd2292b811eff3aa0dd75e1e85c333b8e3fa9bed53bb20f5359ff4e6900c5e9a388e3a4772a583a79e2299c76582c2b27694b65e9ba22e66bfb817f8b70b22206d7d8ae488c86dbb7137c26d5eff9b33c90e6cee640630313b7a715802e15142fef498c404a8de19674974785f0f852e2d470fe85a2e54ffca9f5851f672b71df691785a5cdabe8f14aa628942147de7593b2cf962414a5b59c632c4e14f1768c0ab2e9250824beea60a3529f11bf5e070ce90a47686eb0be1086fb21f0827f55295b4a48307db0b048c05a4aec3f488c576ca6f1879d354224c7e84cbcd8e76dd217a3de54dba73c35", 16);
BigInteger e = new BigInteger("e75b1b", 16);
byte[] msg = Hex.decode("5bb0d1c0ef9b5c7af2477fe08d45523d3842a4b2db943f7033126c2a7829bacb3d2cfc6497ec91688189e81b7f8742488224ba320ce983ce9480722f2cc5bc42611f00bb6311884f660ccc244788378673532edb05284fd92e83f6f6dab406209032e6af9a33c998677933e32d6fb95fd27408940d7728f9c9c40267ca1d20ce");
byte[] sig = Hex.decode("0fe8bb8e3109a1eb7489ef35bf4c1a0780071da789c8bd226a4170538eafefdd30b732d628f0e87a0b9450051feae9754d4fb61f57862d10f0bacc4f660d13281d0cd1141c006ade5186ff7d961a4c6cd0a4b352fc1295c5afd088f80ac1f8e192ef116a010a442655fe8ff5eeacea15807906fb0f0dfa86e680d4c005872357f7ece9aa4e20b15d5f709b30f08648ecaa34f2fbf54eb6b414fa2ff6f87561f70163235e69ccb4ac82a2e46d3be214cc2ef5263b569b2d8fd839b21a9e102665105ea762bda25bb446cfd831487a6b846100dee113ae95ae64f4af22c428c87bab809541c962bb3a56d4c86588e0af4ebc7fcc66dadced311051356d3ea745f7");
RSAKeyParameters rsaPublic = new RSAKeyParameters(false, n, e);
X931Signer signer = new X931Signer(new RSAEngine(), new SHA1Digest());
signer.init(false, rsaPublic);
signer.update(msg, 0, msg.length);
if (!signer.verifySignature(sig))
{
System.out.println("RSA X931 verify test 1 failed.");
}
}
public void shouldPassSignatureTestTwo() throws Exception
{
BigInteger rsaPubMod = new BigInteger(Base64.decode("AIASoe2PQb1IP7bTyC9usjHP7FvnUMVpKW49iuFtrw/dMpYlsMMoIU2jupfifDpdFxIktSB4P+6Ymg5WjvHKTIrvQ7SR4zV4jaPTu56Ys0pZ9EDA6gb3HLjtU+8Bb1mfWM+yjKxcPDuFjwEtjGlPHg1Vq+CA9HNcMSKNn2+tW6qt"));
BigInteger rsaPubExp = new BigInteger(Base64.decode("EQ=="));
BigInteger rsaPrivMod = new BigInteger(Base64.decode("AIASoe2PQb1IP7bTyC9usjHP7FvnUMVpKW49iuFtrw/dMpYlsMMoIU2jupfifDpdFxIktSB4P+6Ymg5WjvHKTIrvQ7SR4zV4jaPTu56Ys0pZ9EDA6gb3HLjtU+8Bb1mfWM+yjKxcPDuFjwEtjGlPHg1Vq+CA9HNcMSKNn2+tW6qt"));
BigInteger rsaPrivDP = new BigInteger(Base64.decode("JXzfzG5v+HtLJIZqYMUefJfFLu8DPuJGaLD6lI3cZ0babWZ/oPGoJa5iHpX4Ul/7l3s1PFsuy1GhzCdOdlfRcQ=="));
BigInteger rsaPrivDQ = new BigInteger(Base64.decode("YNdJhw3cn0gBoVmMIFRZzflPDNthBiWy/dUMSRfJCxoZjSnr1gysZHK01HteV1YYNGcwPdr3j4FbOfri5c6DUQ=="));
BigInteger rsaPrivExp = new BigInteger(Base64.decode("DxFAOhDajr00rBjqX+7nyZ/9sHWRCCp9WEN5wCsFiWVRPtdB+NeLcou7mWXwf1Y+8xNgmmh//fPV45G2dsyBeZbXeJwB7bzx9NMEAfedchyOwjR8PYdjK3NpTLKtZlEJ6Jkh4QihrXpZMO4fKZWUm9bid3+lmiq43FwW+Hof8/E="));
BigInteger rsaPrivP = new BigInteger(Base64.decode("AJ9StyTVW+AL/1s7RBtFwZGFBgd3zctBqzzwKPda6LbtIFDznmwDCqAlIQH9X14X7UPLokCDhuAa76OnDXb1OiE="));
BigInteger rsaPrivQ = new BigInteger(Base64.decode("AM3JfD79dNJ5A3beScSzPtWxx/tSLi0QHFtkuhtSizeXdkv5FSba7lVzwEOGKHmW829bRoNxThDy4ds1IihW1w0="));
BigInteger rsaPrivQinv = new BigInteger(Base64.decode("Lt0g7wrsNsQxuDdB8q/rH8fSFeBXMGLtCIqfOec1j7FEIuYA/ACiRDgXkHa0WgN7nLXSjHoy630wC5Toq8vvUg=="));
RSAKeyParameters rsaPublic = new RSAKeyParameters(false, rsaPubMod, rsaPubExp);
RSAPrivateCrtKeyParameters rsaPrivate = new RSAPrivateCrtKeyParameters(rsaPrivMod, rsaPubExp, rsaPrivExp, rsaPrivP, rsaPrivQ, rsaPrivDP, rsaPrivDQ, rsaPrivQinv);
byte[] msg = new byte[] { 1, 6, 3, 32, 7, 43, 2, 5, 7, 78, 4, 23 };
X931Signer signer = new X931Signer(new RSAEngine(), new SHA1Digest());
signer.init(true, rsaPrivate);
signer.update(msg, 0, msg.length);
byte[] sig = signer.generateSignature();
signer = new X931Signer(new RSAEngine(), new SHA1Digest());
signer.init(false, rsaPublic);
signer.update(msg, 0, msg.length);
if (!signer.verifySignature(sig))
{
System.out.println("X9.31 Signer failed.");
}
}
}
| 4,629 | 69.151515 | 552 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/BCSignerExamples/src/main/java/iso9796_signer_verifier/Main.java | package iso9796_signer_verifier;
import java.io.File;
import java.math.BigInteger;
import java.nio.file.Files;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.interfaces.RSAKey;
import java.security.spec.PKCS8EncodedKeySpec;
import org.bouncycastle.asn1.pkcs.RSAPrivateKey;
import org.bouncycastle.crypto.Digest;
import org.bouncycastle.crypto.digests.SHA1Digest;
import org.bouncycastle.crypto.engines.RSAEngine;
import org.bouncycastle.crypto.params.RSAKeyParameters;
import org.bouncycastle.crypto.signers.ISO9796d2Signer;
public class Main {
private static String privateKeyFilename = null;
private static byte[] message = null;
public static byte[] sign() throws Exception {
RSAEngine rsa = new RSAEngine();
Digest dig = new SHA1Digest();
RSAPrivateKey privateKey = (RSAPrivateKey) getPrivate(privateKeyFilename);
BigInteger big = ((RSAKey) privateKey).getModulus();
ISO9796d2Signer eng = new ISO9796d2Signer(rsa, dig, true);
RSAKeyParameters rsaPriv = new RSAKeyParameters(true, big, privateKey.getPrivateExponent());
eng.init(true, rsaPriv);
eng.update(message[0]);
eng.update(message, 1, message.length - 1);
byte[] signature = eng.generateSignature();
return signature;
}
private static PrivateKey getPrivate(String filename) throws Exception {
byte[] keyBytes = Files.readAllBytes(new File(filename).toPath());
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePrivate(spec);
}
}
| 1,555 | 30.755102 | 94 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/BCSignerExamples/src/main/java/pattern/SignerTest.java | package pattern;
import java.math.BigInteger;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.nist.NISTObjectIdentifiers;
import org.bouncycastle.crypto.Digest;
import org.bouncycastle.crypto.digests.SHA256Digest;
import org.bouncycastle.crypto.params.RSAKeyParameters;
import org.bouncycastle.crypto.params.RSAPrivateCrtKeyParameters;
import org.bouncycastle.crypto.signers.RSADigestSigner;
import org.bouncycastle.util.encoders.Base64;
public class SignerTest {
public void testSignerGenerate() throws Exception {
BigInteger dummy = new BigInteger(Base64.decode("ABCD"));
RSAPrivateCrtKeyParameters rsaPrivate = new RSAPrivateCrtKeyParameters(dummy, dummy, dummy, dummy, dummy, dummy,
dummy, dummy);
Digest digest = new SHA256Digest();
byte[] msg = new byte[] { 1, 6, 3, 32, 7, 43, 2, 5, 7, 78, 4, 23 };
RSADigestSigner signer = new RSADigestSigner(digest);
signer.init(true, rsaPrivate);
signer.update(msg, 0, msg.length);
byte[] sign = signer.generateSignature();
}
public void testSignerVerify() throws Exception {
BigInteger dummy = new BigInteger(Base64.decode("ABCD"));
RSAKeyParameters rsaPublic = new RSAKeyParameters(false, dummy, dummy);
RSAPrivateCrtKeyParameters rsaPrivate = new RSAPrivateCrtKeyParameters(dummy, dummy, dummy, dummy, dummy, dummy,
dummy, dummy);
SHA256Digest digest = new SHA256Digest();
byte[] msg = new byte[] { 1, 6, 3, 32, 7, 43, 2, 5, 7, 78, 4, 23 };
ASN1ObjectIdentifier digOid = NISTObjectIdentifiers.id_sha256;
RSADigestSigner signer = new RSADigestSigner(digest);
signer.init(true, rsaPrivate);
signer.update(msg, 0, msg.length);
byte[] sign = signer.generateSignature();
signer = new RSADigestSigner(digest, digOid);
signer.init(false, rsaPublic);
signer.update(msg, 0, msg.length);
boolean result = signer.verifySignature(sign);
}
}
| 1,873 | 36.48 | 114 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/BCSymmetricCipherExamples/src/main/java/cbc_aes_example/CBCAESBouncyCastle.java | package cbc_aes_example;
import java.security.SecureRandom;
import java.util.Arrays;
import org.bouncycastle.crypto.DataLengthException;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.bouncycastle.crypto.engines.AESEngine;
import org.bouncycastle.crypto.modes.CBCBlockCipher;
import org.bouncycastle.crypto.paddings.BlockCipherPadding;
import org.bouncycastle.crypto.paddings.PKCS7Padding;
import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.crypto.params.ParametersWithIV;
// Copied from https://github.com/p120ph37/cbc-aes-example/
public class CBCAESBouncyCastle {
private final CBCBlockCipher cbcBlockCipher = new CBCBlockCipher(new AESEngine());
private final SecureRandom random = new SecureRandom();
private KeyParameter key;
private BlockCipherPadding bcp = new PKCS7Padding();
public void setPadding(BlockCipherPadding bcp) {
this.bcp = bcp;
}
public void setKey(byte[] key) {
this.key = new KeyParameter(key);
}
public byte[] encrypt(byte[] input)
throws DataLengthException, InvalidCipherTextException {
return processing(input, true);
}
public byte[] decrypt(byte[] input)
throws DataLengthException, InvalidCipherTextException {
return processing(input, false);
}
private byte[] processing(byte[] input, boolean encrypt)
throws DataLengthException, InvalidCipherTextException {
PaddedBufferedBlockCipher pbbc =
new PaddedBufferedBlockCipher(cbcBlockCipher, bcp);
int blockSize = cbcBlockCipher.getBlockSize();
int inputOffset = 0;
int inputLength = input.length;
int outputOffset = 0;
byte[] iv = new byte[blockSize];
if(encrypt) {
outputOffset += blockSize;
random.nextBytes(iv);
} else {
System.arraycopy(input, 0 , iv, 0, blockSize);
inputOffset += blockSize;
inputLength -= blockSize;
}
pbbc.init(encrypt, new ParametersWithIV(key, iv));
byte[] output = new byte[pbbc.getOutputSize(inputLength) + outputOffset];
if(encrypt) {
System.arraycopy(iv, 0 , output, 0, blockSize);
}
int outputLength = outputOffset + pbbc.processBytes(
input, inputOffset, inputLength, output, outputOffset);
outputLength += pbbc.doFinal(output, outputLength);
return Arrays.copyOf(output, outputLength);
}
} | 2,583 | 31.708861 | 86 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/BCSymmetricCipherExamples/src/main/java/cbc_aes_example/Main.java | package cbc_aes_example;
import java.security.SecureRandom;
import java.util.Arrays;
import org.bouncycastle.crypto.DataLengthException;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.bouncycastle.crypto.engines.AESEngine;
import org.bouncycastle.crypto.modes.CBCBlockCipher;
import org.bouncycastle.crypto.paddings.BlockCipherPadding;
import org.bouncycastle.crypto.paddings.PKCS7Padding;
import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.crypto.params.ParametersWithIV;
public class Main {
public static void main(String...args) throws DataLengthException, InvalidCipherTextException {
CBCAESBouncyCastle bc = new CBCAESBouncyCastle();
bc.setKey(new byte[15]);
bc.encrypt("test".getBytes());
bc.decrypt("test".getBytes());
}
} | 859 | 34.833333 | 96 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/BCSymmetricCipherExamples/src/main/java/gcm_aes_example/GCMAESBouncyCastle.java | package gcm_aes_example;
import java.security.SecureRandom;
import java.util.Arrays;
import org.bouncycastle.crypto.DataLengthException;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.bouncycastle.crypto.engines.AESEngine;
import org.bouncycastle.crypto.modes.CBCBlockCipher;
import org.bouncycastle.crypto.modes.GCMBlockCipher;
import org.bouncycastle.crypto.paddings.BlockCipherPadding;
import org.bouncycastle.crypto.paddings.PKCS7Padding;
import org.bouncycastle.crypto.params.AEADParameters;
import org.bouncycastle.crypto.params.KeyParameter;
public class GCMAESBouncyCastle {
private byte[] key;
public byte[] processing(byte[] input, boolean encrypt)
throws DataLengthException, InvalidCipherTextException {
byte[] nonce = new byte[16];
GCMBlockCipher cipher = new GCMBlockCipher(new AESEngine());
AEADParameters parameters = new AEADParameters(new KeyParameter(key), 0, nonce);
cipher.init(false, parameters);
byte[] out = new byte[cipher.getOutputSize(12)];
byte[] output = new byte[cipher.getOutputSize(12)];
int pos = cipher.processBytes(input, 123 , 123, output, 123);
pos += cipher.doFinal(out, pos);
return Arrays.copyOf(out, pos);
}
public byte[] processingCorrect(byte[] input, boolean encrypt)
throws DataLengthException, InvalidCipherTextException {
byte[] nonce = new byte[16];
SecureRandom secRand = new SecureRandom();
byte[] keyParam = new byte[16];
secRand.nextBytes(keyParam);
key = keyParam;
GCMBlockCipher cipher = new GCMBlockCipher(new AESEngine());
AEADParameters parameters = new AEADParameters(new KeyParameter(key), 0, nonce);
cipher.init(false, parameters);
byte[] out = new byte[cipher.getOutputSize(12)];
byte[] output = new byte[cipher.getOutputSize(12)];
int pos = cipher.processBytes(input, 123 , 123, output, 123);
pos += cipher.doFinal(out, pos);
return Arrays.copyOf(out, pos);
}
} | 2,106 | 37.309091 | 89 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/BragaCryptoBench/cryptogooduses/DHandECDH/src/main/java/example/NonAuthenticatedDH_2048.java | package example;
import java.security.*;
import java.security.spec.*;
import java.util.Arrays;
import javax.crypto.*;
import javax.crypto.spec.*;
import javax.crypto.interfaces.*;
public final class NonAuthenticatedDH_2048 {
public static void main(String argv[]) {
try {
AlgorithmParameterGenerator apg = AlgorithmParameterGenerator.getInstance("DH", "SunJCE");
apg.init(2048);
AlgorithmParameters p = apg.generateParameters();
DHParameterSpec dhps = (DHParameterSpec) p.getParameterSpec(DHParameterSpec.class);
KeyPairGenerator kpg1 = KeyPairGenerator.getInstance("DH", "SunJCE");
kpg1.initialize(dhps);
KeyPair kp1 = kpg1.generateKeyPair();
KeyAgreement ka1 = KeyAgreement.getInstance("DH", "SunJCE");
ka1.init(kp1.getPrivate());
byte[] pubKey1 = kp1.getPublic().getEncoded();
KeyFactory kf1 = KeyFactory.getInstance("DH", "SunJCE");
X509EncodedKeySpec x509ks = new X509EncodedKeySpec(pubKey1);
PublicKey apk1 = kf1.generatePublic(x509ks);
DHParameterSpec dhps2 = ((DHPublicKey) apk1).getParams();
KeyPairGenerator kpg2 = KeyPairGenerator.getInstance("DH", "SunJCE");
kpg2.initialize(dhps2);
KeyPair kp2 = kpg2.generateKeyPair();
KeyAgreement ka2 = KeyAgreement.getInstance("DH", "SunJCE");
ka2.init(kp2.getPrivate());
byte[] pubKey2 = kp2.getPublic().getEncoded();
KeyFactory kf2 = KeyFactory.getInstance("DH", "SunJCE");
x509ks = new X509EncodedKeySpec(pubKey2);
PublicKey apk2 = kf2.generatePublic(x509ks);
ka1.doPhase(apk2, true);
byte[] secretKey1 = ka1.generateSecret();
ka2.doPhase(apk1, true);
byte[] secretKey2 = ka2.generateSecret();
if (!Arrays.equals(secretKey1, secretKey2)) {
throw new Exception("Shared secrets differ");
}
} catch (Exception e) {}
}
}
| 1,782 | 29.220339 | 93 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/BragaCryptoBench/cryptogooduses/DHandECDH/src/main/java/example/NonAuthenticatedEphemeralDH_2048.java | package example;
import java.security.*;
import java.security.spec.*;
import java.util.Arrays;
import javax.crypto.*;
public final class NonAuthenticatedEphemeralDH_2048 {
public static void main(String argv[]) {
try {
KeyPairGenerator kpg1 = KeyPairGenerator.getInstance("DH", "SunJCE");
kpg1.initialize(2048);
KeyPair kp1 = kpg1.generateKeyPair();
KeyAgreement ka1 = KeyAgreement.getInstance("DH", "SunJCE");
ka1.init(kp1.getPrivate());
byte[] publicKey1 = kp1.getPublic().getEncoded();
KeyFactory kf1 = KeyFactory.getInstance("DH", "SunJCE");
X509EncodedKeySpec x509ks = new X509EncodedKeySpec(publicKey1);
PublicKey apk1 = kf1.generatePublic(x509ks);
KeyPairGenerator kpg2 = KeyPairGenerator.getInstance("DH", "SunJCE");
kpg2.initialize(2048);
KeyPair kp2 = kpg2.generateKeyPair();
KeyAgreement ka2 = KeyAgreement.getInstance("DH", "SunJCE");
ka2.init(kp2.getPrivate());
byte[] publicKey2 = kp2.getPublic().getEncoded();
KeyFactory kf2 = KeyFactory.getInstance("DH", "SunJCE");
x509ks = new X509EncodedKeySpec(publicKey2);
PublicKey apk2 = kf2.generatePublic(x509ks);
ka1.doPhase(apk2, true);
byte[] genSecret1 = ka1.generateSecret();
ka2.doPhase(apk1, true);
byte[] genSecret2 = ka2.generateSecret();
if (!Arrays.equals(genSecret1, genSecret2)) {
throw new Exception("Shared secrets differ");
}
} catch (Exception e) {}
}
}
| 1,421 | 29.255319 | 72 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/BragaCryptoBench/cryptogooduses/DHandECDH/src/main/java/example/NonAuthenticatedEphemeralECDH_128.java | package example;
import java.security.*;
import java.security.spec.*;
import java.util.Arrays;
import javax.crypto.*;
public final class NonAuthenticatedEphemeralECDH_128 {
public static void main(String argv[]) {
try {
KeyPairGenerator kpg1 = KeyPairGenerator.getInstance("EC", "SunEC");
kpg1.initialize(256);
KeyPair kp1 = kpg1.generateKeyPair();
KeyAgreement ka1 = KeyAgreement.getInstance("ECDH", "SunEC");
ka1.init(kp1.getPrivate());
byte[] pubKey1 = kp1.getPublic().getEncoded();
KeyFactory kf1 = KeyFactory.getInstance("EC", "SunEC");
X509EncodedKeySpec x509ks = new X509EncodedKeySpec(pubKey1);
PublicKey apk1 = kf1.generatePublic(x509ks);
KeyPairGenerator kpg2 = KeyPairGenerator.getInstance("EC", "SunEC");
kpg2.initialize(256);
KeyPair kp2 = kpg2.generateKeyPair();
KeyAgreement ka2 = KeyAgreement.getInstance("ECDH", "SunEC");
ka2.init(kp2.getPrivate());
byte[] pubKey2 = kp2.getPublic().getEncoded();
KeyFactory kf2 = KeyFactory.getInstance("EC", "SunEC");
x509ks = new X509EncodedKeySpec(pubKey2);
PublicKey apk2 = kf2.generatePublic(x509ks);
ka1.doPhase(apk2, true);
byte[] genSecret1 = ka1.generateSecret();
ka2.doPhase(apk1, true);
byte[] genSecret2 = ka2.generateSecret();
if (!Arrays.equals(genSecret1, genSecret2)) {
throw new Exception("Shared secrets differ");
}
} catch (Exception e) {
}
}
}
| 1,409 | 28.375 | 71 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/BragaCryptoBench/cryptogooduses/DHandECDH/src/main/java/example/NonAuthenticatedEphemeralECDH_192.java | package example;
import java.security.*;
import java.security.spec.*;
import java.util.Arrays;
import javax.crypto.*;
public final class NonAuthenticatedEphemeralECDH_192 {
public static void main(String argv[]) {
try {
KeyPairGenerator kpg1 = KeyPairGenerator.getInstance("EC", "SunEC");
kpg1.initialize(384);
KeyPair kp1 = kpg1.generateKeyPair();
KeyAgreement ka1 = KeyAgreement.getInstance("ECDH", "SunEC");
ka1.init(kp1.getPrivate());
byte[] pubKey1 = kp1.getPublic().getEncoded();
KeyFactory kf1 = KeyFactory.getInstance("EC", "SunEC");
X509EncodedKeySpec x509ks = new X509EncodedKeySpec(pubKey1);
PublicKey apk1 = kf1.generatePublic(x509ks);
KeyPairGenerator kpg2 = KeyPairGenerator.getInstance("EC", "SunEC");
kpg2.initialize(384);
KeyPair kp2 = kpg2.generateKeyPair();
KeyAgreement ka2 = KeyAgreement.getInstance("ECDH", "SunEC");
ka2.init(kp2.getPrivate());
byte[] pubKey2 = kp2.getPublic().getEncoded();
KeyFactory kf2 = KeyFactory.getInstance("EC", "SunEC");
x509ks = new X509EncodedKeySpec(pubKey2);
PublicKey apk2 = kf2.generatePublic(x509ks);
ka1.doPhase(apk2, true);
byte[] genSecret1 = ka1.generateSecret();
ka2.doPhase(apk1, true);
byte[] genSecret2 = ka2.generateSecret();
if (!Arrays.equals(genSecret1, genSecret2)) {
throw new Exception("Shared secrets differ");
}
} catch (Exception e) {
}
}
}
| 1,409 | 28.375 | 71 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/BragaCryptoBench/cryptogooduses/DHandECDH/src/main/java/example/NonAuthenticatedEphemeralECDH_256.java | package example;
import java.security.*;
import java.security.spec.*;
import java.util.Arrays;
import javax.crypto.*;
public final class NonAuthenticatedEphemeralECDH_256 {
public static void main(String argv[]) {
try {
KeyPairGenerator kpg1 = KeyPairGenerator.getInstance("EC", "SunEC");
kpg1.initialize(521);
KeyPair kp1 = kpg1.generateKeyPair();
KeyAgreement ka1 = KeyAgreement.getInstance("ECDH", "SunEC");
ka1.init(kp1.getPrivate());
byte[] pubKey1 = kp1.getPublic().getEncoded();
KeyFactory kf1 = KeyFactory.getInstance("EC", "SunEC");
X509EncodedKeySpec x509ks = new X509EncodedKeySpec(pubKey1);
PublicKey apk1 = kf1.generatePublic(x509ks);
KeyPairGenerator kpg2 = KeyPairGenerator.getInstance("EC", "SunEC");
kpg2.initialize(521);
KeyPair kp2 = kpg2.generateKeyPair();
KeyAgreement ka2 = KeyAgreement.getInstance("ECDH", "SunEC");
ka2.init(kp2.getPrivate());
byte[] pubKey2 = kp2.getPublic().getEncoded();
KeyFactory kf2 = KeyFactory.getInstance("EC", "SunEC");
x509ks = new X509EncodedKeySpec(pubKey2);
PublicKey apk2 = kf2.generatePublic(x509ks);
ka1.doPhase(apk2, true);
byte[] genSecret1 = ka1.generateSecret();
ka2.doPhase(apk1, true);
byte[] genSecret2 = ka2.generateSecret();
if (!Arrays.equals(genSecret1, genSecret2)) {
throw new Exception("Shared secrets differ");
}
} catch (Exception e) {
}
}
}
| 1,409 | 28.375 | 71 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/BragaCryptoBench/cryptogooduses/alwaysDefineCSP/src/main/java/example/DefinedProvider1.java | package example;
import java.security.KeyPairGenerator;
import java.security.Signature;
public final class DefinedProvider1 {
public static void main(String[] args) throws Exception {
KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA","SUN");
Signature signerA = Signature.getInstance("SHA256WithDSA","SUN");
Signature verifierB = Signature.getInstance("SHA256WithDSA","SUN");
}
}
| 433 | 26.125 | 75 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/BragaCryptoBench/cryptogooduses/alwaysDefineCSP/src/main/java/example/DefinedProvider2.java | package example;
import java.security.KeyPairGenerator;
import java.security.Signature;
public final class DefinedProvider2 {
public static void main(String[] args) throws Exception {
KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC","SunEC");
Signature signerA = Signature.getInstance("SHA512WithECDSA","SunEC");
Signature verifierB = Signature.getInstance("SHA512WithECDSA","SunEC");
}
}
| 442 | 26.6875 | 79 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/BragaCryptoBench/cryptogooduses/alwaysDefineCSP/src/main/java/example/DefinedProvider3.java | package example;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
public final class DefinedProvider3 {
public static void main(String[] args) {
try {
SecureRandom r1 = SecureRandom.getInstance("SHA1PRNG","SUN");
SecureRandom r2 = SecureRandom.getInstanceStrong();
r1.setSeed(r2.nextLong());
}
catch (NoSuchAlgorithmException | NoSuchProviderException e) {}
}
}
| 486 | 24.631579 | 70 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/BragaCryptoBench/cryptogooduses/alwaysDefineCSP/src/main/java/example/DefinedProvider4.java | package example;
import java.security.*;
import javax.crypto.*;
public final class DefinedProvider4 {
public static void main(String argv[]) {
try {
KeyPairGenerator kpg1 = KeyPairGenerator.getInstance("DH","SunJCE");
KeyAgreement ka1 = KeyAgreement.getInstance("DH","SunJCE");
KeyFactory kf1 = KeyFactory.getInstance("DH","SunJCE");
KeyPairGenerator kpg2 = KeyPairGenerator.getInstance("DH","SunJCE");
KeyAgreement ka2 = KeyAgreement.getInstance("DH","SunJCE");
KeyFactory kf2 = KeyFactory.getInstance("DH","SunJCE");
} catch (NoSuchAlgorithmException | NoSuchProviderException e) {}
}
}
| 714 | 33.047619 | 80 | java |