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/CryptoAnalysisTargets/CryptoGuardExamples/brokenhash/src/main/java/example/brokenhash/BrokenHashABICase1.java | package example.brokenhash;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class BrokenHashABICase1 {
public static void main (String [] args) throws NoSuchAlgorithmException {
String str = "abcdef";
String crypto = "SHA1";
go(str,crypto);
}
public static void go (String str, String crypto) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance(crypto);
md.update(str.getBytes());
System.out.println(md.digest());
}
}
| 553 | 29.777778 | 87 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/CryptoGuardExamples/brokenhash/src/main/java/example/brokenhash/BrokenHashABICase5.java | package example.brokenhash;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class BrokenHashABICase5 {
public static final String DEFAULT_CRYPTO = "SHA1";
private static char[] CRYPTO;
private static char[] crypto;
public static void main (String [] args) throws NoSuchAlgorithmException {
String str = "abcdef";
go2();
go3();
go(str);
}
private static void go2(){
CRYPTO = DEFAULT_CRYPTO.toCharArray();
}
private static void go3(){
crypto = CRYPTO;
}
public static void go (String str) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance(String.valueOf(crypto));
md.update(str.getBytes());
System.out.println(md.digest());
}
}
| 817 | 26.266667 | 78 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/CryptoGuardExamples/brokenhash/src/main/java/example/brokenhash/BrokenHashBBCase2.java | package example.brokenhash;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class BrokenHashBBCase2 {
public static void main (String [] args) throws NoSuchAlgorithmException {
String name = "abcdef";
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(name.getBytes());
System.out.println(md.digest());
}
}
| 403 | 27.857143 | 78 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/CryptoGuardExamples/ecbcrypto/src/main/java/example/ecbcrypto/EcbInSymmCryptoABICase1.java | package example.ecbcrypto;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
public class EcbInSymmCryptoABICase1 {
public void go(String crypto) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException {
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
SecretKey key = keyGen.generateKey();
Cipher cipher = Cipher.getInstance(crypto);
cipher.init(Cipher.ENCRYPT_MODE, key);
}
public static void main (String [] args) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException {
EcbInSymmCryptoABICase1 bc = new EcbInSymmCryptoABICase1();
String crypto = "AES/ECB/PKCS5Padding";
bc.go(crypto);
}
}
| 893 | 36.25 | 123 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/CryptoGuardExamples/ecbcrypto/src/main/java/example/ecbcrypto/EcbInSymmCryptoABICase2.java | package example.ecbcrypto;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
public class EcbInSymmCryptoABICase2 {
public static final String DEFAULT_CRYPTO = "AES/ECB/PKCS5Padding";
private static char[] CRYPTO;
private static char[] crypto;
public void go() throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException {
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
SecretKey key = keyGen.generateKey();
Cipher cipher = Cipher.getInstance(String.valueOf(crypto));
cipher.init(Cipher.ENCRYPT_MODE, key);
}
private static void go2(){
CRYPTO = DEFAULT_CRYPTO.toCharArray();
}
private static void go3(){
crypto = CRYPTO;
}
public static void main (String [] args) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException {
EcbInSymmCryptoABICase2 bc = new EcbInSymmCryptoABICase2();
go2();
go3();
bc.go();
}
}
| 1,158 | 33.088235 | 123 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/CryptoGuardExamples/ecbcrypto/src/main/java/example/ecbcrypto/EcbInSymmCryptoBBCase1.java | package example.ecbcrypto;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
public class EcbInSymmCryptoBBCase1 {
public void go() throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException {
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
SecretKey key = keyGen.generateKey();
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key);
}
public static void main (String [] args) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException {
EcbInSymmCryptoBBCase1 bc = new EcbInSymmCryptoBBCase1();
bc.go();
}
}
| 840 | 34.041667 | 123 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/CryptoGuardExamples/ecbcrypto/src/main/java/example/ecbcrypto/EcbInSymmCryptoCorrected.java | package example.ecbcrypto;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
public class EcbInSymmCryptoCorrected {
public void go() throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException {
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
SecretKey key = keyGen.generateKey();
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key);
}
public static void main (String [] args) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException {
EcbInSymmCryptoCorrected bc = new EcbInSymmCryptoCorrected();
bc.go();
}
}
| 845 | 35.782609 | 123 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/CryptoGuardExamples/insecureasymmetriccrypto/src/main/java/example/insecureasymmetriccrypto/InsecureAsymmetricCipherABICase1.java | package example.insecureasymmetriccrypto;
import javax.crypto.*;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
public class InsecureAsymmetricCipherABICase1 {
public void go(KeyPairGenerator kgp, KeyPair kp) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IOException, IllegalBlockSizeException, BadPaddingException, ClassNotFoundException {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, kp.getPublic());
//encrypting
String myMessage = new String("Secret Message");
SealedObject encryptedMessage = new SealedObject(myMessage,cipher);
//decrypting
Cipher dec = Cipher.getInstance("RSA");
dec.init(Cipher.DECRYPT_MODE, kp.getPrivate());
String message = (String) encryptedMessage.getObject(dec);
System.out.println(message);
}
public static void main (String [] args) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, IOException, IllegalBlockSizeException, BadPaddingException, ClassNotFoundException {
InsecureAsymmetricCipherABICase1 bc = new InsecureAsymmetricCipherABICase1();
KeyPairGenerator kgp = KeyPairGenerator.getInstance("RSA");
//kgp.initialize(1024);
KeyPair kp = kgp.generateKeyPair();
bc.go(kgp,kp);
}
}
| 1,491 | 40.444444 | 216 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/CryptoGuardExamples/insecureasymmetriccrypto/src/main/java/example/insecureasymmetriccrypto/InsecureAsymmetricCipherABICase2.java | package example.insecureasymmetriccrypto;
import javax.crypto.*;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
public class InsecureAsymmetricCipherABICase2 {
public static final String DEFAULT_KEY_SIZE = "1024";
private static char[] KEY_SIZE;
private static char[] keysize;
public void go(KeyPairGenerator kgp, KeyPair kp) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IOException, IllegalBlockSizeException, BadPaddingException, ClassNotFoundException {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, kp.getPublic());
//encrypting
String myMessage = new String("Secret Message");
SealedObject encryptedMessage = new SealedObject(myMessage,cipher);
//decrypting
Cipher dec = Cipher.getInstance("RSA");
dec.init(Cipher.DECRYPT_MODE, kp.getPrivate());
String message = (String) encryptedMessage.getObject(dec);
System.out.println(message);
}
private static void go2(){
KEY_SIZE = DEFAULT_KEY_SIZE.toCharArray();
}
private static void go3(){
keysize = KEY_SIZE;
}
public static void main (String [] args) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, IOException, IllegalBlockSizeException, BadPaddingException, ClassNotFoundException {
InsecureAsymmetricCipherABICase2 bc = new InsecureAsymmetricCipherABICase2();
go2();
go3();
KeyPairGenerator kgp = KeyPairGenerator.getInstance("RSA");
kgp.initialize(Integer.parseInt(String.valueOf(keysize)));
KeyPair kp = kgp.generateKeyPair();
bc.go(kgp,kp);
}
}
| 1,839 | 37.333333 | 216 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/CryptoGuardExamples/insecureasymmetriccrypto/src/main/java/example/insecureasymmetriccrypto/InsecureAsymmetricCipherBBCase1.java | package example.insecureasymmetriccrypto;
import javax.crypto.*;
import java.io.IOException;
import java.security.*;
public class InsecureAsymmetricCipherBBCase1 {
public void go() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IOException, IllegalBlockSizeException, BadPaddingException, ClassNotFoundException {
KeyPairGenerator kgp = KeyPairGenerator.getInstance("RSA");
int keysize = 1024;
kgp.initialize(keysize);
KeyPair kp = kgp.generateKeyPair();
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, kp.getPublic());
//encrypting
String myMessage = new String("Secret Message");
SealedObject encryptedMessage = new SealedObject(myMessage,cipher);
//decrypting
Cipher dec = Cipher.getInstance("RSA");
dec.init(Cipher.DECRYPT_MODE, kp.getPrivate());
String message = (String) encryptedMessage.getObject(dec);
System.out.println(message);
}
public static void main (String [] args) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, IOException, IllegalBlockSizeException, BadPaddingException, ClassNotFoundException {
InsecureAsymmetricCipherBBCase1 bc = new InsecureAsymmetricCipherBBCase1();
bc.go();
}
}
| 1,346 | 37.485714 | 208 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/CryptoGuardExamples/pbeiteration/src/main/java/example/pbeiteration/LessThan1000IterationPBEABHCase1.java | package example.pbeiteration;
import javax.crypto.spec.PBEParameterSpec;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.Map;
public class LessThan1000IterationPBEABHCase1 {
public static void main(){
LessThan1000IterationPBEABHCase1 lt = new LessThan1000IterationPBEABHCase1();
lt.key2();
}
public void key2(){
String name = "abcdef";
Map<String,Integer> hm = new HashMap<String, Integer>();
hm.put("aaa", new Integer(1020));
hm.put("bbb", new Integer(20));
int iteration = hm.get("bbb");
SecureRandom random = new SecureRandom();
PBEParameterSpec pbeParamSpec = null;
byte[] salt = new byte[32];
random.nextBytes(salt);
//int count = 20;
pbeParamSpec = new PBEParameterSpec(salt, iteration);
}
}
| 853 | 27.466667 | 85 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/CryptoGuardExamples/pbeiteration/src/main/java/example/pbeiteration/LessThan1000IterationPBEABICase1.java | package example.pbeiteration;
import javax.crypto.spec.PBEParameterSpec;
import java.security.SecureRandom;
public class LessThan1000IterationPBEABICase1 {
public static void main(){
LessThan1000IterationPBEABICase1 lt = new LessThan1000IterationPBEABICase1();
int count = 20;
lt.key2(count);
}
public void key2(int count){
SecureRandom random = new SecureRandom();
PBEParameterSpec pbeParamSpec = null;
byte[] salt = new byte[32];
random.nextBytes(salt);
pbeParamSpec = new PBEParameterSpec(salt, count);
}
}
| 594 | 26.045455 | 85 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/CryptoGuardExamples/pbeiteration/src/main/java/example/pbeiteration/LessThan1000IterationPBEABICase2.java | package example.pbeiteration;
import javax.crypto.spec.PBEParameterSpec;
import java.security.SecureRandom;
public class LessThan1000IterationPBEABICase2 {
public static final String DEFAULT_COUNT = "20";
private static char[] COUNT;
private static char[] count;
public static void main(){
LessThan1000IterationPBEABICase2 lt = new LessThan1000IterationPBEABICase2();
go2();
go3();
lt.key2();
}
private static void go2(){
COUNT = DEFAULT_COUNT.toCharArray();
}
private static void go3(){
count = COUNT;
}
public void key2(){
SecureRandom random = new SecureRandom();
PBEParameterSpec pbeParamSpec = null;
byte[] salt = new byte[32];
random.nextBytes(salt);
pbeParamSpec = new PBEParameterSpec(salt, Integer.parseInt(String.valueOf(count)));
}
}
| 880 | 27.419355 | 91 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/CryptoGuardExamples/pbeiteration/src/main/java/example/pbeiteration/LessThan1000IterationPBEBBCase1.java | package example.pbeiteration;
import javax.crypto.spec.PBEParameterSpec;
import java.security.SecureRandom;
public class LessThan1000IterationPBEBBCase1 {
public static void main(){
LessThan1000IterationPBEBBCase1 lt = new LessThan1000IterationPBEBBCase1();
lt.key2();
}
public void key2(){
SecureRandom random = new SecureRandom();
PBEParameterSpec pbeParamSpec = null;
byte[] salt = new byte[32];
random.nextBytes(salt);
int count = 20;
pbeParamSpec = new PBEParameterSpec(salt, count);
}
}
| 575 | 27.8 | 83 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/CryptoGuardExamples/predictablecryptographickey/src/main/java/example/predictablecryptographickey/PredictableCryptographicKeyABHCase1.java | package example.predictablecryptographickey;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.SecureRandom;
import java.util.Arrays;
public class PredictableCryptographicKeyABHCase1 {
public static void main(String [] args) throws UnsupportedEncodingException {
SecureRandom random = new SecureRandom();
String defaultKey = String.valueOf(random.ints());
byte [] keyBytes = defaultKey.getBytes("UTF-8");
keyBytes = Arrays.copyOf(keyBytes,16);
SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
}
}
| 615 | 33.222222 | 81 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/CryptoGuardExamples/predictablecryptographickey/src/main/java/example/predictablecryptographickey/PredictableCryptographicKeyABHCase2.java | package example.predictablecryptographickey;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class PredictableCryptographicKeyABHCase2 {
public static void main(String [] args) throws UnsupportedEncodingException {
Map<String,String> hm = new HashMap<String, String>();
hm.put("aaa", "afix");
hm.put("bbb", "bfix");
hm.put("ccc", "cfix");
hm.put("ddd", "dfix");
String key = hm.get("aaa");
byte [] keyBytes = key.getBytes();
keyBytes = Arrays.copyOf(keyBytes,16);
SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
}
}
| 730 | 28.24 | 81 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/CryptoGuardExamples/predictablecryptographickey/src/main/java/example/predictablecryptographickey/PredictableCryptographicKeyABICase1.java | package example.predictablecryptographickey;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Arrays;
public class PredictableCryptographicKeyABICase1 {
public static void main(String [] args){
String key = "defaultkey";
go(key);
}
private static void go(String key) {
byte[] keyBytes = key.getBytes();
keyBytes = Arrays.copyOf(keyBytes,16);
SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
}
}
| 501 | 25.421053 | 67 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/CryptoGuardExamples/predictablecryptographickey/src/main/java/example/predictablecryptographickey/PredictableCryptographicKeyABICase2.java | package example.predictablecryptographickey;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;
import java.util.Arrays;
public class PredictableCryptographicKeyABICase2 {
public static final String DEFAULT_ENCRYPT_KEY = "defaultkey";
private static char[] ENCRYPT_KEY;
private static char[] encryptKey;
public static void main(String [] args){
go2();
go3();
go();
}
private static void go2(){
ENCRYPT_KEY = DEFAULT_ENCRYPT_KEY.toCharArray();
}
private static void go3(){
encryptKey = ENCRYPT_KEY;
}
private static void go() {
byte[] keyBytes = encryptKey.toString().getBytes();
keyBytes = Arrays.copyOf(keyBytes,16);
SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
}
}
| 818 | 26.3 | 67 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/CryptoGuardExamples/predictablecryptographickey/src/main/java/example/predictablecryptographickey/PredictableCryptographicKeyBBCase1.java | package example.predictablecryptographickey;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;
import java.util.Arrays;
public class PredictableCryptographicKeyBBCase1 {
public static void main(String [] args){
String defaultKey = "defaultkey";
byte[] keyBytes = defaultKey.getBytes();
keyBytes = Arrays.copyOf(keyBytes,16);
SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
}
}
| 456 | 29.466667 | 67 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/CryptoGuardExamples/predictablekeystorepassword/src/main/java/example/predictablekeystorepassword/PredictableKeyStorePasswordABICase1.java | package example.predictablekeystorepassword;
import java.io.IOException;
import java.net.URL;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
public class PredictableKeyStorePasswordABICase1 {
URL cacerts;
public static void main(String args[]) throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException {
PredictableKeyStorePasswordABICase1 pksp = new PredictableKeyStorePasswordABICase1();
String key = "changeit";
pksp.go(key);
}
public void go(String key) throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException {
String type = "JKS";
KeyStore ks = KeyStore.getInstance(type);
cacerts = new URL("https://www.google.com");
ks.load(cacerts.openStream(), key.toCharArray());
}
}
| 934 | 36.4 | 130 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/CryptoGuardExamples/predictablepbepassword/src/main/java/example/predictablepbepassword/PredictablePBEPasswordABHCase2.java | package example.predictablepbepassword;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.Map;
public class PredictablePBEPasswordABHCase2 {
private PBEKeySpec pbeKeySpec = null;
private PBEParameterSpec pbeParamSpec = null;
public static void main(String [] args){
PredictablePBEPasswordABHCase2 ckp = new PredictablePBEPasswordABHCase2();
Map<String,String> hm = new HashMap<String, String>();
hm.put("aaa", "afix");
hm.put("bbb", "bfix");
hm.put("ccc", "cfix");
hm.put("ddd", "dfix");
String key = hm.get("aaa");
ckp.key(key);
}
public void key(String key) {
byte [] salt = new byte[16];
SecureRandom sr = new SecureRandom();
sr.nextBytes(salt);
int iterationCount = 11010;
int keyLength = 16;
pbeKeySpec = new PBEKeySpec(key.toCharArray(),salt,iterationCount,keyLength);
}
}
| 1,027 | 30.151515 | 85 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/CryptoGuardExamples/predictablepbepassword/src/main/java/example/predictablepbepassword/PredictablePBEPasswordABICase1.java | package example.predictablepbepassword;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import java.security.SecureRandom;
public class PredictablePBEPasswordABICase1 {
private PBEKeySpec pbeKeySpec = null;
private PBEParameterSpec pbeParamSpec = null;
public static void main(String [] args){
PredictablePBEPasswordABICase1 ckp = new PredictablePBEPasswordABICase1();
String password = "sagar";
ckp.key(password);
}
public void key(String password) {
byte [] salt = new byte[16];
SecureRandom sr = new SecureRandom();
sr.nextBytes(salt);
int iterationCount = 11010;
int keyLength = 16;
pbeKeySpec = new PBEKeySpec(password.toCharArray(),salt,iterationCount,keyLength);
}
}
| 807 | 28.925926 | 90 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/CryptoGuardExamples/predictablepbepassword/src/main/java/example/predictablepbepassword/PredictablePBEPasswordBBCase2.java | package example.predictablepbepassword;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import java.security.SecureRandom;
public class PredictablePBEPasswordBBCase2 {
private PBEKeySpec pbeKeySpec = null;
private PBEParameterSpec pbeParamSpec = null;
public static void main(String [] args){
PredictablePBEPasswordBBCase2 ckp = new PredictablePBEPasswordBBCase2();
ckp.key();
}
public void key() {
char [] defaultKey = {'s'};
byte [] salt = new byte[16];
SecureRandom sr = new SecureRandom();
sr.nextBytes(salt);
int iterationCount = 11010;
int keyLength = 16;
pbeKeySpec = new PBEKeySpec(defaultKey,salt,iterationCount,keyLength);
}
}
| 768 | 29.76 | 80 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/CryptoGuardExamples/staticinitializationvector/src/main/java/example/staticinitializationvector/StaticInitializationVectorABHCase1.java | package example.staticinitializationvector;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
public class StaticInitializationVectorABHCase1 {
public void go() throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, InvalidAlgorithmParameterException, UnsupportedEncodingException {
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
SecretKey key = keyGen.generateKey();
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte [] bytes = "abcde".getBytes("UTF-8");
IvParameterSpec ivSpec = new IvParameterSpec(bytes);
cipher.init(Cipher.ENCRYPT_MODE,key,ivSpec);
}
public static void main (String [] args) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, InvalidAlgorithmParameterException, UnsupportedEncodingException {
StaticInitializationVectorABHCase1 siv = new StaticInitializationVectorABHCase1();
siv.go();
}
}
| 1,291 | 40.677419 | 189 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/CryptoGuardExamples/staticinitializationvector/src/main/java/example/staticinitializationvector/StaticInitializationVectorABHCase2.java | package example.staticinitializationvector;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
public class StaticInitializationVectorABHCase2 {
public void go() throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, InvalidAlgorithmParameterException {
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
SecretKey key = keyGen.generateKey();
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
String name = "abcdef";
Map<String,String> hm = new HashMap<String, String>();
hm.put("aaa", "abcde");
hm.put("bbb", "fghij");
hm.put("ccc", "klmno");
hm.put("ddd", "pqrst");
String str = hm.get("aaa");
byte [] bytes = str.getBytes();
IvParameterSpec ivSpec = new IvParameterSpec(bytes);
cipher.init(Cipher.ENCRYPT_MODE,key,ivSpec);
}
public static void main (String [] args) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, InvalidAlgorithmParameterException {
StaticInitializationVectorABHCase2 siv = new StaticInitializationVectorABHCase2();
siv.go();
}
}
| 1,484 | 35.219512 | 159 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/CryptoGuardExamples/staticinitializationvector/src/main/java/example/staticinitializationvector/StaticInitializationVectorABICase1.java | package example.staticinitializationvector;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import java.security.*;
public class StaticInitializationVectorABICase1 {
public void go(IvParameterSpec ivSpec) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, InvalidAlgorithmParameterException {
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
SecretKey key = keyGen.generateKey();
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE,key,ivSpec);
}
public static void main (String [] args) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, InvalidAlgorithmParameterException {
StaticInitializationVectorABICase1 siv = new StaticInitializationVectorABICase1();
byte [] bytes = "abcde".getBytes();
IvParameterSpec ivSpec = new IvParameterSpec(bytes);
siv.go(ivSpec);
}
}
| 1,083 | 40.692308 | 159 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/CryptoGuardExamples/staticinitializationvector/src/main/java/example/staticinitializationvector/StaticInitializationVectorABICase2.java | package example.staticinitializationvector;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
public class StaticInitializationVectorABICase2 {
public static final String DEFAULT_INITIALIZATION = "abcde";
private static char[] INITIALIZATION;
private static char[] initialization;
public void go(IvParameterSpec ivSpec) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, InvalidAlgorithmParameterException {
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
SecretKey key = keyGen.generateKey();
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE,key,ivSpec);
}
private static void go2(){
INITIALIZATION = DEFAULT_INITIALIZATION.toCharArray();
}
private static void go3(){
initialization = INITIALIZATION;
}
public static void main (String [] args) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, InvalidAlgorithmParameterException {
StaticInitializationVectorABICase2 siv = new StaticInitializationVectorABICase2();
go2();
go3();
IvParameterSpec ivSpec = new IvParameterSpec(new byte[]{Byte.parseByte(String.valueOf(initialization))});
siv.go(ivSpec);
}
}
| 1,571 | 40.368421 | 159 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/CryptoGuardExamples/staticinitializationvector/src/main/java/example/staticinitializationvector/StaticInitializationVectorBBCase1.java | package example.staticinitializationvector;
import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
public class StaticInitializationVectorBBCase1 {
public void go() throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, InvalidAlgorithmParameterException {
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
SecretKey key = keyGen.generateKey();
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte [] bytes = "abcde".getBytes();
IvParameterSpec ivSpec = new IvParameterSpec(bytes);
cipher.init(Cipher.ENCRYPT_MODE,key,ivSpec);
}
public static void main (String [] args) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, InvalidAlgorithmParameterException {
StaticInitializationVectorBBCase1 siv = new StaticInitializationVectorBBCase1();
siv.go();
}
}
| 1,063 | 37 | 159 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/CryptoGuardExamples/staticsalts/src/main/java/example/staticsalts/StaticSaltsABHCase1.java | package example.staticsalts;
import javax.crypto.spec.PBEParameterSpec;
import java.util.HashMap;
import java.util.Map;
public class StaticSaltsABHCase1 {
public static void main (String [] args){
StaticSaltsABHCase1 cs = new StaticSaltsABHCase1();
cs.key2();
}
public void key2(){
Map<String,Byte> hm = new HashMap<String, Byte>();
hm.put("aaa", new Byte((byte) 0xa2));
hm.put("bbb", new Byte((byte) 0xa4));
hm.put("ccc", new Byte((byte) 0xa6));
hm.put("ddd", new Byte((byte) 0xa8));
byte b = hm.get("aaa");
PBEParameterSpec pbeParamSpec = null;
byte[] salt = {b,b};
int count = 1020;
pbeParamSpec = new PBEParameterSpec(salt, count);
}
}
| 757 | 26.071429 | 59 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/CryptoGuardExamples/staticsalts/src/main/java/example/staticsalts/StaticSaltsABICase2.java | package example.staticsalts;
import javax.crypto.spec.PBEParameterSpec;
public class StaticSaltsABICase2 {
public static final String DEFAULT_SALT = "12345";
private static char[] SALT;
private static char[] salt;
public static void main(String [] args){
StaticSaltsABICase2 cs = new StaticSaltsABICase2();
int count = 1020;
go2();
go3();
cs.key2(count);
}
private static void go2(){
SALT = DEFAULT_SALT.toCharArray();
}
private static void go3(){
salt = SALT;
}
public void key2(int count){
PBEParameterSpec pbeParamSpec = null;
pbeParamSpec = new PBEParameterSpec(new byte[]{Byte.parseByte(salt.toString())}, count);
}
}
| 745 | 23.064516 | 96 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/CryptoGuardExamples/staticsalts/src/main/java/example/staticsalts/StaticSaltsBBCase1.java | package example.staticsalts;
import javax.crypto.spec.PBEParameterSpec;
public class StaticSaltsBBCase1 {
public static void main (String [] args){
StaticSaltsBBCase1 cs = new StaticSaltsBBCase1();
cs.key2();
}
public void key2(){
PBEParameterSpec pbeParamSpec = null;
byte[] salt = {(byte) 0xa2};
int count = 1020;
pbeParamSpec = new PBEParameterSpec(salt, count);
}
}
| 437 | 23.333333 | 57 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/CryptoMisuseExamples/src/main/java/main/Encrypt.java | package main;
import java.math.BigInteger;
import java.security.GeneralSecurityException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.RSAKeyGenParameterSpec;
public class Encrypt {
public void correct() throws GeneralSecurityException {
Integer keySize = new Integer(2048);
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
RSAKeyGenParameterSpec parameters = new RSAKeyGenParameterSpec(keySize, RSAKeyGenParameterSpec.F4);
generator.initialize(parameters, new SecureRandom());
KeyPair keyPair = generator.generateKeyPair();
}
public void incorrect() throws GeneralSecurityException {
Integer keySize = new Integer(208);
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
RSAKeyGenParameterSpec parameters = new RSAKeyGenParameterSpec(keySize, RSAKeyGenParameterSpec.F0);
generator.initialize(parameters, new SecureRandom());
KeyPair keyPair = generator.generateKeyPair();
}
public void correctBigInteger() throws GeneralSecurityException {
Integer keySize = new Integer(2048);
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
RSAKeyGenParameterSpec parameters = new RSAKeyGenParameterSpec(keySize, BigInteger.valueOf(65537));
generator.initialize(parameters, new SecureRandom());
KeyPair keyPair = generator.generateKeyPair();
}
public void incorrectBigInteger() throws GeneralSecurityException {
Integer keySize = new Integer(208);
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
RSAKeyGenParameterSpec parameters = new RSAKeyGenParameterSpec(keySize, BigInteger.valueOf(2));
generator.initialize(parameters, new SecureRandom());
KeyPair keyPair = generator.generateKeyPair();
}
}
| 1,833 | 42.666667 | 101 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/CryptoMisuseExamples/src/main/java/main/Msg.java | package main;
import java.security.GeneralSecurityException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.Signature;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
public class Msg {
private String ALG = "AES";
public byte[] sign(String data) throws GeneralSecurityException{
Signature signature = Signature.getInstance("SHA");
signature.initSign(getPrivateKey());
signature.update(data.getBytes());
return signature.sign();
}
//
public PrivateKey getPrivateKey() throws GeneralSecurityException {
KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA");
kpGen.initialize(118);
KeyPair keyPair = kpGen.generateKeyPair();
return keyPair.getPrivate();
}
// public static void main(String...args) throws GeneralSecurityException {
// Msg msg = new Msg();
//// msg.sign("test");
// }
public void encrypt() throws GeneralSecurityException, BadPaddingException {
Cipher c = Cipher.getInstance("AES");
}
public void encryptAlgFromVar() throws GeneralSecurityException, BadPaddingException {
String alg = "AES";
Cipher c = Cipher.getInstance(alg);
}
public void encryptAlgFromField() throws GeneralSecurityException, BadPaddingException {
ALG = "Test";
Cipher c = Cipher.getInstance(ALG);
}
}
| 1,385 | 27.875 | 89 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/FileEncryptor/src/main/java/FileHandler.java | import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.GeneralSecurityException;
import javax.crypto.SecretKey;
import Crypto.Enc;
import Crypto.KeyDeriv;
public class FileHandler {
byte[] content = null;
byte[] encryptedContent = null;
public boolean readFile(String path) {
try {
content = Files.readAllBytes(Paths.get(path));
} catch (IOException e) {
return false;
}
return true;
}
public boolean encryptContent(char[] pwd) throws GeneralSecurityException {
// TODO: Implement encryption. 'content' must be encrypted, the
// ciphered text must be stored in 'encryptedContent'.
KeyDeriv kd = new KeyDeriv();
SecretKey key = kd.getKey(pwd);
Enc enc = new Enc();
encryptedContent = enc.encrypt(content, key);
return true;
}
public boolean writeContent(String path) {
try {
Files.write(Paths.get(path), encryptedContent);
} catch (IOException e) {
return false;
} finally {
content = null;
}
return true;
}
} | 1,031 | 20.061224 | 76 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/FileEncryptor/src/main/java/Runner.java | import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
public class Runner {
public static void main(String[] args) throws GeneralSecurityException, UnsupportedEncodingException {
char[] pwd = new char[] { 'p', 'w', 'd' };
String error = "Reading file failed.";
// Cipher c = Cipher.getInstance("AES/ABC");
// c.init(1, KeyGenerator.getInstance("AES").generateKey());
// error = new String(c.doFinal("WHAT!?".getBytes()));
FileHandler f = new FileHandler();
if (!f.readFile(".\\resources\\input.txt")) {
System.err.println(error);
System.exit(-1);
}
if (!f.encryptContent(pwd)) {
System.err.println("File not encrypted!");
System.exit(-2);
}
if (f.writeContent(".\\bin\\output.txt")) {
System.out.println("Encrypted file successfully written!");
}
}
}
| 837 | 23.647059 | 103 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/FileEncryptor/src/main/java/Crypto/Enc.java |
package Crypto;
import java.security.GeneralSecurityException;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
/** @author CogniCrypt */
public class Enc {
public byte[] encrypt(byte[] data, SecretKey key) throws GeneralSecurityException {
byte[] ivb = new byte[16];
SecureRandom.getInstanceStrong().nextBytes(ivb);
IvParameterSpec iv = new IvParameterSpec(ivb);
Cipher c = Cipher.getInstance("AES/CFB/NoPadding");
c.init(Cipher.ENCRYPT_MODE, key, iv);
byte[] res = c.doFinal(data);
byte[] ret = new byte[res.length + ivb.length];
System.arraycopy(ivb, 0, ret, 0, ivb.length);
System.arraycopy(res, 0, ret, ivb.length, res.length);
return ret;
}
public byte[] decrypt(byte[] ciphertext, SecretKey key) throws GeneralSecurityException {
byte[] ivb = new byte[16];
System.arraycopy(ciphertext, 0, ivb, 0, ivb.length);
IvParameterSpec iv = new IvParameterSpec(ivb);
byte[] data = new byte[ciphertext.length - ivb.length];
System.arraycopy(ciphertext, ivb.length, data, 0, data.length);
Cipher c = Cipher.getInstance("AES/CFB/NoPadding");
c.init(Cipher.DECRYPT_MODE, key, iv);
byte[] res = c.doFinal(data);
return res;
}
}
| 1,266 | 24.34 | 90 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/FileEncryptor/src/main/java/Crypto/KeyDeriv.java |
package Crypto;
import java.security.GeneralSecurityException;
import java.security.SecureRandom;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
/** @author CogniCrypt */
public class KeyDeriv {
public SecretKey getKey(char[] pwd) throws GeneralSecurityException {
byte[] salt = new byte[16];
SecureRandom.getInstanceStrong().nextBytes(salt);
PBEKeySpec spec = new PBEKeySpec(pwd, salt, 65536, 128);
SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
SecretKeySpec ret = new SecretKeySpec(skf.generateSecret(spec).getEncoded(), "AES");
spec.clearPassword();
return ret;
}
}
| 721 | 26.769231 | 86 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/Java9ClasspathExample/src/main/java/ConstraintErrorExample.java |
import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
public class ConstraintErrorExample {
public static void main(String[] args) {
try {
Cipher instance = Cipher.getInstance("AES/ECB/PKCS5Padding");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
}
}
}
| 415 | 18.809524 | 64 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/Java9ModuleExample/src/module-info.java |
module org.demo.jpms {
requires java.base;
exports org.demo.jpms;
} | 74 | 7.333333 | 23 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/Java9ModuleExample/src/org/demo/jpms/MainClass.java | package org.demo.jpms;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
public class MainClass {
public static void main(String[] args) {
try {
Cipher instance = Cipher.getInstance("AES/ECB/PKCS5Padding");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
}
}
}
| 424 | 19.238095 | 64 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/MUBenchExamples/src/main/java/example/CipherUsesBlowfishExample.java | package example;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
/**
* This code contains a misuse example CogniCrypt_SAST of a Cipher object.
* CogniCrypt_SAST reports that the string argument to Cipher.getInstance("Blowfish") does not correspond the CrySL specification.
*
*/
public class CipherUsesBlowfishExample {
public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException {
Cipher instance = Cipher.getInstance("Blowfish");
}
}
| 555 | 25.47619 | 130 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/MUBenchExamples/src/main/java/example/CipherUsesBlowfishWithECBModeExample.java | package example;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
/**
* This code contains a misuse example CogniCrypt_SAST of a Cipher object.
* CogniCrypt_SAST reports that the string argument to Cipher.getInstance("Blowfish/ECB/NoPadding") does not correspond the CrySL specification.
*
*/
public class CipherUsesBlowfishWithECBModeExample {
public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException {
Cipher instance = Cipher.getInstance("Blowfish/ECB/NoPadding");
}
}
| 594 | 27.333333 | 144 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/MUBenchExamples/src/main/java/example/CipherUsesDESExample.java | package example;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
/**
* This code contains a misuse example CogniCrypt_SAST of a Cipher object.
* CogniCrypt_SAST reports that the string argument to Cipher.getInstance("DES") does not correspond the CrySL specification.
*
*/
public class CipherUsesDESExample {
public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException {
Cipher instance = Cipher.getInstance("DES");
}
}
| 540 | 24.761905 | 125 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/MUBenchExamples/src/main/java/example/CipherUsesDSAExample.java | package example;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
/**
* This code contains a misuse example CogniCrypt_SAST of a Cipher object.
* CogniCrypt_SAST reports that the string argument to Cipher.getInstance("DSA") does not correspond the CrySL specification.
*
*/
public class CipherUsesDSAExample {
public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException {
Cipher instance = Cipher.getInstance("DSA");
}
}
| 540 | 24.761905 | 125 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/MUBenchExamples/src/main/java/example/CipherUsesJustAESExample.java | package example;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
/**
* This code contains a misuse example CogniCrypt_SAST of a Cipher object.
* CogniCrypt_SAST reports that the string argument to Cipher.getInstance("AES") does not correspond the CrySL specification.
*
*/
public class CipherUsesJustAESExample {
public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException {
Cipher instance = Cipher.getInstance("AES");
}
}
| 544 | 24.952381 | 125 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/MUBenchExamples/src/main/java/example/CipherUsesNonRandomKeyExample.java | package example;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
public class CipherUsesNonRandomKeyExample {
public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
String plainText = "Message";
String key = "/u6=la%g57%Bnci(";
byte[] keyBytes = key.getBytes();
SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");
Cipher aesCipher = Cipher.getInstance("AES/GCM/NoPadding");
aesCipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] encrypted = aesCipher.doFinal(plainText.getBytes());
}
}
| 1,025 | 34.37931 | 221 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/MUBenchExamples/src/main/java/example/CipherUsesPBEWithMD5AndDESExample.java | package example;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
/**
* This code contains a misuse example CogniCrypt_SAST of a Cipher object.
* CogniCrypt_SAST reports that the string argument to Cipher.getInstance("PBEWithMD5AndDES") does not correspond the CrySL specification.
*
*/
public class CipherUsesPBEWithMD5AndDESExample {
public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException {
Cipher instance = Cipher.getInstance("PBEWithMD5AndDES");
}
}
| 579 | 26.619048 | 138 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/MUBenchExamples/src/main/java/example/CipherUsesRSAWithCBCExample.java | package example;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
/**
* This code contains a misuse example CogniCrypt_SAST of a Cipher object.
* CogniCrypt_SAST reports that the string argument to Cipher.getInstance("RSA/CBC/PKCS1Padding") does not correspond the CrySL specification.
*
*/
public class CipherUsesRSAWithCBCExample {
public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException {
Cipher instance = Cipher.getInstance("RSA/CBC/PKCS1Padding");
}
}
| 581 | 26.714286 | 142 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/MUBenchExamples/src/main/java/example/EmptyArrayUsedForCipherDoFinalExample.java | package example;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
public class EmptyArrayUsedForCipherDoFinalExample {
public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
String plainText = "";
int keySize = 128;
KeyGenerator keygenerator = KeyGenerator.getInstance("AES");
keygenerator.init(keySize);
SecretKey key = keygenerator.generateKey();
Cipher aesCipher = Cipher.getInstance("AES/GCM/PKCS5Padding");
aesCipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encrypted = aesCipher.doFinal(plainText.getBytes());
}
}
| 989 | 33.137931 | 191 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/MUBenchExamples/src/main/java/example/InitInMacCalledMoreThanOnceExample.java | package example;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
public class InitInMacCalledMoreThanOnceExample {
public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException {
KeyGenerator keyGen1 = KeyGenerator.getInstance("AES");
SecureRandom secRandom1 = new SecureRandom();
keyGen1.init(secRandom1);
Key key1 = keyGen1.generateKey();
KeyGenerator keyGen2 = KeyGenerator.getInstance("AES");
SecureRandom secRandom2 = new SecureRandom();
keyGen2.init(secRandom2);
Key key2 = keyGen1.generateKey();
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(key1);
mac.init(key2);
}
}
| 802 | 25.766667 | 94 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/MessageDigestExample/src/main/java/MessageDigestExample/MessageDigestExample/Main.java | package MessageDigestExample.MessageDigestExample;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class Main {
public static void main(String[] args) throws NoSuchAlgorithmException, IOException {
File file = new File(".\\resources\\abc.txt");
InputStream inputstream = new FileInputStream(file);
String msg = getSHA256(inputstream);
System.out.println(msg);
}
private static String getSHA256(InputStream uri) throws IOException, NoSuchAlgorithmException
{
InputStream is = uri;
MessageDigest md = MessageDigest.getInstance("SHA-256");
DigestInputStream dis = new DigestInputStream(is, md);
while (dis.read() != -1) {
// we just drain the stream here to compute the Message Digest
}
md = dis.getMessageDigest();
StringBuilder sb = new StringBuilder(64); // SHA-256 is always 64 hex characters
for (byte b : md.digest())
{
sb.append(String.format("%02x", b));
}
return sb.toString();
}
}
| 1,232 | 27.022727 | 94 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/OracleExample/src/Crypto/PWHasher.java |
package Crypto;
import java.security.GeneralSecurityException;
import java.security.SecureRandom;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import java.util.Base64;
/** @author CogniCrypt */
public class PWHasher {
// adopted code from https://github.com/defuse/password-hashing
public String createPWHash(char[] pwd) throws GeneralSecurityException {
byte[] salt = new byte[224 / 8];
SecureRandom.getInstanceStrong().nextBytes(salt);
PBEKeySpec spec = new PBEKeySpec(pwd, salt, 65536, 224);
SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA224");
String pwdHash = toBase64(salt) + ":" + toBase64(f.generateSecret(spec).getEncoded());
spec.clearPassword();
return pwdHash;
}
public Boolean verifyPWHash(char[] pwd, String pwdhash) throws GeneralSecurityException {
String[] parts = pwdhash.split(":");
byte[] salt = fromBase64(parts[0]);
PBEKeySpec spec = new PBEKeySpec(pwd, salt, 65536, 224);
SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA224");
Boolean areEqual = slowEquals(f.generateSecret(spec).getEncoded(), fromBase64(parts[1]));
spec.clearPassword();
return areEqual;
}
private static boolean slowEquals(byte[] a, byte[] b) {
int diff = a.length ^ b.length;
for (int i = 0; i < a.length && i < b.length; i++) {
diff |= a[i] ^ b[i];
}
return diff == 0;
}
private static String toBase64(byte[] array) {
return Base64.getEncoder().encodeToString(array);
}
private static byte[] fromBase64(String hash) {
return Base64.getDecoder().decode(hash);
}
}
| 1,594 | 29.09434 | 91 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/OracleExample/src/main/java/Crypto/PWHasher.java |
package Crypto;
import java.security.GeneralSecurityException;
import java.security.SecureRandom;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import java.util.Base64;
/** @author CogniCrypt */
public class PWHasher {
// adopted code from https://github.com/defuse/password-hashing
public String createPWHash(char[] pwd) throws GeneralSecurityException {
byte[] salt = new byte[224 / 8];
SecureRandom.getInstanceStrong().nextBytes(salt);
PBEKeySpec spec = new PBEKeySpec(pwd, salt, 65536, 224);
SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA224");
String pwdHash = toBase64(salt) + ":" + toBase64(f.generateSecret(spec).getEncoded());
spec.clearPassword();
return pwdHash;
}
public Boolean verifyPWHash(char[] pwd, String pwdhash) throws GeneralSecurityException {
String[] parts = pwdhash.split(":");
byte[] salt = fromBase64(parts[0]);
PBEKeySpec spec = new PBEKeySpec(pwd, salt, 65536, 224);
SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA224");
Boolean areEqual = slowEquals(f.generateSecret(spec).getEncoded(), fromBase64(parts[1]));
spec.clearPassword();
return areEqual;
}
private static boolean slowEquals(byte[] a, byte[] b) {
int diff = a.length ^ b.length;
for (int i = 0; i < a.length && i < b.length; i++) {
diff |= a[i] ^ b[i];
}
return diff == 0;
}
private static String toBase64(byte[] array) {
return Base64.getEncoder().encodeToString(array);
}
private static byte[] fromBase64(String hash) {
return Base64.getDecoder().decode(hash);
}
}
| 1,594 | 29.09434 | 91 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/OracleExample/src/main/java/main/Main.java | package main;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import Crypto.PWHasher;
public class Main {
public static void main(String... args) throws GeneralSecurityException {
byte[] plainText = args[0].getBytes();
String secretKey = "SECRET";
byte[] keyBytes = secretKey.getBytes();
SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] doFinal = cipher.doFinal();
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(secretKeySpec);
mac.doFinal(plainText);
}
public static void keyStoreExample()
throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
KeyStore instance = KeyStore.getInstance("Test");
String pwdAsString = "Test";
char[] password = pwdAsString.toCharArray();
instance.load(null, password);
}
public static void cipherUsageExample() throws GeneralSecurityException {
String trans = "AES";
KeyGenerator keygen = KeyGenerator.getInstance("AES");
keygen.init(128);
SecretKey key = keygen.generateKey();
Cipher cCipher = Cipher.getInstance(trans);
cCipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encText = cCipher.doFinal("".getBytes());
}
public void templateUsage(char[] pwd) throws GeneralSecurityException {
PWHasher pwHasher = new PWHasher();
String pwdHash = pwHasher.createPWHash(pwd);
Boolean t = pwHasher.verifyPWHash(pwd, pwdHash);
}
public static void interproceduralTypestate() throws GeneralSecurityException {
String trans = "AES/CBC/PKCS5Padding";
Cipher cCipher = Cipher.getInstance(trans);
use(cCipher);
}
private static void use(Cipher cCipher) throws IllegalBlockSizeException, BadPaddingException {
byte[] encText = cCipher.doFinal("".getBytes());
}
public void incorrectKeyForWrongCipher() throws GeneralSecurityException{
Object object = new Object();
use(object);
KeyGenerator keygen = KeyGenerator.getInstance("AES");
keygen.init(128);
SecretKey key = keygen.generateKey();
Cipher cCipher = Cipher.getInstance("Blowfish");
cCipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encText = cCipher.doFinal("".getBytes());
}
public void use(Object object) {
}
public void useCorrectDoFinal() throws GeneralSecurityException{
KeyGenerator keygen = KeyGenerator.getInstance("AES");
keygen.init(128);
SecretKey key = keygen.generateKey();
Cipher cCipher = Cipher.getInstance("AES");
cCipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encText = cCipher.doFinal("".getBytes());
}
public void useWrongDoFinal() throws GeneralSecurityException{
KeyGenerator keygen = KeyGenerator.getInstance("AES");
keygen.init(128);
SecretKey key = keygen.generateKey();;
Cipher cCipher = Cipher.getInstance("AES");
cCipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encText = cCipher.doFinal();
}
public void useNoDoFinal() throws GeneralSecurityException{
KeyGenerator keygen = KeyGenerator.getInstance("AES");
keygen.init(128);
SecretKey key = keygen.generateKey();;
Cipher cCipher = Cipher.getInstance("AES");
cCipher.init(Cipher.ENCRYPT_MODE, key);
}
public void useDoFinalInLoop() throws GeneralSecurityException{
KeyGenerator keygen = KeyGenerator.getInstance("AES");
keygen.init(128);
SecretKey key = keygen.generateKey();;
Cipher cCipher = Cipher.getInstance("AES");
cCipher.init(Cipher.ENCRYPT_MODE, key);
for (int i=0; i<42; i++){
cCipher.doFinal("".getBytes());
}
}
}
| 4,020 | 32.231405 | 96 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/ReportFormatExample/src/main/java/MessageDigestExample/MessageDigestExample/Main.java | package MessageDigestExample.MessageDigestExample;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class Main {
public static void main(String[] args) throws NoSuchAlgorithmException, IOException {
File file = new File(".\\resources\\abc.txt");
InputStream inputstream = new FileInputStream(file);
String msg = getSHA256(inputstream);
System.out.println(msg);
}
private static String getSHA256(InputStream uri) throws IOException, NoSuchAlgorithmException
{
InputStream is = uri;
MessageDigest md = MessageDigest.getInstance("SHA-256");
DigestInputStream dis = new DigestInputStream(is, md);
while (dis.read() != -1) {
// we just drain the stream here to compute the Message Digest
}
md = dis.getMessageDigest();
StringBuilder sb = new StringBuilder(64); // SHA-256 is always 64 hex characters
for (byte b : md.digest())
{
sb.append(String.format("%02x", b));
}
return sb.toString();
}
}
| 1,232 | 27.022727 | 94 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/ReportedIssues/src/main/java/issue103/Main.java | package issue103;
import java.security.GeneralSecurityException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.IvParameterSpec;
public class Main {
public static void main(String[] args) throws GeneralSecurityException {
byte[] seed = { 1, 2, 3 };
new SecureRandom(seed); //Static Seed
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
random.setSeed(seed); //Static Seed
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(256, random); // "Second parameter was not properly randomized"
keyGen.generateKey();
new IvParameterSpec(seed); // "First parameter was not properly randomized"
}
}
| 736 | 26.296296 | 77 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/ReportedIssues/src/main/java/issue137/NonDeterministic.java | package issue137;
import javax.crypto.Cipher;
public class NonDeterministic {
public static void main(String[] args) throws Exception {
Object x = getFoo();
if (x != null) {
Cipher cipher = Cipher.getInstance(x.toString());
}
}
public static Object getFoo() {
String f = "foo";
return f.equals("bar") ? System.out : System.in;
}
}
| 352 | 17.578947 | 58 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/ReportedIssues/src/main/java/issue137/Program.java | package issue137;
import javax.crypto.Cipher;
class Program {
public static void main(String[] args) throws Exception {
String x = getFoo();
if (x != null) {
Cipher cipher = Cipher.getInstance(x);
cipher.toString();
}
}
public static String getFoo() {
String f = "foo";
return f.equals("bar") ? "A" : "B";
}
}
| 337 | 15.9 | 58 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/ReportedIssues/src/main/java/issue49/Main.java | package issue49;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.Signature;
public class Main {
public byte[] sign(String data) throws Exception {
Signature signature = Signature.getInstance("SHA256withRSA");
signature.initSign(getPrivateKey());
signature.update(data.getBytes());
return signature.sign();
}
private PrivateKey getPrivateKey() throws NoSuchAlgorithmException {
KeyPairGenerator gen = KeyPairGenerator.getInstance("AES");
gen.initialize(1024);
KeyPair keyPair = gen.generateKeyPair();
return keyPair.getPrivate();
}
}
| 678 | 27.291667 | 69 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/ReportedIssues/src/main/java/issue68/AESCryptor.java | package issue68;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
public class AESCryptor {
private static final int IV_LENGTH = 16;
private static final int PADDING_LENGTH = 16;
private static final String ENCRYPTION_ALGORITHM = "AES";
private static final String ENCRYPTION_ALGORITHM_WITH_MODE = "AES/CBC/PKCS5Padding";
private static final String PASSWORD_HASH_ALGORITHM = "PBKDF2WithHmacSHA1";
private static final byte[] PASSWORD_HASH_SALT = "*1w@UTcZLS@6fS713x80".getBytes(StandardCharsets.UTF_8);
private static final int PASSWORD_HASH_ITERATION_COUNT = 12450;
private static final int PASSWORD_HASH_LENGTH_BITS = 128;
private final SecretKeySpec keySpec;
private final Cipher decryptionCipher;
private final Cipher encryptionCipher;
private final SecureRandom random = new SecureRandom();
public AESCryptor(final String password) throws EncryptionException {
this(getKey(password));
}
public AESCryptor(final byte[] encryptionKey) throws EncryptionException {
this.keySpec = new SecretKeySpec(encryptionKey, ENCRYPTION_ALGORITHM);
try {
decryptionCipher = Cipher.getInstance(ENCRYPTION_ALGORITHM_WITH_MODE);
encryptionCipher = Cipher.getInstance(ENCRYPTION_ALGORITHM_WITH_MODE);
} catch (final NoSuchAlgorithmException | NoSuchPaddingException e) {
throw new EncryptionException(e.getMessage());
}
}
private byte[] decryptImpl(final byte[] bytes) {
final ByteBuffer buffer = ByteBuffer.wrap(bytes);
try {
final byte[] iv = new byte[IV_LENGTH];
buffer.get(iv);
final byte[] content = new byte[buffer.remaining()];
buffer.get(content);
final IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
synchronized (decryptionCipher) {
decryptionCipher.init(Cipher.DECRYPT_MODE, keySpec, ivParameterSpec);
return decryptionCipher.doFinal(content);
}
} catch (final BufferUnderflowException | InvalidAlgorithmParameterException | InvalidKeyException |
IllegalBlockSizeException | BadPaddingException e) {
return null;
}
}
private byte[] encryptImpl(final byte[] bytes) {
try {
final byte[] iv = new byte[IV_LENGTH];
random.nextBytes(iv);
final IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
final byte[] result;
synchronized (encryptionCipher) {
encryptionCipher.init(Cipher.ENCRYPT_MODE, keySpec, ivParameterSpec);
result = encryptionCipher.doFinal(bytes);
}
final ByteBuffer buffer = ByteBuffer.allocate(iv.length + result.length);
buffer.put(iv);
buffer.put(result);
return buffer.array();
} catch (final BufferUnderflowException | InvalidAlgorithmParameterException | InvalidKeyException |
IllegalBlockSizeException | BadPaddingException e) {
return null;
}
}
public byte[] encrypt(final byte[] rawData) {
return encryptImpl(rawData);
}
public byte[] decrypt(final byte[] encryptedData) {
return decryptImpl(encryptedData);
}
private static SecretKeyFactory getFactory() throws NoSuchAlgorithmException {
return SecretKeyFactory.getInstance(PASSWORD_HASH_ALGORITHM);
}
private static byte[] getKey(final String password) throws EncryptionException {
final KeySpec keySpec = new PBEKeySpec(password.toCharArray(), PASSWORD_HASH_SALT,
PASSWORD_HASH_ITERATION_COUNT, PASSWORD_HASH_LENGTH_BITS);
try {
return getFactory().generateSecret(keySpec).getEncoded();
} catch (final NoSuchAlgorithmException | InvalidKeySpecException e) {
throw new EncryptionException(e.getMessage());
}
}
} | 4,649 | 33.191176 | 109 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/ReportedIssues/src/main/java/issue68/EncryptionException.java | package issue68;
public class EncryptionException extends Exception {
public EncryptionException(String message) {
// TODO Auto-generated constructor stub
}
}
| 166 | 15.7 | 52 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/ReportedIssues/src/main/java/issue68/Main.java | package issue68;
public class Main {
public void main(String...args) throws EncryptionException{
AESCryptor c = new AESCryptor("");
c.decrypt("te".getBytes());
c.encrypt("e".getBytes());
}
}
| 202 | 17.454545 | 60 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/ReportedIssues/src/main/java/issue68/simplified/field/AESCryptor.java | package issue68.simplified.field;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
public class AESCryptor {
SecureRandom random = new SecureRandom();
private byte[] encryptImpl(final byte[] bytes) {
try {
final byte[] iv = new byte[2];
random.nextBytes(iv);
final IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
use(ivParameterSpec);
} catch (final BufferUnderflowException e) {
return null;
}
return null;
}
private void use(IvParameterSpec ivParameterSpec) {
// TODO Auto-generated method stub
}
public byte[] encrypt(final byte[] rawData) {
return encryptImpl(rawData);
}
} | 1,373 | 27.040816 | 76 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/ReportedIssues/src/main/java/issue68/simplified/field/EncryptionException.java | package issue68.simplified.field;
public class EncryptionException extends Exception {
public EncryptionException(String message) {
// TODO Auto-generated constructor stub
}
}
| 183 | 17.4 | 52 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/ReportedIssues/src/main/java/issue68/simplified/field/Main.java | package issue68.simplified.field;
public class Main {
public void main(String...args) throws EncryptionException{
AESCryptor c = new AESCryptor();
c.encrypt("e".getBytes());
}
}
| 187 | 17.8 | 60 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/ReportedIssues/src/main/java/issue68/simplified/nofield/AESCryptor.java | package issue68.simplified.nofield;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
public class AESCryptor {
private byte[] encryptImpl(final byte[] bytes) {
try {
SecureRandom random = new SecureRandom();
final byte[] iv = new byte[2];
random.nextBytes(iv);
final IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
use(ivParameterSpec);
} catch (final BufferUnderflowException e) {
return null;
}
return null;
}
private void use(IvParameterSpec ivParameterSpec) {
// TODO Auto-generated method stub
}
public byte[] encrypt(final byte[] rawData) {
return encryptImpl(rawData);
}
} | 1,383 | 27.244898 | 76 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/ReportedIssues/src/main/java/issue68/simplified/nofield/EncryptionException.java | package issue68.simplified.nofield;
public class EncryptionException extends Exception {
public EncryptionException(String message) {
// TODO Auto-generated constructor stub
}
}
| 185 | 17.6 | 52 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/ReportedIssues/src/main/java/issue68/simplified/nofield/Main.java | package issue68.simplified.nofield;
public class Main {
public void main(String...args) throws EncryptionException{
AESCryptor c = new AESCryptor();
c.encrypt("e".getBytes());
}
}
| 189 | 18 | 60 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/ReportedIssues/src/main/java/issue70/ClientProtocolDecoder.java | package issue70;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class ClientProtocolDecoder {
public static final byte[] AES_KEY = "vWf7g1Gt701h0.#0".getBytes();
public static final byte[] AES_IV = "rgnHV16#8HQFc&16".getBytes();
public ClientProtocolDecoder() {
}
public static byte[] decryptAES(byte[] bytes) throws Exception {
try {
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
SecretKeySpec keyspec = new SecretKeySpec(AES_KEY, "AES");
IvParameterSpec ivspec = new IvParameterSpec(AES_IV);
cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
byte[] original = cipher.doFinal(bytes);
return original;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
| 788 | 27.178571 | 68 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/ReportedIssues/src/main/java/issue81/Encryption.java | package issue81;
import java.security.GeneralSecurityException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
public 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");
byte[] keyMaterial = secretKeyFactory.generateSecret(pBEKeySpec).getEncoded();
SecretKey encryptionKey = new SecretKeySpec(keyMaterial, "AES");
//pBEKeySpec.clearPassword();
return encryptionKey;
}
private byte[] encrypt(byte[] plainText, SecretKey encryptionKey) throws GeneralSecurityException, NoSuchPaddingException {
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));
}
} | 1,458 | 39.527778 | 127 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/ReportedIssues/src/main/java/issue81/Main.java | package issue81;
import java.security.GeneralSecurityException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.crypto.spec.PBEKeySpec;
public class Main {
public static void main(String...args) throws GeneralSecurityException {
byte [] next = new byte[32];
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.nextBytes(next);
PBEKeySpec pBEKeySpec = new PBEKeySpec("password".toCharArray(), next, 10299, 128);
}
}
| 502 | 28.588235 | 85 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/ReportedIssues/src/main/java/issuecognicrypt210/CogniCryptSecretKeySpec.java | package issuecognicrypt210;
import java.security.GeneralSecurityException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
public class CogniCryptSecretKeySpec {
public static void main(String [] args)
throws GeneralSecurityException, NoSuchAlgorithmException, InvalidKeySpecException {
char[] password = new char[] {'p', 'a', 's', 's', 'w', 'o', 'r', 'd'};
byte [] next = new byte[32];
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.nextBytes(next);
PBEKeySpec pBEKeySpec = new PBEKeySpec(password, next, 10299, 128);
SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
SecretKey secretKey = secretKeyFactory.generateSecret(pBEKeySpec);
byte[] keyMaterial = secretKey.getEncoded();
SecretKeySpec secretKeySpec = new SecretKeySpec(keyMaterial, "AES");
pBEKeySpec.clearPassword();
}
} | 1,120 | 32.969697 | 91 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/ReportedIssues/src/main/java/issueseeds/Main.java | package issueseeds;
import java.security.SecureRandom;
public class Main {
public static void main (String [] args){
SecureRandom sr = new SecureRandom();
byte [] bytes = {(byte) 100, (byte) 200};
sr.setSeed(bytes);
int v = sr.nextInt();
System.out.println(v);
}
}
| 315 | 20.066667 | 49 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/SSLMisuseExample/src/main/java/crypto/SSLExample.java | package crypto;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.net.ssl.SSLParameters;
public class SSLExample {
public void NoMisuse() throws NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
String[] paramOne = {"TLSv1.1", "TLSv1.2"};
String[] paramTwo = {"TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384"};
SSLParameters params = new SSLParameters();
params.setCipherSuites(paramTwo);
params.setProtocols(paramOne);
}
public void MisuseOne() throws NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
String[] paramOne = {"IPv4", "TLSv1.2"};
String[] paramTwo = {"TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384"};
SSLParameters params = new SSLParameters();
params.setCipherSuites(paramTwo);
params.setProtocols(paramOne);
}
public void MisuseTwo() throws NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
String[] paramOne = {"TLSv1.1", "TLSv1.2"};
String[] paramTwo = {"TLS_ECDHE_ECDSA_WITH_AES_256_SHA_SHA384"};
SSLParameters params = new SSLParameters();
params.setCipherSuites(paramTwo);
params.setProtocols(paramOne);
}
public void MisuseThree() throws NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
String[] paramOne = {"TLSv2.1", "TLSv1.2"};
String[] paramTwo = {"TL_ECDHE_ECDSA_WITH_AES_256_SHA_SHA384"};
SSLParameters params = new SSLParameters();
params.setCipherSuites(paramTwo);
params.setProtocols(paramOne);
}
}
| 1,715 | 38 | 132 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/SecureFileTransmitter/Crypto/Output.java |
package Crypto;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.SecretKey;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.security.SecureRandom;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.spec.InvalidKeySpecException;
import java.util.List;
import java.util.Base64;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import java.io.FileOutputStream;
public class Output {
public void templateUsage(String host,int port) {
//You need to set the right host (first parameter) and the port name (second parameter). If you wish to pass a IP address, please use overload with InetAdress as second parameter instead of string.
TLSClient tls = new TLSClient(host, port);
Boolean sendingSuccessful = tls.sendData("");
String data = tls.receiveData();
tls.closeConnection();
}
}
| 1,210 | 21.018182 | 206 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/SecureFileTransmitter/Crypto/TLSClient.java |
package Crypto;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.SecretKey;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.security.SecureRandom;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.spec.InvalidKeySpecException;
import java.util.List;
import java.util.Base64;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import java.io.FileOutputStream;
/** @author CogniCrypt */
public class TLSClient {
private static SSLSocket sslsocket = null;
private static BufferedWriter bufW = null;
private static BufferedReader bufR = null;
public TLSClient( String host,int port
) {
Properties prop = new Properties();
InputStream input = null;
String pwd = null;
System.setProperty("javax.net.ssl.trustStore","testPath");
try {
// If you move the generated code in another package (default of CogniCrypt is Crypto),
// you need to change the parameter (replacing Crypto with the package name).
input = Object.class.getClass().getResourceAsStream("/Crypto/clientConfig.properties");
prop.load(input);
pwd = prop.getProperty("pwd");
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.setProperty("javax.net.ssl.trustStorePassword",pwd);
SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
try {
sslsocket = (SSLSocket) sslsocketfactory.createSocket( host,
port
);
setCipherSuites();
setProtocols();
sslsocket.startHandshake();
bufW = new BufferedWriter(new OutputStreamWriter(sslsocket.getOutputStream()));
bufR = new BufferedReader(new InputStreamReader(sslsocket.getInputStream()));
} catch (IOException ex) {
System.out.println("Connection to server could not be established. Please check whether the ip/hostname and port are correct");
ex.printStackTrace();
}
}
private void setCipherSuites() {
if (sslsocket != null) {
//Insert cipher suites here
sslsocket.setEnabledCipherSuites(new String[]{
"TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384","TLS_DHE_RSA_WITH_AES_256_GCM_SHA384","TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384","TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384","TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384","TLS_DHE_RSA_WITH_AES_256_CBC_SHA256","TLS_DHE_DSS_WITH_AES_256_CBC_SHA256",
});
}
}
private void setProtocols() {
if (sslsocket != null) {
//Insert TLSxx here
sslsocket.setEnabledProtocols( new String[]{
"TLSv1.1", "TLSv1.2"
} );
}
}
public void closeConnection() {
try {
if (!sslsocket.isClosed()) {
sslsocket.close();
}
} catch (IOException ex) {
System.out.println("Could not close channel.");
ex.printStackTrace();
}
}
public boolean sendData(String content) {
try {
bufW.write(content + "\n");
bufW.flush();
return true;
} catch (IOException ex) {
System.out.println("Sending data failed.");
ex.printStackTrace();
return false;
}
}
public String receiveData() {
try {
return bufR.readLine();
} catch (IOException ex) {
System.out.println("Receiving data failed.");
ex.printStackTrace();
return null;
}
}
}
| 3,689 | 24.804196 | 281 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/SecureFileTransmitter/src/main/java/Crypto/TLSClient.java |
package Crypto;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Properties;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
/** @author CogniCrypt */
public class TLSClient {
private static SSLSocket sslsocket = null;
private static BufferedWriter bufW = null;
private static BufferedReader bufR = null;
public TLSClient(String host, int port) {
Properties prop = new Properties();
InputStream input = null;
String pwd = null;
System.setProperty("javax.net.ssl.trustStore", "testPath");
try {
// If you move the generated code in another package (default of CogniCrypt is
// Crypto),
// you need to change the parameter (replacing Crypto with the package name).
input = Object.class.getClass().getResourceAsStream("/Crypto/clientConfig.properties");
prop.load(input);
pwd = prop.getProperty("pwd");
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.setProperty("javax.net.ssl.trustStorePassword", pwd);
SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
try {
sslsocket = (SSLSocket) sslsocketfactory.createSocket(host, port);
setCipherSuites();
setProtocols();
sslsocket.startHandshake();
bufW = new BufferedWriter(new OutputStreamWriter(sslsocket.getOutputStream()));
bufR = new BufferedReader(new InputStreamReader(sslsocket.getInputStream()));
} catch (IOException ex) {
System.out.println(
"Connection to server could not be established. Please check whether the ip/hostname and port are correct");
ex.printStackTrace();
}
}
private void setCipherSuites() {
if (sslsocket != null) {
// Insert cipher suites here
sslsocket.setEnabledCipherSuites(new String[] { "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384",
"TLS_DHE_RSA_WITH_AES_256_GCM_SHA384", "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384",
"TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384", "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384",
"TLS_DHE_RSA_WITH_AES_256_CBC_SHA256", "TLS_DHE_DSS_WITH_AES_256_CBC_SHA256", });
}
}
private void setProtocols() {
if (sslsocket != null) {
// Insert TLSxx here
sslsocket.setEnabledProtocols(new String[] { "TLSv1.1", "TLSv1.2" });
}
}
public void closeConnection() {
try {
if (!sslsocket.isClosed()) {
sslsocket.close();
}
} catch (IOException ex) {
System.out.println("Could not close channel.");
ex.printStackTrace();
}
}
public boolean sendData(String content) {
try {
bufW.write(content + "\n");
bufW.flush();
return true;
} catch (IOException ex) {
System.out.println("Sending data failed.");
ex.printStackTrace();
return false;
}
}
public String receiveData() {
try {
return bufR.readLine();
} catch (IOException ex) {
System.out.println("Receiving data failed.");
ex.printStackTrace();
return null;
}
}
}
| 3,143 | 26.823009 | 113 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/SecureFileTransmitter/src/main/java/example/FileReader.java | package example;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class FileReader {
String content = null;
public FileReader(String path) throws IOException {
content = new String(Files.readAllBytes(Paths.get(path)));
}
public String getContent() {
return content;
}
}
| 328 | 14.666667 | 60 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/SecureFileTransmitter/src/main/java/example/Main.java | package example;
import Crypto.TLSClient;
public class Main {
public static void main(String... args) throws Exception {
FileReader f = new FileReader(".\\bin\\input.txt");
String fileContent = f.getContent();
// TLSClient tls = new TLSClient("127.0.0.1", 9999);
// tls.sendData();
// tls.closeConnection();
TLSClient tls = new TLSClient("127.0.0.1", 9999);
Boolean sendingSuccessful = tls.sendData(fileContent);
if(!sendingSuccessful)
System.out.println("Data was not sent.");
fileContent = tls.receiveData();
tls.closeConnection();
}
}
| 571 | 21.88 | 59 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/StopwatchExample/src/main/java/main/Main.java | package main;
import com.google.common.base.Stopwatch;
public class Main {
private static void correct() {
Stopwatch watch = Stopwatch.createStarted();
watch.isRunning();
watch.stop();
watch.start();
if(watch.isRunning()) {
watch.stop();
}
}
private static void wrong() {
Stopwatch watch = Stopwatch.createStarted();
watch.stop();
watch.stop();
}
private static void wrongWithContext() {
Stopwatch watch = Stopwatch.createStarted();
context(watch);
context(watch);
}
private static void wrongWithTwoContexts() {
Stopwatch watch = Stopwatch.createStarted();
context2(watch);
context(watch);
}
private static void context2(Stopwatch watch) {
watch.stop();
}
private static void context(Stopwatch watch) {
watch.stop();
}
}
| 778 | 17.547619 | 48 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/UserAuthenticator/src/main/java/DatabaseConnection.java |
public class DatabaseConnection {
private static String password;
public static void storePassword(String user, String pass) {
password = pass;
}
public static String retrievePassword(String user) {
return password;
}
}
| 236 | 15.928571 | 61 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/UserAuthenticator/src/main/java/Main.java | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import Crypto.PWHasher;
public class Main {
public static void main(String[] args) throws IOException, GeneralSecurityException {
///// PASSWORD STORAGE
// Get password from user via console input
char[] userinput = new char[256];
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please enter your password");
int readChars = br.read(userinput);
// Copy actual password to separate array to avoid storing a lot of
// zeros
char[] userPwd = Arrays.copyOf(userinput, readChars);
// Clear array
for (int i = 0; i <= readChars; i++) {
userinput[i] = 0;
}
// TODO: Implement transformation of password userPwd for secure storage
PWHasher pwHasher = new PWHasher();
String pwdHash = pwHasher.createPWHash(userPwd);
System.out.println("Password" + ((pwdHash.isEmpty()) ? " not(!)" : "") + " securely stored.");
if (pwdHash.isEmpty()) {
return;
}
// Store password in database
DatabaseConnection.storePassword("Annelie", pwdHash);
///// PASSWORD VERIFICATION
// Get password from user via console input
System.out.println("Please enter your password again for confirmation");
readChars = br.read(userinput);
// Copy actual password to separate array to avoid storing a lot of
// zeros
userPwd = Arrays.copyOf(userinput, readChars);
// Clear array
for (int i = 0; i <= readChars; i++) {
userinput[i] = 0;
}
String pwdFromDatabase = DatabaseConnection.retrievePassword("Annelie");
// TODO: Implement password verification
Boolean t = pwHasher.verifyPWHash(userPwd, pwdFromDatabase);
System.out.println("Verification " + ((t) ? "successful" : "failed"));
}
}
| 1,858 | 27.6 | 96 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/UserAuthenticator/src/main/java/Crypto/PWHasher.java |
package Crypto;
import java.security.GeneralSecurityException;
import java.security.SecureRandom;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import java.util.Base64;
/** @author CogniCrypt */
public class PWHasher {
// adopted code from https://github.com/defuse/password-hashing
public String createPWHash(char[] pwd) throws GeneralSecurityException {
byte[] salt = new byte[224 / 8];
SecureRandom.getInstanceStrong().nextBytes(salt);
PBEKeySpec spec = new PBEKeySpec(pwd, salt, 65536, 224);
SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA224");
String pwdHash = toBase64(salt) + ":" + toBase64(f.generateSecret(spec).getEncoded());
spec.clearPassword();
return pwdHash;
}
public Boolean verifyPWHash(char[] pwd, String pwdhash) throws GeneralSecurityException {
String[] parts = pwdhash.split(":");
byte[] salt = fromBase64(parts[0]);
PBEKeySpec spec = new PBEKeySpec(pwd, salt, 65536, 224);
SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA224");
Boolean areEqual = slowEquals(f.generateSecret(spec).getEncoded(), fromBase64(parts[1]));
spec.clearPassword();
return areEqual;
}
private static boolean slowEquals(byte[] a, byte[] b) {
int diff = a.length ^ b.length;
for (int i = 0; i < a.length && i < b.length; i++) {
diff |= a[i] ^ b[i];
}
return diff == 0;
}
private static String toBase64(byte[] array) {
return Base64.getEncoder().encodeToString(array);
}
private static byte[] fromBase64(String hash) {
return Base64.getDecoder().decode(hash);
}
}
| 1,594 | 29.09434 | 91 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/glassfish-embedded/src/main/java/org/glassfish/grizzly/config/ssl/ConcreteSSL.java | package org.glassfish.grizzly.config.ssl;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import javax.net.ssl.SSLServerSocket;
public class ConcreteSSL extends JSSESocketFactory {
@Override
public void init() throws IOException {
// TODO Auto-generated method stub
}
@Override
protected String[] getEnabledProtocols(SSLServerSocket paramSSLServerSocket, String paramString) {
// TODO Auto-generated method stub
return null;
}
@Override
protected void setEnabledProtocols(SSLServerSocket paramSSLServerSocket, String[] paramArrayOfString) {
// TODO Auto-generated method stub
}
@Override
public ServerSocket createServerSocket(int port) throws IOException {
// TODO Auto-generated method stub
return null;
}
@Override
public ServerSocket createServerSocket(int port, int backlog) throws IOException {
// TODO Auto-generated method stub
return null;
}
@Override
public ServerSocket createServerSocket(int port, int backlog, InetAddress ifAddress) throws IOException {
// TODO Auto-generated method stub
return null;
}
}
| 1,108 | 22.104167 | 106 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/glassfish-embedded/src/main/java/org/glassfish/grizzly/config/ssl/CustomClass.java | package org.glassfish.grizzly.config.ssl;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
public class CustomClass {
public void init(SecretKey k, String algs) throws NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException{
Cipher instance = Cipher.getInstance(algs);
instance.init(2, k);
byte[] ci = instance.doFinal("test".getBytes());
}
public void call() throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
String param = "AES";
init(null, param);
}
}
| 842 | 35.652174 | 169 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/glassfish-embedded/src/main/java/org/glassfish/grizzly/config/ssl/JSSESocketFactory.java | package org.glassfish.grizzly.config.ssl;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.security.KeyStore;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.net.ServerSocketFactory;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSocket;
import org.glassfish.grizzly.http.util.StringManager;
public abstract class JSSESocketFactory
extends ServerSocketFactory
{
private static final StringManager sm = StringManager.getManager(JSSESocketFactory.class.getPackage().getName(), JSSESocketFactory.class.getClassLoader());
public static final String defaultProtocol = "TLS";
public static final String defaultAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
static final boolean defaultClientAuth = false;
private static final String defaultKeyPass = "changeit";
protected static final Logger logger = Logger.getLogger(JSSESocketFactory.class.getName());
protected boolean initialized;
protected boolean clientAuthNeed = false;
protected boolean clientAuthWant = false;
protected SSLServerSocketFactory sslProxy = null;
protected String[] enabledCiphers;
private Map<String,String> attributes;
public ServerSocket createSocket(int port)
throws IOException
{
if (!this.initialized) {
init();
}
ServerSocket socket = this.sslProxy.createServerSocket(port);
initServerSocket(socket);
return socket;
}
public ServerSocket createSocket(int port, int backlog)
throws IOException
{
if (!this.initialized) {
init();
}
ServerSocket socket = this.sslProxy.createServerSocket(port, backlog);
initServerSocket(socket);
return socket;
}
public ServerSocket createSocket(int port, int backlog, InetAddress ifAddress)
throws IOException
{
if (!this.initialized) {
init();
}
ServerSocket socket = this.sslProxy.createServerSocket(port, backlog, ifAddress);
initServerSocket(socket);
return socket;
}
public Socket acceptSocket(ServerSocket socket)
throws IOException
{
SSLSocket asock;
try
{
asock = (SSLSocket)socket.accept();
if (this.clientAuthNeed) {
asock.setNeedClientAuth(this.clientAuthNeed);
} else {
asock.setWantClientAuth(this.clientAuthWant);
}
}
catch (SSLException e)
{
throw new SocketException("SSL handshake error" + e.toString());
}
return asock;
}
public void handshake(Socket sock)
throws IOException
{
((SSLSocket)sock).startHandshake();
}
protected String[] getEnabledCiphers(String requestedCiphers, String[] supportedCiphers)
{
String[] enabled = null;
if (requestedCiphers != null)
{
List<String> vec = null;
String cipher = requestedCiphers;
int index = requestedCiphers.indexOf(',');
if (index != -1)
{
int fromIndex = 0;
while (index != -1)
{
cipher = requestedCiphers.substring(fromIndex, index).trim();
if (cipher.length() > 0) {
for (int i = 0; (supportedCiphers != null) && (i < supportedCiphers.length); i++) {
if (supportedCiphers[i].equals(cipher))
{
if (vec == null) {
vec = new ArrayList();
}
vec.add(cipher);
break;
}
}
}
fromIndex = index + 1;
index = requestedCiphers.indexOf(',', fromIndex);
}
cipher = requestedCiphers.substring(fromIndex);
}
if (cipher != null)
{
cipher = cipher.trim();
if (cipher.length() > 0) {
for (int i = 0; (supportedCiphers != null) && (i < supportedCiphers.length); i++) {
if (supportedCiphers[i].equals(cipher))
{
if (vec == null) {
vec = new ArrayList();
}
vec.add(cipher);
break;
}
}
}
}
if (vec != null) {
enabled = (String[])vec.toArray(new String[vec.size()]);
}
}
return enabled;
}
protected String getKeystorePassword()
{
String keyPass = (String)this.attributes.get("keypass");
if (keyPass == null) {
keyPass = "changeit";
}
String keystorePass = (String)this.attributes.get("keystorePass");
if (keystorePass == null) {
keystorePass = keyPass;
}
return keystorePass;
}
protected KeyStore getKeystore(String pass)
throws IOException
{
String keystoreFile = (String)this.attributes.get("keystore");
if (logger.isLoggable(Level.FINE)) {
logger.fine("Keystore file= " + keystoreFile);
}
String keystoreType = (String)this.attributes.get("keystoreType");
if (logger.isLoggable(Level.FINE)) {
logger.fine("Keystore type= " + keystoreType);
}
return getStore(keystoreType, keystoreFile, pass);
}
protected String getTruststorePassword()
{
String truststorePassword = (String)this.attributes.get("truststorePass");
if (truststorePassword == null)
{
truststorePassword = System.getProperty("javax.net.ssl.trustStorePassword");
if (truststorePassword == null) {
truststorePassword = getKeystorePassword();
}
}
return truststorePassword;
}
protected KeyStore getTrustStore()
throws IOException
{
KeyStore ts = null;
String truststore = (String)this.attributes.get("truststore");
if (logger.isLoggable(Level.FINE)) {
logger.fine("Truststore file= " + truststore);
}
String truststoreType = (String)this.attributes.get("truststoreType");
if (logger.isLoggable(Level.FINE)) {
logger.fine("Truststore type= " + truststoreType);
}
String truststorePassword = getTruststorePassword();
if ((truststore != null) && (truststorePassword != null)) {
ts = getStore(truststoreType, truststore, truststorePassword);
}
return ts;
}
private KeyStore getStore(String type, String path, String pass)
throws IOException
{
KeyStore ks = null;
InputStream istream = null;
try
{
ks = KeyStore.getInstance(type);
if ((!"PKCS11".equalsIgnoreCase(type)) && (!"".equalsIgnoreCase(path)))
{
File keyStoreFile = new File(path);
if (!keyStoreFile.isAbsolute()) {
keyStoreFile = new File(System.getProperty("catalina.base"), path);
}
istream = new FileInputStream(keyStoreFile);
}
ks.load(istream, pass.toCharArray());
return ks;
}
catch (FileNotFoundException fnfe)
{
logger.log(Level.SEVERE, sm.getString("jsse.keystore_load_failed", type, path, fnfe.getMessage()), fnfe);
throw fnfe;
}
catch (IOException ioe)
{
logger.log(Level.SEVERE, sm.getString("jsse.keystore_load_failed", type, path, ioe.getMessage()), ioe);
throw ioe;
}
catch (Exception ex)
{
logger.log(Level.SEVERE, sm.getString("jsse.keystore_load_failed", type, path, ex.getMessage()), ex);
throw new IOException(sm.getString("jsse.keystore_load_failed", type, path, ex.getMessage()));
}
finally
{
if (istream != null) {
try
{
istream.close();
}
catch (IOException ioe) {}
}
}
}
public abstract void init()
throws IOException;
protected abstract String[] getEnabledProtocols(SSLServerSocket paramSSLServerSocket, String paramString);
protected abstract void setEnabledProtocols(SSLServerSocket paramSSLServerSocket, String[] paramArrayOfString);
protected void initServerSocket(ServerSocket ssocket)
{
SSLServerSocket socket = (SSLServerSocket)ssocket;
if (this.attributes.get("ciphers") != null) {
socket.setEnabledCipherSuites(this.enabledCiphers);
}
String requestedProtocols = (String)this.attributes.get("protocols");
setEnabledProtocols(socket, getEnabledProtocols(socket, requestedProtocols));
if (this.clientAuthNeed) {
socket.setNeedClientAuth(this.clientAuthNeed);
} else {
socket.setWantClientAuth(this.clientAuthWant);
}
}
}
| 8,598 | 29.278169 | 157 | java |
CryptoAnalysis | CryptoAnalysis-master/CryptoAnalysisTargets/glassfish-embedded/src/main/java/org/glassfish/grizzly/http/util/StringManager.java | package org.glassfish.grizzly.http.util;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
public class StringManager
{
private ResourceBundle bundle;
private StringManager(String packageName, ClassLoader loader)
{
this(packageName, Locale.getDefault(), loader);
}
private StringManager(String packageName, Locale loc, ClassLoader loader)
{
String bundleName = packageName + ".LocalStrings";
try
{
this.bundle = ResourceBundle.getBundle(bundleName, loc, loader);
}
catch (MissingResourceException ex)
{
this.bundle = ResourceBundle.getBundle(bundleName, Locale.US, loader);
}
}
private StringManager(ResourceBundle bundle)
{
this.bundle = bundle;
}
public String getString(String key)
{
if (key == null)
{
String msg = "key may not have a null value";
throw new IllegalArgumentException(msg);
}
String str;
try
{
str = this.bundle.getString(key);
}
catch (MissingResourceException mre)
{
str = null;
}
return str;
}
public String getString(String key, Object[] args)
{
String value = getString(key);
String iString;
try
{
if (args == null) {
args = new Object[1];
}
Object[] nonNullArgs = args;
for (int i = 0; i < args.length; i++) {
if (args[i] == null)
{
if (nonNullArgs == args) {
nonNullArgs = (Object[])args.clone();
}
nonNullArgs[i] = "null";
}
}
if (value == null) {
value = key;
}
iString = MessageFormat.format(value, nonNullArgs);
}
catch (IllegalArgumentException iae)
{
StringBuilder buf = new StringBuilder();
buf.append(value);
for (int i = 0; i < args.length; i++) {
buf.append(" arg[").append(i).append("]=").append(args[i]);
}
iString = buf.toString();
}
return iString;
}
public String getString(String key, Object arg)
{
Object[] args = { arg };
return getString(key, args);
}
public String getString(String key, Object arg1, Object arg2)
{
Object[] args = { arg1, arg2 };
return getString(key, args);
}
public String getString(String key, Object arg1, Object arg2, Object arg3)
{
Object[] args = { arg1, arg2, arg3 };
return getString(key, args);
}
public String getString(String key, Object arg1, Object arg2, Object arg3, Object arg4)
{
Object[] args = { arg1, arg2, arg3, arg4 };
return getString(key, args);
}
private static final Map<String, StringManager> managers = new HashMap();
public static synchronized StringManager getManager(String packageName, ClassLoader loader)
{
StringManager mgr = (StringManager)managers.get(packageName);
if (mgr == null)
{
mgr = new StringManager(packageName, loader);
managers.put(packageName, mgr);
}
return mgr;
}
public static synchronized StringManager getManager(ResourceBundle bundle)
{
return new StringManager(bundle);
}
public static synchronized StringManager getManager(String packageName, Locale loc, ClassLoader loader)
{
StringManager mgr = (StringManager)managers.get(packageName + '_' + loc.toString());
if (mgr == null)
{
mgr = new StringManager(packageName, loc, loader);
managers.put(packageName + '_' + loc.toString(), mgr);
}
return mgr;
}
}
| 3,600 | 23.664384 | 105 | java |
null | pytorch-main/android/pytorch_android/src/androidTest/java/org/pytorch/PytorchHostTests.java | package org.pytorch;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.Objects;
public class PytorchHostTests extends PytorchTestBase {
@Override
protected Module loadModel(String path) throws IOException {
return Module.load(assetFilePath(path));
}
private String assetFilePath(String assetName) throws IOException {
Path tempFile = Files.createTempFile("test", ".pt");
try (InputStream resource =
Objects.requireNonNull(getClass().getClassLoader().getResourceAsStream("test.pt"))) {
Files.copy(resource, tempFile, StandardCopyOption.REPLACE_EXISTING);
}
return tempFile.toAbsolutePath().toString();
}
}
| 772 | 28.730769 | 93 | java |
null | pytorch-main/android/pytorch_android/src/androidTest/java/org/pytorch/PytorchInstrumentedTests.java | package org.pytorch;
import android.content.Context;
import androidx.test.InstrumentationRegistry;
import androidx.test.runner.AndroidJUnit4;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.junit.runner.RunWith;
@RunWith(AndroidJUnit4.class)
public class PytorchInstrumentedTests extends PytorchTestBase {
@Override
protected Module loadModel(String path) throws IOException {
return Module.load(assetFilePath(path));
}
private String assetFilePath(String assetName) throws IOException {
final Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
File file = new File(appContext.getFilesDir(), assetName);
if (file.exists() && file.length() > 0) {
return file.getAbsolutePath();
}
try (InputStream is = appContext.getAssets().open(assetName)) {
try (OutputStream os = new FileOutputStream(file)) {
byte[] buffer = new byte[4 * 1024];
int read;
while ((read = is.read(buffer)) != -1) {
os.write(buffer, 0, read);
}
os.flush();
}
return file.getAbsolutePath();
} catch (IOException e) {
throw e;
}
}
}
| 1,262 | 28.372093 | 95 | java |
null | pytorch-main/android/pytorch_android/src/androidTest/java/org/pytorch/PytorchLiteInstrumentedTests.java | package org.pytorch;
import android.content.Context;
import androidx.test.InstrumentationRegistry;
import androidx.test.runner.AndroidJUnit4;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.junit.runner.RunWith;
@RunWith(AndroidJUnit4.class)
public class PytorchLiteInstrumentedTests extends PytorchTestBase {
@Override
protected Module loadModel(String path) throws IOException {
return LiteModuleLoader.load(assetFilePath(path));
}
private String assetFilePath(String assetName) throws IOException {
final Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
File file = new File(appContext.getFilesDir(), assetName);
if (file.exists() && file.length() > 0) {
return file.getAbsolutePath();
}
try (InputStream is = appContext.getAssets().open(assetName)) {
try (OutputStream os = new FileOutputStream(file)) {
byte[] buffer = new byte[4 * 1024];
int read;
while ((read = is.read(buffer)) != -1) {
os.write(buffer, 0, read);
}
os.flush();
}
return file.getAbsolutePath();
} catch (IOException e) {
throw e;
}
}
}
| 1,276 | 28.697674 | 95 | java |
null | pytorch-main/android/pytorch_android/src/androidTest/java/org/pytorch/PytorchTestBase.java | package org.pytorch;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
public abstract class PytorchTestBase {
private static final String TEST_MODULE_ASSET_NAME = "android_api_module.ptl";
@Test
public void testForwardNull() throws IOException {
final Module module = loadModel(TEST_MODULE_ASSET_NAME);
final IValue input = IValue.from(Tensor.fromBlob(Tensor.allocateByteBuffer(1), new long[] {1}));
assertTrue(input.isTensor());
final IValue output = module.forward(input);
assertTrue(output.isNull());
}
@Test
public void testEqBool() throws IOException {
final Module module = loadModel(TEST_MODULE_ASSET_NAME);
for (boolean value : new boolean[] {false, true}) {
final IValue input = IValue.from(value);
assertTrue(input.isBool());
assertTrue(value == input.toBool());
final IValue output = module.runMethod("eqBool", input);
assertTrue(output.isBool());
assertTrue(value == output.toBool());
}
}
@Test
public void testEqInt() throws IOException {
final Module module = loadModel(TEST_MODULE_ASSET_NAME);
for (long value : new long[] {Long.MIN_VALUE, -1024, -1, 0, 1, 1024, Long.MAX_VALUE}) {
final IValue input = IValue.from(value);
assertTrue(input.isLong());
assertTrue(value == input.toLong());
final IValue output = module.runMethod("eqInt", input);
assertTrue(output.isLong());
assertTrue(value == output.toLong());
}
}
@Test
public void testEqFloat() throws IOException {
final Module module = loadModel(TEST_MODULE_ASSET_NAME);
double[] values =
new double[] {
-Double.MAX_VALUE,
Double.MAX_VALUE,
-Double.MIN_VALUE,
Double.MIN_VALUE,
-Math.exp(1.d),
-Math.sqrt(2.d),
-3.1415f,
3.1415f,
-1,
0,
1,
};
for (double value : values) {
final IValue input = IValue.from(value);
assertTrue(input.isDouble());
assertTrue(value == input.toDouble());
final IValue output = module.runMethod("eqFloat", input);
assertTrue(output.isDouble());
assertTrue(value == output.toDouble());
}
}
@Test
public void testEqTensor() throws IOException {
final long[] inputTensorShape = new long[] {1, 3, 224, 224};
final long numElements = Tensor.numel(inputTensorShape);
final float[] inputTensorData = new float[(int) numElements];
for (int i = 0; i < numElements; ++i) {
inputTensorData[i] = i;
}
final Tensor inputTensor = Tensor.fromBlob(inputTensorData, inputTensorShape);
final Module module = loadModel(TEST_MODULE_ASSET_NAME);
final IValue input = IValue.from(inputTensor);
assertTrue(input.isTensor());
assertTrue(inputTensor == input.toTensor());
final IValue output = module.runMethod("eqTensor", input);
assertTrue(output.isTensor());
final Tensor outputTensor = output.toTensor();
assertNotNull(outputTensor);
assertArrayEquals(inputTensorShape, outputTensor.shape());
float[] outputData = outputTensor.getDataAsFloatArray();
for (int i = 0; i < numElements; i++) {
assertTrue(inputTensorData[i] == outputData[i]);
}
}
@Test
public void testEqDictIntKeyIntValue() throws IOException {
final Module module = loadModel(TEST_MODULE_ASSET_NAME);
final Map<Long, IValue> inputMap = new HashMap<>();
inputMap.put(Long.MIN_VALUE, IValue.from(-Long.MIN_VALUE));
inputMap.put(Long.MAX_VALUE, IValue.from(-Long.MAX_VALUE));
inputMap.put(0l, IValue.from(0l));
inputMap.put(1l, IValue.from(-1l));
inputMap.put(-1l, IValue.from(1l));
final IValue input = IValue.dictLongKeyFrom(inputMap);
assertTrue(input.isDictLongKey());
final IValue output = module.runMethod("eqDictIntKeyIntValue", input);
assertTrue(output.isDictLongKey());
final Map<Long, IValue> outputMap = output.toDictLongKey();
assertTrue(inputMap.size() == outputMap.size());
for (Map.Entry<Long, IValue> entry : inputMap.entrySet()) {
assertTrue(outputMap.get(entry.getKey()).toLong() == entry.getValue().toLong());
}
}
@Test
public void testEqDictStrKeyIntValue() throws IOException {
final Module module = loadModel(TEST_MODULE_ASSET_NAME);
final Map<String, IValue> inputMap = new HashMap<>();
inputMap.put("long_min_value", IValue.from(Long.MIN_VALUE));
inputMap.put("long_max_value", IValue.from(Long.MAX_VALUE));
inputMap.put("long_0", IValue.from(0l));
inputMap.put("long_1", IValue.from(1l));
inputMap.put("long_-1", IValue.from(-1l));
final IValue input = IValue.dictStringKeyFrom(inputMap);
assertTrue(input.isDictStringKey());
final IValue output = module.runMethod("eqDictStrKeyIntValue", input);
assertTrue(output.isDictStringKey());
final Map<String, IValue> outputMap = output.toDictStringKey();
assertTrue(inputMap.size() == outputMap.size());
for (Map.Entry<String, IValue> entry : inputMap.entrySet()) {
assertTrue(outputMap.get(entry.getKey()).toLong() == entry.getValue().toLong());
}
}
@Test
public void testListIntSumReturnTuple() throws IOException {
final Module module = loadModel(TEST_MODULE_ASSET_NAME);
for (int n : new int[] {0, 1, 128}) {
long[] a = new long[n];
long sum = 0;
for (int i = 0; i < n; i++) {
a[i] = i;
sum += a[i];
}
final IValue input = IValue.listFrom(a);
assertTrue(input.isLongList());
final IValue output = module.runMethod("listIntSumReturnTuple", input);
assertTrue(output.isTuple());
assertTrue(2 == output.toTuple().length);
IValue output0 = output.toTuple()[0];
IValue output1 = output.toTuple()[1];
assertArrayEquals(a, output0.toLongList());
assertTrue(sum == output1.toLong());
}
}
@Test
public void testOptionalIntIsNone() throws IOException {
final Module module = loadModel(TEST_MODULE_ASSET_NAME);
assertFalse(module.runMethod("optionalIntIsNone", IValue.from(1l)).toBool());
assertTrue(module.runMethod("optionalIntIsNone", IValue.optionalNull()).toBool());
}
@Test
public void testIntEq0None() throws IOException {
final Module module = loadModel(TEST_MODULE_ASSET_NAME);
assertTrue(module.runMethod("intEq0None", IValue.from(0l)).isNull());
assertTrue(module.runMethod("intEq0None", IValue.from(1l)).toLong() == 1l);
}
@Test(expected = IllegalArgumentException.class)
public void testRunUndefinedMethod() throws IOException {
final Module module = loadModel(TEST_MODULE_ASSET_NAME);
module.runMethod("test_undefined_method_throws_exception");
}
@Test
public void testTensorMethods() {
long[] shape = new long[] {1, 3, 224, 224};
final int numel = (int) Tensor.numel(shape);
int[] ints = new int[numel];
float[] floats = new float[numel];
byte[] bytes = new byte[numel];
for (int i = 0; i < numel; i++) {
bytes[i] = (byte) ((i % 255) - 128);
ints[i] = i;
floats[i] = i / 1000.f;
}
Tensor tensorBytes = Tensor.fromBlob(bytes, shape);
assertTrue(tensorBytes.dtype() == DType.INT8);
assertArrayEquals(bytes, tensorBytes.getDataAsByteArray());
Tensor tensorInts = Tensor.fromBlob(ints, shape);
assertTrue(tensorInts.dtype() == DType.INT32);
assertArrayEquals(ints, tensorInts.getDataAsIntArray());
Tensor tensorFloats = Tensor.fromBlob(floats, shape);
assertTrue(tensorFloats.dtype() == DType.FLOAT32);
float[] floatsOut = tensorFloats.getDataAsFloatArray();
assertTrue(floatsOut.length == numel);
for (int i = 0; i < numel; i++) {
assertTrue(floats[i] == floatsOut[i]);
}
}
@Test(expected = IllegalStateException.class)
public void testTensorIllegalStateOnWrongType() {
long[] shape = new long[] {1, 3, 224, 224};
final int numel = (int) Tensor.numel(shape);
float[] floats = new float[numel];
Tensor tensorFloats = Tensor.fromBlob(floats, shape);
assertTrue(tensorFloats.dtype() == DType.FLOAT32);
tensorFloats.getDataAsByteArray();
}
@Test
public void testEqString() throws IOException {
final Module module = loadModel(TEST_MODULE_ASSET_NAME);
String[] values =
new String[] {
"smoketest",
"проверка не латинских символов", // not latin symbols check
"#@$!@#)($*!@#$)(!@*#$"
};
for (String value : values) {
final IValue input = IValue.from(value);
assertTrue(input.isString());
assertTrue(value.equals(input.toStr()));
final IValue output = module.runMethod("eqStr", input);
assertTrue(output.isString());
assertTrue(value.equals(output.toStr()));
}
}
@Test
public void testStr3Concat() throws IOException {
final Module module = loadModel(TEST_MODULE_ASSET_NAME);
String[] values =
new String[] {
"smoketest",
"проверка не латинских символов", // not latin symbols check
"#@$!@#)($*!@#$)(!@*#$"
};
for (String value : values) {
final IValue input = IValue.from(value);
assertTrue(input.isString());
assertTrue(value.equals(input.toStr()));
final IValue output = module.runMethod("str3Concat", input);
assertTrue(output.isString());
String expectedOutput =
new StringBuilder().append(value).append(value).append(value).toString();
assertTrue(expectedOutput.equals(output.toStr()));
}
}
@Test
public void testEmptyShape() throws IOException {
final Module module = loadModel(TEST_MODULE_ASSET_NAME);
final long someNumber = 43;
final IValue input = IValue.from(Tensor.fromBlob(new long[] {someNumber}, new long[] {}));
final IValue output = module.runMethod("newEmptyShapeWithItem", input);
assertTrue(output.isTensor());
Tensor value = output.toTensor();
assertArrayEquals(new long[] {}, value.shape());
assertArrayEquals(new long[] {someNumber}, value.getDataAsLongArray());
}
@Test
public void testAliasWithOffset() throws IOException {
final Module module = loadModel(TEST_MODULE_ASSET_NAME);
final IValue output = module.runMethod("testAliasWithOffset");
assertTrue(output.isTensorList());
Tensor[] tensors = output.toTensorList();
assertEquals(100, tensors[0].getDataAsLongArray()[0]);
assertEquals(200, tensors[1].getDataAsLongArray()[0]);
}
@Test
public void testNonContiguous() throws IOException {
final Module module = loadModel(TEST_MODULE_ASSET_NAME);
final IValue output = module.runMethod("testNonContiguous");
assertTrue(output.isTensor());
Tensor value = output.toTensor();
assertArrayEquals(new long[] {2}, value.shape());
assertArrayEquals(new long[] {100, 300}, value.getDataAsLongArray());
}
@Test
public void testChannelsLast() throws IOException {
long[] inputShape = new long[] {1, 3, 2, 2};
long[] data = new long[] {1, 11, 101, 2, 12, 102, 3, 13, 103, 4, 14, 104};
Tensor inputNHWC = Tensor.fromBlob(data, inputShape, MemoryFormat.CHANNELS_LAST);
final Module module = loadModel(TEST_MODULE_ASSET_NAME);
final IValue outputNCHW = module.runMethod("contiguous", IValue.from(inputNHWC));
assertIValueTensor(
outputNCHW,
MemoryFormat.CONTIGUOUS,
new long[] {1, 3, 2, 2},
new long[] {1, 2, 3, 4, 11, 12, 13, 14, 101, 102, 103, 104});
final IValue outputNHWC = module.runMethod("contiguousChannelsLast", IValue.from(inputNHWC));
assertIValueTensor(outputNHWC, MemoryFormat.CHANNELS_LAST, inputShape, data);
}
@Test
public void testChannelsLast3d() throws IOException {
long[] shape = new long[] {1, 2, 2, 2, 2};
long[] dataNCHWD = new long[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
long[] dataNHWDC = new long[] {1, 9, 2, 10, 3, 11, 4, 12, 5, 13, 6, 14, 7, 15, 8, 16};
Tensor inputNHWDC = Tensor.fromBlob(dataNHWDC, shape, MemoryFormat.CHANNELS_LAST_3D);
final Module module = loadModel(TEST_MODULE_ASSET_NAME);
final IValue outputNCHWD = module.runMethod("contiguous", IValue.from(inputNHWDC));
assertIValueTensor(outputNCHWD, MemoryFormat.CONTIGUOUS, shape, dataNCHWD);
Tensor inputNCHWD = Tensor.fromBlob(dataNCHWD, shape, MemoryFormat.CONTIGUOUS);
final IValue outputNHWDC =
module.runMethod("contiguousChannelsLast3d", IValue.from(inputNCHWD));
assertIValueTensor(outputNHWDC, MemoryFormat.CHANNELS_LAST_3D, shape, dataNHWDC);
}
@Test
public void testChannelsLastConv2d() throws IOException {
long[] inputShape = new long[] {1, 3, 2, 2};
long[] dataNCHW = new long[] {1, 2, 3, 4, 11, 12, 13, 14, 101, 102, 103, 104};
Tensor inputNCHW = Tensor.fromBlob(dataNCHW, inputShape, MemoryFormat.CONTIGUOUS);
long[] dataNHWC = new long[] {1, 11, 101, 2, 12, 102, 3, 13, 103, 4, 14, 104};
Tensor inputNHWC = Tensor.fromBlob(dataNHWC, inputShape, MemoryFormat.CHANNELS_LAST);
long[] weightShape = new long[] {3, 3, 1, 1};
long[] dataWeightOIHW = new long[] {2, 0, 0, 0, 1, 0, 0, 0, -1};
Tensor wNCHW = Tensor.fromBlob(dataWeightOIHW, weightShape, MemoryFormat.CONTIGUOUS);
long[] dataWeightOHWI = new long[] {2, 0, 0, 0, 1, 0, 0, 0, -1};
Tensor wNHWC = Tensor.fromBlob(dataWeightOHWI, weightShape, MemoryFormat.CHANNELS_LAST);
final Module module = loadModel(TEST_MODULE_ASSET_NAME);
final IValue outputNCHW =
module.runMethod("conv2d", IValue.from(inputNCHW), IValue.from(wNCHW), IValue.from(false));
assertIValueTensor(
outputNCHW,
MemoryFormat.CONTIGUOUS,
new long[] {1, 3, 2, 2},
new long[] {2, 4, 6, 8, 11, 12, 13, 14, -101, -102, -103, -104});
final IValue outputNHWC =
module.runMethod("conv2d", IValue.from(inputNHWC), IValue.from(wNHWC), IValue.from(true));
assertIValueTensor(
outputNHWC,
MemoryFormat.CHANNELS_LAST,
new long[] {1, 3, 2, 2},
new long[] {2, 11, -101, 4, 12, -102, 6, 13, -103, 8, 14, -104});
}
@Test
public void testMobileNetV2() throws IOException {
try {
final Module module = loadModel("mobilenet_v2.ptl");
final IValue inputs = module.runMethod("get_all_bundled_inputs");
assertTrue(inputs.isList());
final IValue input = inputs.toList()[0];
assertTrue(input.isTuple());
module.forward(input.toTuple()[0]);
assertTrue(true);
} catch (Exception ex) {
assertTrue("failed to run MobileNetV2 " + ex.getMessage(), false);
}
}
@Test
public void testPointwiseOps() throws IOException {
runModel("pointwise_ops");
}
@Test
public void testReductionOps() throws IOException {
runModel("reduction_ops");
}
@Test
public void testComparisonOps() throws IOException {
runModel("comparison_ops");
}
@Test
public void testOtherMathOps() throws IOException {
runModel("other_math_ops");
}
@Test
public void testSpectralOps() throws IOException {
runModel("spectral_ops");
}
@Test
public void testBlasLapackOps() throws IOException {
runModel("blas_lapack_ops");
}
@Test
public void testSamplingOps() throws IOException {
runModel("sampling_ops");
}
@Test
public void testTensorOps() throws IOException {
runModel("tensor_general_ops");
}
@Test
public void testTensorCreationOps() throws IOException {
runModel("tensor_creation_ops");
}
@Test
public void testTensorIndexingOps() throws IOException {
runModel("tensor_indexing_ops");
}
@Test
public void testTensorTypingOps() throws IOException {
runModel("tensor_typing_ops");
}
@Test
public void testTensorViewOps() throws IOException {
runModel("tensor_view_ops");
}
@Test
public void testConvolutionOps() throws IOException {
runModel("convolution_ops");
}
@Test
public void testPoolingOps() throws IOException {
runModel("pooling_ops");
}
@Test
public void testPaddingOps() throws IOException {
runModel("padding_ops");
}
@Test
public void testActivationOps() throws IOException {
runModel("activation_ops");
}
@Test
public void testNormalizationOps() throws IOException {
runModel("normalization_ops");
}
@Test
public void testRecurrentOps() throws IOException {
runModel("recurrent_ops");
}
@Test
public void testTransformerOps() throws IOException {
runModel("transformer_ops");
}
@Test
public void testLinearOps() throws IOException {
runModel("linear_ops");
}
@Test
public void testDropoutOps() throws IOException {
runModel("dropout_ops");
}
@Test
public void testSparseOps() throws IOException {
runModel("sparse_ops");
}
@Test
public void testDistanceFunctionOps() throws IOException {
runModel("distance_function_ops");
}
@Test
public void testLossFunctionOps() throws IOException {
runModel("loss_function_ops");
}
@Test
public void testVisionFunctionOps() throws IOException {
runModel("vision_function_ops");
}
@Test
public void testShuffleOps() throws IOException {
runModel("shuffle_ops");
}
@Test
public void testNNUtilsOps() throws IOException {
runModel("nn_utils_ops");
}
@Test
public void testQuantOps() throws IOException {
runModel("general_quant_ops");
}
@Test
public void testDynamicQuantOps() throws IOException {
runModel("dynamic_quant_ops");
}
@Test
public void testStaticQuantOps() throws IOException {
runModel("static_quant_ops");
}
@Test
public void testFusedQuantOps() throws IOException {
runModel("fused_quant_ops");
}
@Test
public void testTorchScriptBuiltinQuantOps() throws IOException {
runModel("torchscript_builtin_ops");
}
@Test
public void testTorchScriptCollectionQuantOps() throws IOException {
runModel("torchscript_collection_ops");
}
static void assertIValueTensor(
final IValue ivalue,
final MemoryFormat memoryFormat,
final long[] expectedShape,
final long[] expectedData) {
assertTrue(ivalue.isTensor());
Tensor t = ivalue.toTensor();
assertEquals(memoryFormat, t.memoryFormat());
assertArrayEquals(expectedShape, t.shape());
assertArrayEquals(expectedData, t.getDataAsLongArray());
}
void runModel(final String name) throws IOException {
final Module storage_module = loadModel(name + ".ptl");
storage_module.forward();
// TODO enable this once the on-the-fly script is ready
// final Module on_the_fly_module = loadModel(name + "_temp.ptl");
// on_the_fly_module.forward();
assertTrue(true);
}
protected abstract Module loadModel(String assetName) throws IOException;
}
| 19,019 | 31.568493 | 100 | java |
null | pytorch-main/android/pytorch_android/src/androidTest/java/org/pytorch/suite/PytorchInstrumentedTestSuite.java | package org.pytorch.suite;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.pytorch.PytorchInstrumentedTests;
@RunWith(Suite.class)
@Suite.SuiteClasses({PytorchInstrumentedTests.class})
public class PytorchInstrumentedTestSuite {}
| 260 | 25.1 | 53 | java |
null | pytorch-main/android/pytorch_android/src/androidTest/java/org/pytorch/suite/PytorchLiteInstrumentedTestSuite.java | package org.pytorch.suite;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.pytorch.PytorchLiteInstrumentedTests;
@RunWith(Suite.class)
@Suite.SuiteClasses({PytorchLiteInstrumentedTests.class})
public class PytorchLiteInstrumentedTestSuite {}
| 272 | 26.3 | 57 | java |
null | pytorch-main/android/pytorch_android/src/main/java/org/pytorch/DType.java | package org.pytorch;
/** Codes representing tensor data types. */
public enum DType {
// NOTE: "jniCode" must be kept in sync with pytorch_jni_common.cpp.
// NOTE: Never serialize "jniCode", because it can change between releases.
/** Code for dtype torch.uint8. {@link Tensor#dtype()} */
UINT8(1),
/** Code for dtype torch.int8. {@link Tensor#dtype()} */
INT8(2),
/** Code for dtype torch.int32. {@link Tensor#dtype()} */
INT32(3),
/** Code for dtype torch.float32. {@link Tensor#dtype()} */
FLOAT32(4),
/** Code for dtype torch.int64. {@link Tensor#dtype()} */
INT64(5),
/** Code for dtype torch.float64. {@link Tensor#dtype()} */
FLOAT64(6),
;
final int jniCode;
DType(int jniCode) {
this.jniCode = jniCode;
}
}
| 759 | 26.142857 | 77 | java |
null | pytorch-main/android/pytorch_android/src/main/java/org/pytorch/Device.java | package org.pytorch;
public enum Device {
// Must be in sync with kDeviceCPU, kDeviceVulkan in
// pytorch_android/src/main/cpp/pytorch_jni_lite.cpp
CPU(1),
VULKAN(2),
;
final int jniCode;
Device(int jniCode) {
this.jniCode = jniCode;
}
}
| 261 | 15.375 | 54 | java |
null | pytorch-main/android/pytorch_android/src/main/java/org/pytorch/INativePeer.java | package org.pytorch;
interface INativePeer {
void resetNative();
IValue forward(IValue... inputs);
IValue runMethod(String methodName, IValue... inputs);
}
| 165 | 15.6 | 56 | java |
null | pytorch-main/android/pytorch_android/src/main/java/org/pytorch/IValue.java | package org.pytorch;
import com.facebook.jni.annotations.DoNotStrip;
import java.util.Locale;
import java.util.Map;
/**
* Java representation of a TorchScript value, which is implemented as tagged union that can be one
* of the supported types: https://pytorch.org/docs/stable/jit.html#types .
*
* <p>Calling {@code toX} methods for inappropriate types will throw {@link IllegalStateException}.
*
* <p>{@code IValue} objects are constructed with {@code IValue.from(value)}, {@code
* IValue.tupleFrom(value1, value2, ...)}, {@code IValue.listFrom(value1, value2, ...)}, or one of
* the {@code dict} methods, depending on the key type.
*
* <p>Data is retrieved from {@code IValue} objects with the {@code toX()} methods. Note that {@code
* str}-type IValues must be extracted with {@link #toStr()}, rather than {@link #toString()}.
*
* <p>{@code IValue} objects may retain references to objects passed into their constructors, and
* may return references to their internal state from {@code toX()}.
*/
@DoNotStrip
public class IValue {
private static final int TYPE_CODE_NULL = 1;
private static final int TYPE_CODE_TENSOR = 2;
private static final int TYPE_CODE_BOOL = 3;
private static final int TYPE_CODE_LONG = 4;
private static final int TYPE_CODE_DOUBLE = 5;
private static final int TYPE_CODE_STRING = 6;
private static final int TYPE_CODE_TUPLE = 7;
private static final int TYPE_CODE_BOOL_LIST = 8;
private static final int TYPE_CODE_LONG_LIST = 9;
private static final int TYPE_CODE_DOUBLE_LIST = 10;
private static final int TYPE_CODE_TENSOR_LIST = 11;
private static final int TYPE_CODE_LIST = 12;
private static final int TYPE_CODE_DICT_STRING_KEY = 13;
private static final int TYPE_CODE_DICT_LONG_KEY = 14;
private String[] TYPE_NAMES = {
"Unknown",
"Null",
"Tensor",
"Bool",
"Long",
"Double",
"String",
"Tuple",
"BoolList",
"LongList",
"DoubleList",
"TensorList",
"GenericList",
"DictStringKey",
"DictLongKey",
};
@DoNotStrip private final int mTypeCode;
@DoNotStrip private Object mData;
@DoNotStrip
private IValue(int typeCode) {
this.mTypeCode = typeCode;
}
@DoNotStrip
public boolean isNull() {
return TYPE_CODE_NULL == this.mTypeCode;
}
@DoNotStrip
public boolean isTensor() {
return TYPE_CODE_TENSOR == this.mTypeCode;
}
@DoNotStrip
public boolean isBool() {
return TYPE_CODE_BOOL == this.mTypeCode;
}
@DoNotStrip
public boolean isLong() {
return TYPE_CODE_LONG == this.mTypeCode;
}
@DoNotStrip
public boolean isDouble() {
return TYPE_CODE_DOUBLE == this.mTypeCode;
}
@DoNotStrip
public boolean isString() {
return TYPE_CODE_STRING == this.mTypeCode;
}
@DoNotStrip
public boolean isTuple() {
return TYPE_CODE_TUPLE == this.mTypeCode;
}
@DoNotStrip
public boolean isBoolList() {
return TYPE_CODE_BOOL_LIST == this.mTypeCode;
}
@DoNotStrip
public boolean isLongList() {
return TYPE_CODE_LONG_LIST == this.mTypeCode;
}
@DoNotStrip
public boolean isDoubleList() {
return TYPE_CODE_DOUBLE_LIST == this.mTypeCode;
}
@DoNotStrip
public boolean isTensorList() {
return TYPE_CODE_TENSOR_LIST == this.mTypeCode;
}
@DoNotStrip
public boolean isList() {
return TYPE_CODE_LIST == this.mTypeCode;
}
@DoNotStrip
public boolean isDictStringKey() {
return TYPE_CODE_DICT_STRING_KEY == this.mTypeCode;
}
@DoNotStrip
public boolean isDictLongKey() {
return TYPE_CODE_DICT_LONG_KEY == this.mTypeCode;
}
/** Creates a new {@code IValue} of type {@code Optional} that contains no value. */
@DoNotStrip
public static IValue optionalNull() {
return new IValue(TYPE_CODE_NULL);
}
/** Creates a new {@code IValue} of type {@code Tensor}. */
@DoNotStrip
public static IValue from(Tensor tensor) {
final IValue iv = new IValue(TYPE_CODE_TENSOR);
iv.mData = tensor;
return iv;
}
/** Creates a new {@code IValue} of type {@code bool}. */
@DoNotStrip
public static IValue from(boolean value) {
final IValue iv = new IValue(TYPE_CODE_BOOL);
iv.mData = value;
return iv;
}
/** Creates a new {@code IValue} of type {@code int}. */
@DoNotStrip
public static IValue from(long value) {
final IValue iv = new IValue(TYPE_CODE_LONG);
iv.mData = value;
return iv;
}
/** Creates a new {@code IValue} of type {@code float}. */
@DoNotStrip
public static IValue from(double value) {
final IValue iv = new IValue(TYPE_CODE_DOUBLE);
iv.mData = value;
return iv;
}
/** Creates a new {@code IValue} of type {@code str}. */
@DoNotStrip
public static IValue from(String value) {
final IValue iv = new IValue(TYPE_CODE_STRING);
iv.mData = value;
return iv;
}
/** Creates a new {@code IValue} of type {@code List[bool]}. */
@DoNotStrip
public static IValue listFrom(boolean... list) {
final IValue iv = new IValue(TYPE_CODE_BOOL_LIST);
iv.mData = list;
return iv;
}
/** Creates a new {@code IValue} of type {@code List[int]}. */
@DoNotStrip
public static IValue listFrom(long... list) {
final IValue iv = new IValue(TYPE_CODE_LONG_LIST);
iv.mData = list;
return iv;
}
/** Creates a new {@code IValue} of type {@code List[float]}. */
@DoNotStrip
public static IValue listFrom(double... list) {
final IValue iv = new IValue(TYPE_CODE_DOUBLE_LIST);
iv.mData = list;
return iv;
}
/** Creates a new {@code IValue} of type {@code List[Tensor]}. */
@DoNotStrip
public static IValue listFrom(Tensor... list) {
final IValue iv = new IValue(TYPE_CODE_TENSOR_LIST);
iv.mData = list;
return iv;
}
/** Creates a new {@code IValue} of type {@code List[T]}. All elements must have the same type. */
@DoNotStrip
public static IValue listFrom(IValue... array) {
final int size = array.length;
if (size > 0) {
final int typeCode0 = array[0].mTypeCode;
for (int i = 1; i < size; i++) {
if (typeCode0 != array[i].mTypeCode) {
throw new IllegalArgumentException("List must contain items of the same type");
}
}
}
final IValue iv = new IValue(TYPE_CODE_LIST);
iv.mData = array;
return iv;
}
/** Creates a new {@code IValue} of type {@code Tuple[T0, T1, ...]}. */
@DoNotStrip
public static IValue tupleFrom(IValue... array) {
final IValue iv = new IValue(TYPE_CODE_TUPLE);
iv.mData = array;
return iv;
}
/** Creates a new {@code IValue} of type {@code Dict[str, V]}. */
@DoNotStrip
public static IValue dictStringKeyFrom(Map<String, IValue> map) {
final IValue iv = new IValue(TYPE_CODE_DICT_STRING_KEY);
iv.mData = map;
return iv;
}
/** Creates a new {@code IValue} of type {@code Dict[int, V]}. */
@DoNotStrip
public static IValue dictLongKeyFrom(Map<Long, IValue> map) {
final IValue iv = new IValue(TYPE_CODE_DICT_LONG_KEY);
iv.mData = map;
return iv;
}
@DoNotStrip
public Tensor toTensor() {
preconditionType(TYPE_CODE_TENSOR, mTypeCode);
return (Tensor) mData;
}
@DoNotStrip
public boolean toBool() {
preconditionType(TYPE_CODE_BOOL, mTypeCode);
return (boolean) mData;
}
@DoNotStrip
public long toLong() {
preconditionType(TYPE_CODE_LONG, mTypeCode);
return (long) mData;
}
@DoNotStrip
public double toDouble() {
preconditionType(TYPE_CODE_DOUBLE, mTypeCode);
return (double) mData;
}
@DoNotStrip
public String toStr() {
preconditionType(TYPE_CODE_STRING, mTypeCode);
return (String) mData;
}
@DoNotStrip
public boolean[] toBoolList() {
preconditionType(TYPE_CODE_BOOL_LIST, mTypeCode);
return (boolean[]) mData;
}
@DoNotStrip
public long[] toLongList() {
preconditionType(TYPE_CODE_LONG_LIST, mTypeCode);
return (long[]) mData;
}
@DoNotStrip
public double[] toDoubleList() {
preconditionType(TYPE_CODE_DOUBLE_LIST, mTypeCode);
return (double[]) mData;
}
@DoNotStrip
public Tensor[] toTensorList() {
preconditionType(TYPE_CODE_TENSOR_LIST, mTypeCode);
return (Tensor[]) mData;
}
@DoNotStrip
public IValue[] toList() {
preconditionType(TYPE_CODE_LIST, mTypeCode);
return (IValue[]) mData;
}
@DoNotStrip
public IValue[] toTuple() {
preconditionType(TYPE_CODE_TUPLE, mTypeCode);
return (IValue[]) mData;
}
@DoNotStrip
public Map<String, IValue> toDictStringKey() {
preconditionType(TYPE_CODE_DICT_STRING_KEY, mTypeCode);
return (Map<String, IValue>) mData;
}
@DoNotStrip
public Map<Long, IValue> toDictLongKey() {
preconditionType(TYPE_CODE_DICT_LONG_KEY, mTypeCode);
return (Map<Long, IValue>) mData;
}
private void preconditionType(int typeCodeExpected, int typeCode) {
if (typeCode != typeCodeExpected) {
throw new IllegalStateException(
String.format(
Locale.US,
"Expected IValue type %s, actual type %s",
getTypeName(typeCodeExpected),
getTypeName(typeCode)));
}
}
private String getTypeName(int typeCode) {
return typeCode >= 0 && typeCode < TYPE_NAMES.length ? TYPE_NAMES[typeCode] : "Unknown";
}
}
| 9,262 | 25.927326 | 100 | java |
null | pytorch-main/android/pytorch_android/src/main/java/org/pytorch/LiteModuleLoader.java | package org.pytorch;
import android.content.res.AssetManager;
import java.util.Map;
public class LiteModuleLoader {
/**
* Loads a serialized TorchScript module from the specified path on the disk to run on specified
* device. The model should be generated from this api _save_for_lite_interpreter().
*
* @param modelPath path to file that contains the serialized TorchScript module.
* @param extraFiles map with extra files names as keys, content of them will be loaded to values.
* @param device {@link org.pytorch.Device} to use for running specified module.
* @return new {@link org.pytorch.Module} object which owns torch::jit::mobile::Module.
*/
public static Module load(
final String modelPath, final Map<String, String> extraFiles, final Device device) {
return new Module(new LiteNativePeer(modelPath, extraFiles, device));
}
/**
* Loads a serialized TorchScript module from the specified path on the disk to run on CPU. The
* model should be generated from this api _save_for_lite_interpreter().
*
* @param modelPath path to file that contains the serialized TorchScript module.
* @return new {@link org.pytorch.Module} object which owns torch::jit::mobile::Module.
*/
public static Module load(final String modelPath) {
return new Module(new LiteNativePeer(modelPath, null, Device.CPU));
}
/**
* Attention: This is not recommended way of loading production modules, as prepackaged assets
* increase apk size etc. For production usage consider using loading from file on the disk {@link
* org.pytorch.Module#load(String)}.
*
* <p>This method is meant to use in tests and demos.
*/
public static Module loadModuleFromAsset(
final AssetManager assetManager, final String assetName, final Device device) {
return new Module(new LiteNativePeer(assetName, assetManager, device));
}
public static Module loadModuleFromAsset(
final AssetManager assetManager, final String assetName) {
return new Module(new LiteNativePeer(assetName, assetManager, Device.CPU));
}
}
| 2,090 | 40.82 | 100 | java |
null | pytorch-main/android/pytorch_android/src/main/java/org/pytorch/LiteNativePeer.java | package org.pytorch;
import com.facebook.jni.HybridData;
import com.facebook.soloader.nativeloader.NativeLoader;
import com.facebook.soloader.nativeloader.SystemDelegate;
import java.util.Map;
class LiteNativePeer implements INativePeer {
static {
if (!NativeLoader.isInitialized()) {
NativeLoader.init(new SystemDelegate());
}
NativeLoader.loadLibrary("pytorch_jni_lite");
PyTorchCodegenLoader.loadNativeLibs();
}
private final HybridData mHybridData;
private static native HybridData initHybrid(
String moduleAbsolutePath, Map<String, String> extraFiles, int deviceJniCode);
private static native HybridData initHybridAndroidAsset(
String assetName, /* android.content.res.AssetManager */
Object androidAssetManager,
int deviceJniCode);
LiteNativePeer(String moduleAbsolutePath, Map<String, String> extraFiles, Device device) {
mHybridData = initHybrid(moduleAbsolutePath, extraFiles, device.jniCode);
}
LiteNativePeer(
String assetName, /* android.content.res.AssetManager */
Object androidAssetManager,
Device device) {
mHybridData = initHybridAndroidAsset(assetName, androidAssetManager, device.jniCode);
}
/**
* Explicitly destroys the native torch::jit::mobile::Module. Calling this method is not required,
* as the native object will be destroyed when this object is garbage-collected. However, the
* timing of garbage collection is not guaranteed, so proactively calling {@code resetNative} can
* free memory more quickly. See {@link com.facebook.jni.HybridData#resetNative}.
*/
public void resetNative() {
mHybridData.resetNative();
}
/**
* Runs the 'forward' method of this module with the specified arguments.
*
* @param inputs arguments for the TorchScript module's 'forward' method.
* @return return value from the 'forward' method.
*/
public native IValue forward(IValue... inputs);
/**
* Runs the specified method of this module with the specified arguments.
*
* @param methodName name of the TorchScript method to run.
* @param inputs arguments that will be passed to TorchScript method.
* @return return value from the method.
*/
public native IValue runMethod(String methodName, IValue... inputs);
}
| 2,285 | 34.169231 | 100 | java |
null | pytorch-main/android/pytorch_android/src/main/java/org/pytorch/MemoryFormat.java | package org.pytorch;
public enum MemoryFormat {
CONTIGUOUS(1),
CHANNELS_LAST(2),
CHANNELS_LAST_3D(3),
;
final int jniCode;
MemoryFormat(int jniCode) {
this.jniCode = jniCode;
}
}
| 200 | 12.4 | 29 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.