diff options
| author | J08nY | 2024-03-22 23:58:55 +0100 |
|---|---|---|
| committer | J08nY | 2024-03-25 14:52:43 +0100 |
| commit | 73af477a8774e1ede5dd8de6491eb353dc0b12bd (patch) | |
| tree | 2d4e3b19bc5fb55308b886032312be76341736d4 /src/cz/crcs/ectester/common/util | |
| parent | 64b95fa059295e1dc23371c849f2302c1c18f5b4 (diff) | |
| download | ECTester-73af477a8774e1ede5dd8de6491eb353dc0b12bd.tar.gz ECTester-73af477a8774e1ede5dd8de6491eb353dc0b12bd.tar.zst ECTester-73af477a8774e1ede5dd8de6491eb353dc0b12bd.zip | |
Basic Gradle setup.
Diffstat (limited to 'src/cz/crcs/ectester/common/util')
| -rw-r--r-- | src/cz/crcs/ectester/common/util/ByteUtil.java | 193 | ||||
| -rw-r--r-- | src/cz/crcs/ectester/common/util/CardUtil.java | 534 | ||||
| -rw-r--r-- | src/cz/crcs/ectester/common/util/ECUtil.java | 485 | ||||
| -rw-r--r-- | src/cz/crcs/ectester/common/util/FileUtil.java | 99 | ||||
| -rw-r--r-- | src/cz/crcs/ectester/common/util/Util.java | 28 |
5 files changed, 0 insertions, 1339 deletions
diff --git a/src/cz/crcs/ectester/common/util/ByteUtil.java b/src/cz/crcs/ectester/common/util/ByteUtil.java deleted file mode 100644 index 442824a..0000000 --- a/src/cz/crcs/ectester/common/util/ByteUtil.java +++ /dev/null @@ -1,193 +0,0 @@ -package cz.crcs.ectester.common.util; - -/** - * Utility class, some byte/hex manipulation, convenient byte[] methods. - * - * @author Petr Svenda petr@svenda.com - * @author Jan Jancar johny@neuromancer.sk - */ -public class ByteUtil { - - /** - * Get a short from a byte array at <code>offset</code>, big-endian. - * - * @return the short value - */ - public static short getShort(byte[] array, int offset) { - return (short) (((array[offset] & 0xFF) << 8) | (array[offset + 1] & 0xFF)); - } - - /** - * Get a short from a byte array at <code>offset</code>, return it as an int, big-endian. - * - * @return the short value (as an int) - */ - public static int getShortInt(byte[] array, int offset) { - return (((array[offset] & 0xFF) << 8) | (array[offset + 1] & 0xFF)); - } - - /** - * Set a short in a byte array at <code>offset</code>, big-endian. - */ - public static void setShort(byte[] array, int offset, short value) { - array[offset + 1] = (byte) (value & 0xFF); - array[offset] = (byte) ((value >> 8) & 0xFF); - } - - /** - * Compare two byte arrays upto <code>length</code> and get first difference. - * - * @return the position of the first difference in the two byte arrays, or <code>length</code> if they are equal. - */ - public static int diffBytes(byte[] one, int oneOffset, byte[] other, int otherOffset, int length) { - for (int i = 0; i < length; ++i) { - byte a = one[i + oneOffset]; - byte b = other[i + otherOffset]; - if (a != b) { - return i; - } - } - return length; - } - - /** - * Compare two byte arrays, upto <code>length</code>. - * - * @return whether the arrays are equal upto <code>length</code> - */ - public static boolean compareBytes(byte[] one, int oneOffset, byte[] other, int otherOffset, int length) { - return diffBytes(one, oneOffset, other, otherOffset, length) == length; - } - - /** - * Test if the byte array has all values equal to <code>value</code>. - */ - public static boolean allValue(byte[] array, byte value) { - for (byte a : array) { - if (a != value) - return false; - } - return true; - } - - public static byte[] shortToBytes(short value) { - byte[] result = new byte[2]; - setShort(result, 0, value); - return result; - } - - public static byte[] shortToBytes(short[] shorts) { - if (shorts == null) { - return null; - } - byte[] result = new byte[shorts.length * 2]; - for (int i = 0; i < shorts.length; ++i) { - setShort(result, 2 * i, shorts[i]); - } - return result; - } - - /** - * Parse a hex string into a byte array, big-endian. - * - * @param hex The String to parse. - * @return the byte array from the hex string. - */ - public static byte[] hexToBytes(String hex) { - return hexToBytes(hex, true); - } - - /** - * Parse a hex string into a byte-array, specify endianity. - * - * @param hex The String to parse. - * @param bigEndian Whether to parse as big-endian. - * @return the byte array from the hex string. - */ - public static byte[] hexToBytes(String hex, boolean bigEndian) { - hex = hex.replace(" ", ""); - int len = hex.length(); - StringBuilder sb = new StringBuilder(); - - if (len % 2 == 1) { - sb.append("0"); - ++len; - } - - if (bigEndian) { - sb.append(hex); - } else { - for (int i = 0; i < len / 2; ++i) { - if (sb.length() >= 2) { - sb.insert(sb.length() - 2, hex.substring(2 * i, 2 * i + 2)); - } else { - sb.append(hex.substring(2 * i, 2 * i + 2)); - } - - } - } - - String data = sb.toString(); - byte[] result = new byte[len / 2]; - for (int i = 0; i < len; i += 2) { - result[i / 2] = (byte) ((Character.digit(data.charAt(i), 16) << 4) - + (Character.digit(data.charAt(i + 1), 16))); - } - return result; - } - - public static String byteToHex(byte data) { - return String.format("%02x", data); - } - - public static String bytesToHex(byte[] data) { - return bytesToHex(data, true); - } - - public static String bytesToHex(byte[] data, boolean addSpace) { - if (data == null) { - return ""; - } - return bytesToHex(data, 0, data.length, addSpace); - } - - public static String bytesToHex(byte[] data, int offset, int len) { - return bytesToHex(data, offset, len, true); - } - - public static String bytesToHex(byte[] data, int offset, int len, boolean addSpace) { - if (data == null) { - return ""; - } - StringBuilder buf = new StringBuilder(); - for (int i = offset; i < (offset + len); i++) { - buf.append(byteToHex(data[i])); - if (addSpace && i != (offset + len - 1)) { - buf.append(" "); - } - } - return (buf.toString()); - } - - public static byte[] concatenate(byte[]... arrays) { - int len = 0; - for (byte[] array : arrays) { - if (array == null) - continue; - len += array.length; - } - byte[] out = new byte[len]; - int offset = 0; - for (byte[] array : arrays) { - if (array == null || array.length == 0) - continue; - System.arraycopy(array, 0, out, offset, array.length); - offset += array.length; - } - return out; - } - - public static byte[] prependLength(byte[] data) { - return concatenate(ByteUtil.shortToBytes((short) data.length), data); - } -} diff --git a/src/cz/crcs/ectester/common/util/CardUtil.java b/src/cz/crcs/ectester/common/util/CardUtil.java deleted file mode 100644 index 72963cf..0000000 --- a/src/cz/crcs/ectester/common/util/CardUtil.java +++ /dev/null @@ -1,534 +0,0 @@ -package cz.crcs.ectester.common.util; - -import cz.crcs.ectester.applet.ECTesterApplet; -import cz.crcs.ectester.applet.EC_Consts; -import javacard.framework.ISO7816; -import javacard.security.CryptoException; -import javacard.security.KeyPair; - -import java.util.LinkedList; -import java.util.List; - -/** - * @author Petr Svenda petr@svenda.com - * @author Jan Jancar johny@neuromancer.sk - */ -public class CardUtil { - public static byte getSig(String name) { - switch (name) { - case "SHA1": - return EC_Consts.Signature_ALG_ECDSA_SHA; - case "SHA224": - return EC_Consts.Signature_ALG_ECDSA_SHA_224; - case "SHA256": - return EC_Consts.Signature_ALG_ECDSA_SHA_256; - case "SHA384": - return EC_Consts.Signature_ALG_ECDSA_SHA_384; - case "SHA512": - return EC_Consts.Signature_ALG_ECDSA_SHA_512; - default: - return EC_Consts.Signature_ALG_ECDSA_SHA; - } - } - - public static String getSigHashAlgo(byte sigType) { - switch (sigType) { - case EC_Consts.Signature_ALG_ECDSA_SHA: - return "SHA1"; - case EC_Consts.Signature_ALG_ECDSA_SHA_224: - return "SHA224"; - case EC_Consts.Signature_ALG_ECDSA_SHA_256: - return "SHA256"; - case EC_Consts.Signature_ALG_ECDSA_SHA_384: - return "SHA384"; - case EC_Consts.Signature_ALG_ECDSA_SHA_512: - return "SHA512"; - default: - return null; - } - } - - public static String getSigHashName(byte sigType) { - switch (sigType) { - case EC_Consts.Signature_ALG_ECDSA_SHA: - return "SHA1"; - case EC_Consts.Signature_ALG_ECDSA_SHA_224: - return "SHA224"; - case EC_Consts.Signature_ALG_ECDSA_SHA_256: - return "SHA256"; - case EC_Consts.Signature_ALG_ECDSA_SHA_384: - return "SHA384"; - case EC_Consts.Signature_ALG_ECDSA_SHA_512: - return "SHA512"; - default: - return null; - } - } - - public static byte getKA(String name) { - switch (name) { - case "DH": - return EC_Consts.KeyAgreement_ALG_EC_SVDP_DH; - case "DHC": - return EC_Consts.KeyAgreement_ALG_EC_SVDP_DHC; - case "DH_PLAIN": - return EC_Consts.KeyAgreement_ALG_EC_SVDP_DH_PLAIN; - case "DHC_PLAIN": - return EC_Consts.KeyAgreement_ALG_EC_SVDP_DHC_PLAIN; - case "PACE_GM": - return EC_Consts.KeyAgreement_ALG_EC_PACE_GM; - case "DH_PLAIN_XY": - return EC_Consts.KeyAgreement_ALG_EC_SVDP_DH_PLAIN_XY; - default: - return EC_Consts.KeyAgreement_ALG_EC_SVDP_DH; - } - } - - public static String getKexHashName(byte kexType) { - switch (kexType) { - case EC_Consts.KeyAgreement_ALG_EC_SVDP_DH: - case EC_Consts.KeyAgreement_ALG_EC_SVDP_DHC: - return "SHA1"; - default: - return "NONE"; - } - } - - public static String getSWSource(short sw) { - switch (sw) { - case ISO7816.SW_NO_ERROR: - case ISO7816.SW_APPLET_SELECT_FAILED: - case ISO7816.SW_BYTES_REMAINING_00: - case ISO7816.SW_CLA_NOT_SUPPORTED: - case ISO7816.SW_COMMAND_NOT_ALLOWED: - case ISO7816.SW_CONDITIONS_NOT_SATISFIED: - case ISO7816.SW_CORRECT_LENGTH_00: - case ISO7816.SW_DATA_INVALID: - case ISO7816.SW_FILE_FULL: - case ISO7816.SW_FILE_INVALID: - case ISO7816.SW_FILE_NOT_FOUND: - case ISO7816.SW_FUNC_NOT_SUPPORTED: - case ISO7816.SW_INCORRECT_P1P2: - case ISO7816.SW_INS_NOT_SUPPORTED: - case ISO7816.SW_LOGICAL_CHANNEL_NOT_SUPPORTED: - case ISO7816.SW_RECORD_NOT_FOUND: - case ISO7816.SW_SECURE_MESSAGING_NOT_SUPPORTED: - case ISO7816.SW_SECURITY_STATUS_NOT_SATISFIED: - case ISO7816.SW_UNKNOWN: - case ISO7816.SW_WARNING_STATE_UNCHANGED: - case ISO7816.SW_WRONG_DATA: - case ISO7816.SW_WRONG_LENGTH: - case ISO7816.SW_WRONG_P1P2: - return "ISO"; - case CryptoException.ILLEGAL_VALUE: - case CryptoException.UNINITIALIZED_KEY: - case CryptoException.NO_SUCH_ALGORITHM: - case CryptoException.INVALID_INIT: - case CryptoException.ILLEGAL_USE: - return "CryptoException"; - case ECTesterApplet.SW_SIG_VERIFY_FAIL: - case ECTesterApplet.SW_DH_DHC_MISMATCH: - case ECTesterApplet.SW_KEYPAIR_NULL: - case ECTesterApplet.SW_KA_NULL: - case ECTesterApplet.SW_SIGNATURE_NULL: - case ECTesterApplet.SW_OBJECT_NULL: - return "ECTesterApplet"; - default: - return "?"; - } - } - - public static String getSW(short sw) { - int upper = (sw & 0xff00) >> 8; - int lower = (sw & 0xff); - switch (upper) { - case 0xf1: - return String.format("CryptoException(%d)", lower); - case 0xf2: - return String.format("SystemException(%d)", lower); - case 0xf3: - return String.format("PINException(%d)", lower); - case 0xf4: - return String.format("TransactionException(%d)", lower); - case 0xf5: - return String.format("CardRuntimeException(%d)", lower); - default: - switch (sw) { - case ISO7816.SW_APPLET_SELECT_FAILED: - return "APPLET_SELECT_FAILED"; - case ISO7816.SW_BYTES_REMAINING_00: - return "BYTES_REMAINING"; - case ISO7816.SW_CLA_NOT_SUPPORTED: - return "CLA_NOT_SUPPORTED"; - case ISO7816.SW_COMMAND_NOT_ALLOWED: - return "COMMAND_NOT_ALLOWED"; - case ISO7816.SW_CONDITIONS_NOT_SATISFIED: - return "CONDITIONS_NOT_SATISFIED"; - case ISO7816.SW_CORRECT_LENGTH_00: - return "CORRECT_LENGTH"; - case ISO7816.SW_DATA_INVALID: - return "DATA_INVALID"; - case ISO7816.SW_FILE_FULL: - return "FILE_FULL"; - case ISO7816.SW_FILE_INVALID: - return "FILE_INVALID"; - case ISO7816.SW_FILE_NOT_FOUND: - return "FILE_NOT_FOUND"; - case ISO7816.SW_FUNC_NOT_SUPPORTED: - return "FUNC_NOT_SUPPORTED"; - case ISO7816.SW_INCORRECT_P1P2: - return "INCORRECT_P1P2"; - case ISO7816.SW_INS_NOT_SUPPORTED: - return "INS_NOT_SUPPORTED"; - case ISO7816.SW_LOGICAL_CHANNEL_NOT_SUPPORTED: - return "LOGICAL_CHANNEL_NOT_SUPPORTED"; - case ISO7816.SW_RECORD_NOT_FOUND: - return "RECORD_NOT_FOUND"; - case ISO7816.SW_SECURE_MESSAGING_NOT_SUPPORTED: - return "SECURE_MESSAGING_NOT_SUPPORTED"; - case ISO7816.SW_SECURITY_STATUS_NOT_SATISFIED: - return "SECURITY_STATUS_NOT_SATISFIED"; - case ISO7816.SW_UNKNOWN: - return "UNKNOWN"; - case ISO7816.SW_WARNING_STATE_UNCHANGED: - return "WARNING_STATE_UNCHANGED"; - case ISO7816.SW_WRONG_DATA: - return "WRONG_DATA"; - case ISO7816.SW_WRONG_LENGTH: - return "WRONG_LENGTH"; - case ISO7816.SW_WRONG_P1P2: - return "WRONG_P1P2"; - case CryptoException.ILLEGAL_VALUE: - return "ILLEGAL_VALUE"; - case CryptoException.UNINITIALIZED_KEY: - return "UNINITIALIZED_KEY"; - case CryptoException.NO_SUCH_ALGORITHM: - return "NO_SUCH_ALG"; - case CryptoException.INVALID_INIT: - return "INVALID_INIT"; - case CryptoException.ILLEGAL_USE: - return "ILLEGAL_USE"; - case ECTesterApplet.SW_SIG_VERIFY_FAIL: - return "SIG_VERIFY_FAIL"; - case ECTesterApplet.SW_DH_DHC_MISMATCH: - return "DH_DHC_MISMATCH"; - case ECTesterApplet.SW_KEYPAIR_NULL: - return "KEYPAIR_NULL"; - case ECTesterApplet.SW_KA_NULL: - return "KA_NULL"; - case ECTesterApplet.SW_SIGNATURE_NULL: - return "SIGNATURE_NULL"; - case ECTesterApplet.SW_OBJECT_NULL: - return "OBJECT_NULL"; - case ECTesterApplet.SW_Exception: - return "Exception"; - case ECTesterApplet.SW_ArrayIndexOutOfBoundsException: - return "ArrayIndexOutOfBoundsException"; - case ECTesterApplet.SW_ArithmeticException: - return "ArithmeticException"; - case ECTesterApplet.SW_ArrayStoreException: - return "ArrayStoreException"; - case ECTesterApplet.SW_NullPointerException: - return "NullPointerException"; - case ECTesterApplet.SW_NegativeArraySizeException: - return "NegativeArraySizeException"; - default: - return "unknown"; - } - } - } - - public static String getSWString(short sw) { - if (sw == ISO7816.SW_NO_ERROR) { - return "OK (0x9000)"; - } else { - String str = getSW(sw); - return String.format("fail (%s, 0x%04x)", str, sw); - } - } - - public static String getParams(short params) { - if (params == 0) { - return ""; - } - List<String> ps = new LinkedList<>(); - short paramMask = EC_Consts.PARAMETER_FP; - while (paramMask <= EC_Consts.PARAMETER_S) { - short paramValue = (short) (paramMask & params); - if (paramValue != 0) { - switch (paramValue) { - case EC_Consts.PARAMETER_FP: - ps.add("P"); - break; - case EC_Consts.PARAMETER_F2M: - ps.add("2^M"); - break; - case EC_Consts.PARAMETER_A: - ps.add("A"); - break; - case EC_Consts.PARAMETER_B: - ps.add("B"); - break; - case EC_Consts.PARAMETER_G: - ps.add("G"); - break; - case EC_Consts.PARAMETER_R: - ps.add("R"); - break; - case EC_Consts.PARAMETER_K: - ps.add("K"); - break; - case EC_Consts.PARAMETER_W: - ps.add("W"); - break; - case EC_Consts.PARAMETER_S: - ps.add("S"); - break; - } - } - paramMask = (short) (paramMask << 1); - } - - if (ps.size() != 0) { - return "[" + String.join(",", ps) + "]"; - } else { - return "unknown"; - } - } - - public static String getTransformation(short transformationType) { - if (transformationType == 0) { - return "NONE"; - } - List<String> names = new LinkedList<>(); - short transformationMask = 1; - while (transformationMask <= EC_Consts.TRANSFORMATION_04_MASK) { - short transformationValue = (short) (transformationMask & transformationType); - if (transformationValue != 0) { - switch (transformationValue) { - case EC_Consts.TRANSFORMATION_FIXED: - names.add("FIXED"); - break; - case EC_Consts.TRANSFORMATION_ONE: - names.add("ONE"); - break; - case EC_Consts.TRANSFORMATION_ZERO: - names.add("ZERO"); - break; - case EC_Consts.TRANSFORMATION_ONEBYTERANDOM: - names.add("ONE_BYTE_RANDOM"); - break; - case EC_Consts.TRANSFORMATION_FULLRANDOM: - names.add("FULL_RANDOM"); - break; - case EC_Consts.TRANSFORMATION_INCREMENT: - names.add("INCREMENT"); - break; - case EC_Consts.TRANSFORMATION_INFINITY: - names.add("INFINITY"); - break; - case EC_Consts.TRANSFORMATION_COMPRESS: - names.add("COMPRESSED"); - break; - case EC_Consts.TRANSFORMATION_COMPRESS_HYBRID: - names.add("HYBRID"); - break; - case EC_Consts.TRANSFORMATION_04_MASK: - names.add("MASK(O4)"); - break; - case EC_Consts.TRANSFORMATION_MAX: - names.add("MAX"); - break; - } - } - transformationMask = (short) ((transformationMask) << 1); - } - if (names.size() != 0) { - return String.join(" + ", names); - } else { - return "unknown"; - } - } - - public static String getKATypeString(byte kaType) { - switch (kaType) { - case EC_Consts.KeyAgreement_ALG_EC_SVDP_DH: - return "ALG_EC_SVDP_DH"; - case EC_Consts.KeyAgreement_ALG_EC_SVDP_DH_PLAIN: - return "ALG_EC_SVDP_DH_PLAIN"; - case EC_Consts.KeyAgreement_ALG_EC_PACE_GM: - return "ALG_EC_PACE_GM"; - case EC_Consts.KeyAgreement_ALG_EC_SVDP_DH_PLAIN_XY: - return "ALG_EC_SVDP_DH_PLAIN_XY"; - case EC_Consts.KeyAgreement_ALG_EC_SVDP_DHC: - return "ALG_EC_SVDP_DHC"; - case EC_Consts.KeyAgreement_ALG_EC_SVDP_DHC_PLAIN: - return "ALG_EC_SVDP_DHC_PLAIN"; - default: - return "unknown"; - } - } - - public static byte getKAType(String kaTypeString) { - switch (kaTypeString) { - case "DH": - case "ALG_EC_SVDP_DH": - return EC_Consts.KeyAgreement_ALG_EC_SVDP_DH; - case "DH_PLAIN": - case "ALG_EC_SVDP_DH_PLAIN": - return EC_Consts.KeyAgreement_ALG_EC_SVDP_DH_PLAIN; - case "PACE_GM": - case "ALG_EC_PACE_GM": - return EC_Consts.KeyAgreement_ALG_EC_PACE_GM; - case "DH_PLAIN_XY": - case "ALG_EC_SVDP_DH_PLAIN_XY": - return EC_Consts.KeyAgreement_ALG_EC_SVDP_DH_PLAIN_XY; - case "DHC": - case "ALG_EC_SVDP_DHC": - return EC_Consts.KeyAgreement_ALG_EC_SVDP_DHC; - case "DHC_PLAIN": - case "ALG_EC_SVDP_DHC_PLAIN": - return EC_Consts.KeyAgreement_ALG_EC_SVDP_DHC_PLAIN; - default: - return 0; - } - } - - public static byte parseKAType(String kaTypeString) { - byte kaType; - try { - kaType = Byte.parseByte(kaTypeString); - } catch (NumberFormatException nfex) { - kaType = getKAType(kaTypeString); - } - return kaType; - } - - public static String getSigTypeString(byte sigType) { - switch (sigType) { - case EC_Consts.Signature_ALG_ECDSA_SHA: - return "ALG_ECDSA_SHA"; - case EC_Consts.Signature_ALG_ECDSA_SHA_224: - return "ALG_ECDSA_SHA_224"; - case EC_Consts.Signature_ALG_ECDSA_SHA_256: - return "ALG_ECDSA_SHA_256"; - case EC_Consts.Signature_ALG_ECDSA_SHA_384: - return "ALG_ECDSA_SHA_384"; - case EC_Consts.Signature_ALG_ECDSA_SHA_512: - return "ALG_ECDSA_SHA_512"; - default: - return "unknown"; - } - } - - public static byte getSigType(String sigTypeString) { - switch (sigTypeString) { - case "ECDSA_SHA": - case "ALG_ECDSA_SHA": - return EC_Consts.Signature_ALG_ECDSA_SHA; - case "ECDSA_SHA_224": - case "ALG_ECDSA_SHA_224": - return EC_Consts.Signature_ALG_ECDSA_SHA_224; - case "ECDSA_SHA_256": - case "ALG_ECDSA_SHA_256": - return EC_Consts.Signature_ALG_ECDSA_SHA_256; - case "ECDSA_SHA_384": - case "ALG_ECDSA_SHA_384": - return EC_Consts.Signature_ALG_ECDSA_SHA_384; - case "ECDSA_SHA_512": - case "ALG_ECDSA_SHA_512": - return EC_Consts.Signature_ALG_ECDSA_SHA_512; - default: - return 0; - } - } - - public static byte parseSigType(String sigTypeString) { - byte sigType; - try { - sigType = Byte.parseByte(sigTypeString); - } catch (NumberFormatException nfex) { - sigType = getSigType(sigTypeString); - } - return sigType; - } - - public static String getKeyTypeString(byte keyClass) { - switch (keyClass) { - case KeyPair.ALG_EC_FP: - return "ALG_EC_FP"; - case KeyPair.ALG_EC_F2M: - return "ALG_EC_F2M"; - default: - return ""; - } - } - - public static String getCurveName(byte curve) { - String result = ""; - switch (curve) { - case EC_Consts.CURVE_default: - result = "default"; - break; - case EC_Consts.CURVE_external: - result = "external"; - break; - case EC_Consts.CURVE_secp112r1: - result = "secp112r1"; - break; - case EC_Consts.CURVE_secp128r1: - result = "secp128r1"; - break; - case EC_Consts.CURVE_secp160r1: - result = "secp160r1"; - break; - case EC_Consts.CURVE_secp192r1: - result = "secp192r1"; - break; - case EC_Consts.CURVE_secp224r1: - result = "secp224r1"; - break; - case EC_Consts.CURVE_secp256r1: - result = "secp256r1"; - break; - case EC_Consts.CURVE_secp384r1: - result = "secp384r1"; - break; - case EC_Consts.CURVE_secp521r1: - result = "secp521r1"; - break; - case EC_Consts.CURVE_sect163r1: - result = "sect163r1"; - break; - case EC_Consts.CURVE_sect233r1: - result = "sect233r1"; - break; - case EC_Consts.CURVE_sect283r1: - result = "sect283r1"; - break; - case EC_Consts.CURVE_sect409r1: - result = "sect409r1"; - break; - case EC_Consts.CURVE_sect571r1: - result = "sect571r1"; - break; - } - return result; - } - - public static String getParameterString(short params) { - String what = ""; - if (params == EC_Consts.PARAMETERS_DOMAIN_F2M || params == EC_Consts.PARAMETERS_DOMAIN_FP) { - what = "curve"; - } else if (params == EC_Consts.PARAMETER_W) { - what = "pubkey"; - } else if (params == EC_Consts.PARAMETER_S) { - what = "privkey"; - } else if (params == EC_Consts.PARAMETERS_KEYPAIR) { - what = "keypair"; - } else { - what = getParams(params); - } - return what; - } -} diff --git a/src/cz/crcs/ectester/common/util/ECUtil.java b/src/cz/crcs/ectester/common/util/ECUtil.java deleted file mode 100644 index e8c0a11..0000000 --- a/src/cz/crcs/ectester/common/util/ECUtil.java +++ /dev/null @@ -1,485 +0,0 @@ -package cz.crcs.ectester.common.util; - -import cz.crcs.ectester.applet.EC_Consts; -import cz.crcs.ectester.common.ec.*; -import cz.crcs.ectester.data.EC_Store; -import cz.crcs.ectester.standalone.consts.SignatureIdent; -import org.bouncycastle.asn1.*; -import org.bouncycastle.crypto.digests.SHA1Digest; -import org.bouncycastle.crypto.signers.PlainDSAEncoding; -import org.bouncycastle.crypto.signers.StandardDSAEncoding; - -import java.io.ByteArrayInputStream; -import java.io.FileInputStream; -import java.io.IOException; -import java.math.BigInteger; -import java.nio.charset.StandardCharsets; -import java.security.KeyPair; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.security.interfaces.ECKey; -import java.security.interfaces.ECPrivateKey; -import java.security.interfaces.ECPublicKey; -import java.security.spec.*; -import java.util.LinkedList; -import java.util.List; -import java.util.Random; - -/** - * @author Jan Jancar johny@neuromancer.sk - */ -public class ECUtil { - private static Random rand = new Random(); - - public static byte[] toByteArray(BigInteger what, int bits) { - byte[] raw = what.toByteArray(); - int bytes = (bits + 7) / 8; - if (raw.length < bytes) { - byte[] result = new byte[bytes]; - System.arraycopy(raw, 0, result, bytes - raw.length, raw.length); - return result; - } - if (bytes < raw.length) { - byte[] result = new byte[bytes]; - System.arraycopy(raw, raw.length - bytes, result, 0, bytes); - return result; - } - return raw; - } - - public static byte[] toX962Compressed(byte[][] point) { - if (point.length != 2) { - return null; - } - byte ybit = (byte) (point[1][point[1].length - 1] % 2); - return ByteUtil.concatenate(new byte[]{(byte) (0x02 | ybit)}, point[0]); - } - - public static byte[] toX962Compressed(ECPoint point, int bits) { - if (point.equals(ECPoint.POINT_INFINITY)) { - return new byte[]{0}; - } - byte[] x = toByteArray(point.getAffineX(), bits); - byte marker = (byte) (0x02 | point.getAffineY().mod(BigInteger.valueOf(2)).byteValue()); - return ByteUtil.concatenate(new byte[]{marker}, x); - } - - public static byte[] toX962Compressed(ECPoint point, ECParameterSpec spec) { - return toX962Compressed(point, spec.getOrder().bitLength()); - } - - public static byte[] toX962Uncompressed(ECPoint point, int bits) { - if (point.equals(ECPoint.POINT_INFINITY)) { - return new byte[]{0}; - } - byte[] x = toByteArray(point.getAffineX(), bits); - byte[] y = toByteArray(point.getAffineY(), bits); - return ByteUtil.concatenate(new byte[]{0x04}, x, y); - } - - public static byte[] toX962Uncompressed(ECPoint point, ECParameterSpec spec) { - return toX962Uncompressed(point, spec.getOrder().bitLength()); - } - - public static byte[] toX962Hybrid(ECPoint point, int bits) { - if (point.equals(ECPoint.POINT_INFINITY)) { - return new byte[]{0}; - } - byte[] x = toByteArray(point.getAffineX(), bits); - byte[] y = toByteArray(point.getAffineY(), bits); - byte marker = (byte) (0x06 | point.getAffineY().mod(BigInteger.valueOf(2)).byteValue()); - return ByteUtil.concatenate(new byte[]{marker}, x, y); - } - - public static byte[] toX962Hybrid(ECPoint point, EllipticCurve curve) { - return toX962Hybrid(point, curve.getField().getFieldSize()); - } - - public static byte[] toX962Hybrid(ECPoint point, ECParameterSpec spec) { - return toX962Hybrid(point, spec.getCurve()); - } - - private static boolean isResidue(BigInteger a, BigInteger p) { - BigInteger exponent = p.subtract(BigInteger.ONE).divide(BigInteger.valueOf(2)); - BigInteger result = a.modPow(exponent, p); - return result.equals(BigInteger.ONE); - } - - private static BigInteger modSqrt(BigInteger a, BigInteger p) { - BigInteger q = p.subtract(BigInteger.ONE); - int s = 0; - while (q.mod(BigInteger.valueOf(2)).equals(BigInteger.ZERO)) { - q = q.divide(BigInteger.valueOf(2)); - s++; - } - - BigInteger z = BigInteger.ONE; - do { - z = z.add(BigInteger.ONE); - } while (isResidue(z, p)); - - BigInteger m = BigInteger.valueOf(s); - BigInteger c = z.modPow(q, p); - BigInteger t = a.modPow(q, p); - BigInteger rExponent = q.add(BigInteger.ONE).divide(BigInteger.valueOf(2)); - BigInteger r = a.modPow(rExponent, p); - - while (!t.equals(BigInteger.ONE)) { - int i = 0; - BigInteger exponent; - do { - exponent = BigInteger.valueOf(2).pow(++i); - } while (!t.modPow(exponent, p).equals(BigInteger.ONE)); - - BigInteger twoExponent = m.subtract(BigInteger.valueOf(i + 1)); - BigInteger b = c.modPow(BigInteger.valueOf(2).modPow(twoExponent, p), p); - m = BigInteger.valueOf(i); - c = b.modPow(BigInteger.valueOf(2), p); - t = t.multiply(c).mod(p); - r = r.multiply(b).mod(p); - } - return r; - } - - public static ECPoint fromX962(byte[] data, EllipticCurve curve) { - if (data == null) { - return null; - } - if (data[0] == 0x04 || data[0] == 0x06 || data[0] == 0x07) { - int len = (data.length - 1) / 2; - byte[] xbytes = new byte[len]; - System.arraycopy(data, 1, xbytes, 0, len); - byte[] ybytes = new byte[len]; - System.arraycopy(data, 1 + len, ybytes, 0, len); - return new ECPoint(new BigInteger(1, xbytes), new BigInteger(1, ybytes)); - } else if (data[0] == 0x02 || data[0] == 0x03) { - if (curve == null) { - throw new IllegalArgumentException(); - } - byte[] xbytes = new byte[data.length - 1]; - System.arraycopy(data, 1, xbytes, 0, data.length - 1); - BigInteger x = new BigInteger(1, xbytes); - BigInteger a = curve.getA(); - BigInteger b = curve.getB(); - - ECField field = curve.getField(); - if (field instanceof ECFieldFp) { - BigInteger p = ((ECFieldFp) field).getP(); - BigInteger alpha = x.modPow(BigInteger.valueOf(3), p); - alpha = alpha.add(x.multiply(a)); - alpha = alpha.add(b); - - if (!isResidue(alpha, p)) { - throw new IllegalArgumentException(); - } - - BigInteger beta = modSqrt(alpha, p); - if (beta.getLowestSetBit() == 0) { - // rightmost bit is one - if (data[0] == 0x02) { - // yp is 0 - beta = p.subtract(beta); - } - } else { - // rightmost bit is zero - if (data[0] == 0x03) { - // yp is 1 - beta = p.subtract(beta); - } - } - - return new ECPoint(x, beta); - } else if (field instanceof ECFieldF2m) { - //TODO - throw new UnsupportedOperationException(); - } - return null; - } else { - throw new IllegalArgumentException(); - } - } - - private static byte[] hashCurve(EC_Curve curve) { - int bytes = (curve.getBits() + 7) / 8; - byte[] result = new byte[bytes]; - SHA1Digest digest = new SHA1Digest(); - byte[] curveName = curve.getId().getBytes(StandardCharsets.US_ASCII); - digest.update(curveName, 0, curveName.length); - int written = 0; - while (written < bytes) { - byte[] dig = new byte[digest.getDigestSize()]; - digest.doFinal(dig, 0); - int toWrite = Math.min(digest.getDigestSize(), bytes - written); - System.arraycopy(dig, 0, result, written, toWrite); - written += toWrite; - digest.update(dig, 0, dig.length); - } - return result; - } - - public static EC_Params fullRandomKey(EC_Curve curve) { - int bytes = (curve.getBits() + 7) / 8; - byte[] result = new byte[bytes]; - rand.nextBytes(result); - BigInteger priv = new BigInteger(1, result); - BigInteger order = new BigInteger(1, curve.getParam(EC_Consts.PARAMETER_R)[0]); - priv = priv.mod(order); - return new EC_Params(EC_Consts.PARAMETER_S, new byte[][]{toByteArray(priv, curve.getBits())}); - } - - public static EC_Params fixedRandomKey(EC_Curve curve) { - byte[] hash = hashCurve(curve); - BigInteger priv = new BigInteger(1, hash); - BigInteger order = new BigInteger(1, curve.getParam(EC_Consts.PARAMETER_R)[0]); - priv = priv.mod(order); - return new EC_Params(EC_Consts.PARAMETER_S, new byte[][]{toByteArray(priv, curve.getBits())}); - } - - private static BigInteger computeRHS(BigInteger x, BigInteger a, BigInteger b, BigInteger p) { - BigInteger rhs = x.modPow(BigInteger.valueOf(3), p); - rhs = rhs.add(a.multiply(x)).mod(p); - rhs = rhs.add(b).mod(p); - return rhs; - } - - public static EC_Params fullRandomPoint(EC_Curve curve) { - EllipticCurve ecCurve = curve.toCurve(); - - BigInteger p; - if (ecCurve.getField() instanceof ECFieldFp) { - ECFieldFp fp = (ECFieldFp) ecCurve.getField(); - p = fp.getP(); - if (!p.isProbablePrime(20)) { - return null; - } - } else { - //TODO - return null; - } - BigInteger x; - BigInteger rhs; - do { - x = new BigInteger(ecCurve.getField().getFieldSize(), rand).mod(p); - rhs = computeRHS(x, ecCurve.getA(), ecCurve.getB(), p); - } while (!isResidue(rhs, p)); - BigInteger y = modSqrt(rhs, p); - if (rand.nextBoolean()) { - y = p.subtract(y); - } - - byte[] xArr = toByteArray(x, ecCurve.getField().getFieldSize()); - byte[] yArr = toByteArray(y, ecCurve.getField().getFieldSize()); - return new EC_Params(EC_Consts.PARAMETER_W, new byte[][]{xArr, yArr}); - } - - public static EC_Params fixedRandomPoint(EC_Curve curve) { - EllipticCurve ecCurve = curve.toCurve(); - - BigInteger p; - if (ecCurve.getField() instanceof ECFieldFp) { - ECFieldFp fp = (ECFieldFp) ecCurve.getField(); - p = fp.getP(); - if (!p.isProbablePrime(20)) { - return null; - } - } else { - //TODO - return null; - } - - BigInteger x = new BigInteger(1, hashCurve(curve)).mod(p); - BigInteger rhs = computeRHS(x, ecCurve.getA(), ecCurve.getB(), p); - while (!isResidue(rhs, p)) { - x = x.add(BigInteger.ONE).mod(p); - rhs = computeRHS(x, ecCurve.getA(), ecCurve.getB(), p); - } - BigInteger y = modSqrt(rhs, p); - if (y.bitCount() % 2 == 0) { - y = p.subtract(y); - } - - byte[] xArr = toByteArray(x, ecCurve.getField().getFieldSize()); - byte[] yArr = toByteArray(y, ecCurve.getField().getFieldSize()); - return new EC_Params(EC_Consts.PARAMETER_W, new byte[][]{xArr, yArr}); - } - - public static ECPoint toPoint(EC_Params params) { - return new ECPoint( - new BigInteger(1, params.getParam(EC_Consts.PARAMETER_W)[0]), - new BigInteger(1, params.getParam(EC_Consts.PARAMETER_W)[1])); - } - - public static BigInteger toScalar(EC_Params params) { - return new BigInteger(1, params.getParam(EC_Consts.PARAMETER_S)[0]); - } - - public static ECPublicKey toPublicKey(EC_Key.Public pubkey) { - if (pubkey == null) { - return null; - } - EC_Curve curve = EC_Store.getInstance().getObject(EC_Curve.class, pubkey.getCurve()); - if (curve == null) { - throw new IllegalArgumentException("pubkey curve not found: " + pubkey.getCurve()); - } - return new RawECPublicKey(toPoint(pubkey), curve.toSpec()); - } - - public static ECPrivateKey toPrivateKey(EC_Key.Private privkey) { - if (privkey == null) { - return null; - } - EC_Curve curve = EC_Store.getInstance().getObject(EC_Curve.class, privkey.getCurve()); - if (curve == null) { - throw new IllegalArgumentException("privkey curve not found: " + privkey.getCurve()); - } - return new RawECPrivateKey(toScalar(privkey), curve.toSpec()); - } - - public static KeyPair toKeyPair(EC_Keypair kp) { - if (kp == null) { - return null; - } - EC_Curve curve = EC_Store.getInstance().getObject(EC_Curve.class, kp.getCurve()); - if (curve == null) { - throw new IllegalArgumentException("keypair curve not found: " + kp.getCurve()); - } - ECPublicKey pubkey = new RawECPublicKey(toPoint(kp), curve.toSpec()); - ECPrivateKey privkey = new RawECPrivateKey(toScalar(kp), curve.toSpec()); - return new KeyPair(pubkey, privkey); - } - - public static BigInteger recoverSignatureNonce(byte[] signature, byte[] data, BigInteger privkey, ECParameterSpec params, String hashAlgo, String sigType) { - SignatureIdent sigIdent = SignatureIdent.get(hashAlgo + "with" + sigType); - if (sigIdent == null) { - return null; - } - return recoverSignatureNonce(signature, data, privkey, params, sigIdent); - } - - public static BigInteger recoverSignatureNonce(byte[] signature, byte[] data, BigInteger privkey, ECParameterSpec params, SignatureIdent sigIdent) { - // Parse the types out of SignatureIdent. - String hashAlgo = sigIdent.getHashAlgo(); - String sigType = sigIdent.getSigType(); - if (sigType == null) { - sigType = sigIdent.toString(); - } - // We do not know how to reconstruct those nonces so far. - // sigType.contains("ECKCDSA") || sigType.contains("ECNR") || sigType.contains("SM2") - if (!sigType.contains("ECDSA")) { - return null; - } - try { - int bitSize = params.getOrder().bitLength(); - // Hash the data. - byte[] hash; - if (hashAlgo == null || hashAlgo.equals("NONE")) { - hash = data; - } else { - MessageDigest md = MessageDigest.getInstance(hashAlgo); - hash = md.digest(data); - } - // Trim bitSize of rightmost bits. - BigInteger hashInt = new BigInteger(1, hash); - int hashBits = hashInt.bitLength(); - if (hashBits > bitSize) { - hashInt = hashInt.shiftRight(hashBits - bitSize); - } - - // Parse signature - BigInteger[] sigPair; - if (sigType.contains("CVC") || sigType.contains("PLAIN")) { - sigPair = PlainDSAEncoding.INSTANCE.decode(params.getOrder(), signature); - } else { - sigPair = StandardDSAEncoding.INSTANCE.decode(params.getOrder(), signature); - } - BigInteger r = sigPair[0]; - BigInteger s = sigPair[1]; - - BigInteger rd = privkey.multiply(r).mod(params.getOrder()); - BigInteger hrd = hashInt.add(rd).mod(params.getOrder()); - return s.modInverse(params.getOrder()).multiply(hrd).mod(params.getOrder()); - } catch (NoSuchAlgorithmException | IOException | ArithmeticException ex) { - ex.printStackTrace(); - return null; - } - } - - public static EC_Params joinParams(EC_Params... params) { - List<EC_Params> paramList = new LinkedList<>(); - short paramMask = 0; - int len = 0; - for (EC_Params param : params) { - if (param == null) { - continue; - } - int i = 0; - for (; i + 1 < paramList.size(); ++i) { - if (paramList.get(i + 1).getParams() == param.getParams()) { - throw new IllegalArgumentException(); - } - if (paramList.get(i + 1).getParams() < param.getParams()) { - break; - } - } - paramList.add(i, param); - paramMask |= param.getParams(); - len += param.numParams(); - } - - byte[][] res = new byte[len][]; - int i = 0; - for (EC_Params param : params) { - for (byte[] data : param.getData()) { - res[i++] = data.clone(); - } - } - return new EC_Params(paramMask, res); - } - - public static EC_Params loadParams(short params, String named, String file) throws IOException { - EC_Params result = null; - if (file != null) { - result = new EC_Params(params); - - FileInputStream in = new FileInputStream(file); - result.readCSV(in); - in.close(); - } else if (named != null) { - if (params == EC_Consts.PARAMETER_W) { - result = EC_Store.getInstance().getObject(EC_Key.Public.class, named); - } else if (params == EC_Consts.PARAMETER_S) { - result = EC_Store.getInstance().getObject(EC_Key.Private.class, named); - } - - if (result == null) { - result = EC_Store.getInstance().getObject(EC_Keypair.class, named); - } - } - return result; - } - - public static ECKey loadKey(short params, String named, String file, AlgorithmParameterSpec spec) throws IOException { - if (params == EC_Consts.PARAMETERS_KEYPAIR) { - throw new IllegalArgumentException(); - } - EC_Params param = loadParams(params, named, file); - if (param != null) { - if (params == EC_Consts.PARAMETER_W) { - return new RawECPublicKey(toPoint(param), (ECParameterSpec) spec); - } else if (params == EC_Consts.PARAMETER_S) { - return new RawECPrivateKey(toScalar(param), (ECParameterSpec) spec); - } - } - return null; - } - - public static boolean equalKeyPairParameters(ECPrivateKey priv, ECPublicKey pub) { - if(priv == null || pub == null) { - return false; - } - return priv.getParams().getCurve().equals(pub.getParams().getCurve()) && - priv.getParams().getCofactor() == pub.getParams().getCofactor() && - priv.getParams().getGenerator().equals(pub.getParams().getGenerator()) && - priv.getParams().getOrder().equals(pub.getParams().getOrder()); - } -} diff --git a/src/cz/crcs/ectester/common/util/FileUtil.java b/src/cz/crcs/ectester/common/util/FileUtil.java deleted file mode 100644 index e6e319b..0000000 --- a/src/cz/crcs/ectester/common/util/FileUtil.java +++ /dev/null @@ -1,99 +0,0 @@ -package cz.crcs.ectester.common.util; - -import cz.crcs.ectester.common.output.TeeOutputStream; - -import java.io.*; -import java.net.URL; -import java.net.URLConnection; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.nio.file.StandardCopyOption; -import java.util.LinkedList; -import java.util.List; - -/** - * @author Jan Jancar johny@neuromancer.sk - */ -public class FileUtil { - private static Path appData = null; - public static String LIB_RESOURCE_DIR = "/cz/crcs/ectester/standalone/libs/jni/"; - - public static OutputStream openStream(String[] files) throws FileNotFoundException { - if (files == null) { - return null; - } - List<OutputStream> outs = new LinkedList<>(); - for (String fileOut : files) { - outs.add(new FileOutputStream(fileOut)); - } - return new TeeOutputStream(outs.toArray(new OutputStream[0])); - } - - public static OutputStreamWriter openFiles(String[] files) throws FileNotFoundException { - if (files == null) { - return null; - } - return new OutputStreamWriter(openStream(files)); - } - - public static Path getAppData() { - if (appData != null) { - return appData; - } - - if (System.getProperty("os.name").startsWith("Windows")) { - appData = Paths.get(System.getenv("AppData")); - } else { - if (System.getProperty("os.name").startsWith("Linux")) { - String dataHome = System.getenv("XDG_DATA_HOME"); - if (dataHome != null) { - appData = Paths.get(dataHome); - } else { - appData = Paths.get(System.getProperty("user.home"), ".local", "share"); - } - } else { - appData = Paths.get(System.getProperty("user.home"), ".local", "share"); - } - } - return appData; - } - - public static boolean isNewer(URLConnection jarConn, Path realPath) throws IOException { - if (realPath.toFile().isFile()) { - long jarModified = jarConn.getLastModified(); - long realModified = Files.getLastModifiedTime(realPath).toMillis(); - return jarModified > realModified; - } - return true; - } - - public static boolean writeNewer(String resourcePath, Path outPath) throws IOException { - URL reqURL = FileUtil.class.getResource(resourcePath); - if (reqURL == null) { - return false; - } - URLConnection reqConn = reqURL.openConnection(); - if (isNewer(reqConn, outPath)) { - Files.copy(reqConn.getInputStream(), outPath, StandardCopyOption.REPLACE_EXISTING); - } - reqConn.getInputStream().close(); - return true; - } - - public static Path getLibDir() { - return getAppData().resolve("ECTesterStandalone"); - } - - public static Path getRequirementsDir() { - return getLibDir().resolve("lib"); - } - - public static String getLibSuffix() { - if (System.getProperty("os.name").startsWith("Windows")) { - return "dll"; - } else { - return "so"; - } - } -} diff --git a/src/cz/crcs/ectester/common/util/Util.java b/src/cz/crcs/ectester/common/util/Util.java deleted file mode 100644 index 5b0cd79..0000000 --- a/src/cz/crcs/ectester/common/util/Util.java +++ /dev/null @@ -1,28 +0,0 @@ -package cz.crcs.ectester.common.util; - -/** - * @author Jan Jancar johny@neuromancer.sk - */ -public class Util { - public static long convertTime(long nanos, String timeUnit) { - switch (timeUnit) { - default: - case "nano": - return nanos; - case "micro": - return nanos / 1000; - case "milli": - return nanos / 1000000; - } - } - - public static int getVersion() { - String version = System.getProperty("java.version"); - if(version.startsWith("1.")) { - version = version.substring(2, 3); - } else { - int dot = version.indexOf("."); - if(dot != -1) { version = version.substring(0, dot); } - } return Integer.parseInt(version); - } -} |
