Skip to content
Snippets Groups Projects
Commit c8d09a54 authored by Benoit Lavenier's avatar Benoit Lavenier
Browse files

Add nuiton-config, and plug it to Unit Test

parent d0f5f14d
Branches
Tags
No related merge requests found
Showing
with 253 additions and 163 deletions
package io.ucoin.client.core.technical.crypto;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.abstractj.kalium.NaCl;
import org.abstractj.kalium.NaCl.Sodium;
/**
* Usage:
* <pre>
* String crypto = SimpleCrypto.encrypt(masterpassword, cleartext)
* ...
* String cleartext = SimpleCrypto.decrypt(masterpassword, crypto)
* </pre>
* @author ferenc.hechler
*/
public class SimpleCrypto {
public static String encrypt(String seed, String cleartext) throws Exception {
byte[] rawKey = getRawKey(seed.getBytes());
byte[] result = encrypt(rawKey, cleartext.getBytes());
return toHex(result);
}
public static String decrypt(String seed, String encrypted) throws Exception {
byte[] rawKey = getRawKey(seed.getBytes());
byte[] enc = toByte(encrypted);
byte[] result = decrypt(rawKey, enc);
return new String(result);
}
private static byte[] getRawKey(byte[] seed) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("EC");
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
sr.setSeed(seed);
kgen.init(128, sr); // 192 and 256 bits may not be available
SecretKey skey = kgen.generateKey();
byte[] raw = skey.getEncoded();
return raw;
}
private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(clear);
return encrypted;
}
private static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decrypted = cipher.doFinal(encrypted);
return decrypted;
}
public static String toHex(String txt) {
return toHex(txt.getBytes());
}
public static String fromHex(String hex) {
return new String(toByte(hex));
}
public static byte[] toByte(String hexString) {
int len = hexString.length()/2;
byte[] result = new byte[len];
for (int i = 0; i < len; i++)
result[i] = Integer.valueOf(hexString.substring(2*i, 2*i+2), 16).byteValue();
return result;
}
public static String toHex(byte[] buf) {
if (buf == null)
return "";
StringBuffer result = new StringBuffer(2*buf.length);
for (int i = 0; i < buf.length; i++) {
appendHex(result, buf[i]);
}
return result.toString();
}
private final static String HEX = "0123456789ABCDEF";
private static void appendHex(StringBuffer sb, byte b) {
sb.append(HEX.charAt((b>>4)&0x0f)).append(HEX.charAt(b&0x0f));
}
}
\ No newline at end of file
io.ucoin.client.core.service.BlockchainService
\ No newline at end of file
io.ucoin.client.core.config.ConfigurationProvider
\ No newline at end of file
quadrige2.config.parse.error=Erreur lors de la lecture de la ligne de commande
\ No newline at end of file
package io.ucoin.client.core; package io.ucoin.client.core;
public class TestConfig { import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
public static String getNodeUrl() { public class TestFixtures {
public String getNodeUrl() {
return "http://twiced.fr:9101"; return "http://twiced.fr:9101";
} }
public static String getUid() { public String getUid() {
return "cgeek"; return "cgeek";
} }
public static String getKeySalt() { public String getKeySalt() {
return "a salt string"; return "a salt string";
} }
public static String getKeyPassword() { public String getKeyPassword() {
return "a password string"; return "a password string";
} }
/** /**
* Th expected public key generated from getKeySalt() and getKeyPassword() * Th expected public key generated from getKeySalt() and getKeyPassword()
*
* @return * @return
*/ */
public static String getExpectedPublicKey() { public String getExpectedPublicKey() {
return "FedYyZ64tvNj7Z7dw2gt5Hssayr9o8t8wPvi16jWAxqY"; return "FedYyZ64tvNj7Z7dw2gt5Hssayr9o8t8wPvi16jWAxqY";
} }
} }
package io.ucoin.client.core;
import io.ucoin.client.core.config.Configuration;
import io.ucoin.client.core.config.ConfigurationOption;
import io.ucoin.client.core.service.ServiceLocator;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Locale;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import org.nuiton.i18n.I18n;
import org.nuiton.i18n.init.DefaultI18nInitializer;
import org.nuiton.i18n.init.UserI18nInitializer;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
public class TestResource implements TestRule {
private static final Log log = LogFactory.getLog(TestResource.class);
public static long BUILD_TIMESTAMP = System.nanoTime();
public static TestResource create() {
return new TestResource(null);
}
public static TestResource create(String configName) {
return new TestResource(configName);
}
private TestFixtures fixtures = new TestFixtures();
private File resourceDirectory;
private String configName;
private boolean witherror = false;
protected Class<?> testClass;
protected TestResource(String configName) {
this.configName = configName;
}
public TestFixtures getFixtures() {
return fixtures;
}
public File getResourceDirectory(String name) {
return new File(resourceDirectory, name);
}
@Override
public Statement apply(final Statement base, final Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
before(description);
try {
base.evaluate();
} catch (Throwable e) {
witherror = true;
} finally {
after(description);
}
}
};
}
protected void before(Description description) throws Throwable {
testClass = description.getTestClass();
boolean defaultDbName = StringUtils.isEmpty(configName);
if (log.isInfoEnabled()) {
log.info("Prepare test " + testClass);
}
resourceDirectory = getTestSpecificDirectory(testClass, "");
// check that config file is in classpath (avoid to find out why it does not works...)
String configFilename = getConfigFilesPrefix();
if (!defaultDbName) {
configFilename += "-" + configName;
}
configFilename += ".properties";
InputStream resourceAsStream = getClass().getResourceAsStream("/" + configFilename);
Preconditions.checkNotNull(resourceAsStream, "Could not find " + configFilename + " in test class-path");
// Initialize configuration
initConfiguration(configFilename);
// Init i18n
initI18n();
// Initialize service locator
ServiceLocator.instance().init();
}
protected void after(Description description) throws Throwable {
}
/**
* Convenience methods that could be override to initialize other configuration
*
* @param configFilename
* @param configArgs
*/
protected void initConfiguration(String configFilename) {
String[] configArgs = getConfigArgs();
Configuration config = new Configuration(configFilename, configArgs);
Configuration.setInstance(config);
}
protected void initI18n() throws IOException {
Configuration config = Configuration.instance();
// --------------------------------------------------------------------//
// init i18n
// --------------------------------------------------------------------//
File i18nDirectory = new File(config.getDataDirectory(), "i18n");
if (i18nDirectory.exists()) {
// clean i18n cache
FileUtils.cleanDirectory(i18nDirectory);
}
FileUtils.forceMkdir(i18nDirectory);
if (log.isDebugEnabled()) {
log.debug("I18N directory: " + i18nDirectory);
}
Locale i18nLocale = config.getI18nLocale();
if (log.isInfoEnabled()) {
log.info(String.format("Starts i18n with locale [%s] at [%s]",
i18nLocale, i18nDirectory));
}
I18n.init(new UserI18nInitializer(
i18nDirectory, new DefaultI18nInitializer(getI18nBundleName())),
i18nLocale);
}
/**
* Return configuration files prefix (i.e. 'allegro-test')
* Could be override by external project
*
* @return the prefix to use to retrieve configuration files
*/
protected String getConfigFilesPrefix() {
return "ucoinj-test";
}
protected String getI18nBundleName() {
return "ucoinj-core-i18n";
}
protected String[] getConfigArgs() {
List<String> configArgs = Lists.newArrayList();
configArgs.addAll(Lists.newArrayList(
"--option", ConfigurationOption.BASEDIR.getKey(), resourceDirectory.getAbsolutePath()));
return configArgs.toArray(new String[configArgs.size()]);
}
protected File getTestSpecificDirectory(Class<?> testClass,
String name) throws IOException {
// Trying to look for the temporary folder to store data for the test
String tempDirPath = System.getProperty("java.io.tmpdir");
if (tempDirPath == null) {
// can this really occur ?
tempDirPath = "";
if (log.isWarnEnabled()) {
log.warn("'\"java.io.tmpdir\" not defined");
}
}
File tempDirFile = new File(tempDirPath);
// create the directory to store database data
String dataBasePath = testClass.getName()
+ File.separator // a directory with the test class name
+ name // a sub-directory with the method name
+ '_'
+ BUILD_TIMESTAMP; // and a timestamp
File databaseFile = new File(tempDirFile, dataBasePath);
FileUtils.forceMkdir(databaseFile);
return databaseFile;
}
}
package io.ucoin.client.core.service; package io.ucoin.client.core.service;
import io.ucoin.client.core.TestConfig; import io.ucoin.client.core.TestResource;
import io.ucoin.client.core.model.BlockchainBlock; import io.ucoin.client.core.model.BlockchainBlock;
import io.ucoin.client.core.model.BlockchainParameter; import io.ucoin.client.core.model.BlockchainParameter;
import io.ucoin.client.core.model.Identity; import io.ucoin.client.core.model.Identity;
...@@ -9,16 +9,21 @@ import io.ucoin.client.core.model.Member; ...@@ -9,16 +9,21 @@ import io.ucoin.client.core.model.Member;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.junit.Assert; import org.junit.Assert;
import org.junit.ClassRule;
import org.junit.Test; import org.junit.Test;
public class BlockchainServiceTest { public class BlockchainServiceTest {
private static final Log log = LogFactory.getLog(BlockchainServiceTest.class); private static final Log log = LogFactory.getLog(BlockchainServiceTest.class);
@ClassRule
public static final TestResource resource = TestResource.create();
@Test @Test
public void getParameters() throws Exception { public void getParameters() throws Exception {
BlockchainService blockchainService = new BlockchainService(TestConfig.getNodeUrl()); BlockchainService blockchainService = new BlockchainService();
BlockchainParameter result = blockchainService.getParameters(); BlockchainParameter result = blockchainService.getParameters();
// close // close
...@@ -31,7 +36,7 @@ public class BlockchainServiceTest { ...@@ -31,7 +36,7 @@ public class BlockchainServiceTest {
@Test @Test
public void getBlock() throws Exception { public void getBlock() throws Exception {
BlockchainService blockchainService = new BlockchainService(TestConfig.getNodeUrl()); BlockchainService blockchainService = new BlockchainService();
BlockchainBlock result = blockchainService.getBlock(0); BlockchainBlock result = blockchainService.getBlock(0);
// close // close
blockchainService.close(); blockchainService.close();
......
package io.ucoin.client.core.service; package io.ucoin.client.core.service;
import io.ucoin.client.core.TestConfig; import io.ucoin.client.core.TestResource;
import io.ucoin.client.core.model.WotLookupResults; import io.ucoin.client.core.model.WotLookupResults;
import io.ucoin.client.core.model.WotLookupUId; import io.ucoin.client.core.model.WotLookupUId;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.junit.Assert; import org.junit.Assert;
import org.junit.ClassRule;
import org.junit.Test; import org.junit.Test;
public class WotServiceTest { public class WotServiceTest {
private static final Log log = LogFactory.getLog(WotServiceTest.class); private static final Log log = LogFactory.getLog(WotServiceTest.class);
@ClassRule
public static final TestResource resource = TestResource.create();
@Test @Test
public void find() throws Exception { public void find() throws Exception {
WotService service = new WotService(TestConfig.getNodeUrl()); WotService service = new WotService();
WotLookupResults results = service.find(TestConfig.getUid()); WotLookupResults results = service.find(resource.getFixtures().getUid());
Assert.assertNotNull(results); Assert.assertNotNull(results);
// close // close
...@@ -27,8 +30,8 @@ public class WotServiceTest { ...@@ -27,8 +30,8 @@ public class WotServiceTest {
@Test @Test
public void findByUid() throws Exception { public void findByUid() throws Exception {
WotService service = new WotService(TestConfig.getNodeUrl()); WotService service = new WotService();
WotLookupUId result = service.findByUid(TestConfig.getUid()); WotLookupUId result = service.findByUid(resource.getFixtures().getUid());
Assert.assertNotNull(result); Assert.assertNotNull(result);
// close // close
......
// Copyright (C) 2011 - Will Glozer. All rights reserved.
package io.ucoin.client.core.technical;
public class CryptoTestUtil {
public static byte[] decode(String str) {
byte[] bytes = new byte[str.length() / 2];
int index = 0;
for (int i = 0; i < str.length(); i += 2) {
int high = hexValue(str.charAt(i));
int low = hexValue(str.charAt(i + 1));
bytes[index++] = (byte) ((high << 4) + low);
}
return bytes;
}
public static int hexValue(char c) {
return c >= 'a' ? c - 87 : c - 48;
}
}
package io.ucoin.client.core.technical; package io.ucoin.client.core.technical;
import io.ucoin.client.core.TestConfig; import io.ucoin.client.core.TestResource;
import io.ucoin.client.core.technical.crypto.nacl.NaCl; import io.ucoin.client.core.technical.crypto.nacl.NaCl;
import io.ucoin.client.core.technical.crypto.nacl.curve25519xsalsa20poly1305; import io.ucoin.client.core.technical.crypto.nacl.curve25519xsalsa20poly1305;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException; import java.security.GeneralSecurityException;
import junit.framework.Assert;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.junit.Assert;
import org.junit.ClassRule;
import org.junit.Ignore; import org.junit.Ignore;
import org.junit.Test; import org.junit.Test;
...@@ -20,25 +20,21 @@ import com.lambdaworks.crypto.SCrypt; ...@@ -20,25 +20,21 @@ import com.lambdaworks.crypto.SCrypt;
public class CryptoUtilsTest { public class CryptoUtilsTest {
private static final Log log = LogFactory.getLog(CryptoUtilsTest.class); private static final Log log = LogFactory.getLog(CryptoUtilsTest.class);
@ClassRule
public static final TestResource resource = TestResource.create();
public static int SEED_LENGTH = 32; // Length of the key public static int SEED_LENGTH = 32; // Length of the key
public static int crypto_sign_BYTES = 64; public static int crypto_sign_BYTES = 64;
static final int crypto_secretbox_KEYBYTES = 32; private byte[] precomputed = new byte[curve25519xsalsa20poly1305.crypto_secretbox_BEFORENMBYTES];
static final int crypto_secretbox_NONCEBYTES = 24;
static final int crypto_secretbox_ZEROBYTES = 32;
static final int crypto_secretbox_BOXZEROBYTES = 16;
static final int crypto_secretbox_BEFORENMBYTES = 32;
private byte[] precomputed = new byte[crypto_secretbox_BEFORENMBYTES];
@Test @Test
@Ignore @Ignore
// FIXME BLA : should be implemented using Kalium (but works only on Linux OS ?) // FIXME BLA : should be implemented using Kalium (but works only on Linux OS ?)
public void testScrypt() throws UnsupportedEncodingException, GeneralSecurityException { public void testScrypt() throws UnsupportedEncodingException, GeneralSecurityException {
String salt = TestConfig.getKeySalt(); String salt = resource.getFixtures().getKeySalt();
String password = TestConfig.getKeyPassword(); String password = resource.getFixtures().getKeyPassword();
byte[] P, S; byte[] P, S;
int N, r, p, dkLen; int N, r, p, dkLen;
...@@ -46,8 +42,8 @@ public class CryptoUtilsTest { ...@@ -46,8 +42,8 @@ public class CryptoUtilsTest {
// empty key & salt test missing because unsupported by JCE // empty key & salt test missing because unsupported by JCE
S = TestConfig.getKeySalt().getBytes("UTF-8"); S = resource.getFixtures().getKeySalt().getBytes("UTF-8");
P = TestConfig.getKeyPassword().getBytes("UTF-8"); P = resource.getFixtures().getKeyPassword().getBytes("UTF-8");
N = 4096; N = 4096;
r = 16; r = 16;
p = 1; p = 1;
...@@ -55,32 +51,25 @@ public class CryptoUtilsTest { ...@@ -55,32 +51,25 @@ public class CryptoUtilsTest {
byte[] chain = SCrypt.scrypt(P, S, N, r, p, SEED_LENGTH); byte[] chain = SCrypt.scrypt(P, S, N, r, p, SEED_LENGTH);
String hash = new String(Base64.encode(chain)); String hash = new String(Base64.encode(chain));
System.out.println(hash); System.out.println("Scrypt return: " + hash);
byte[] nonce = new byte[32]; byte[] nonce = new byte[32];
byte[] input = NaCl.getBinary(hash); byte[] input = NaCl.getBinary(hash);
byte[] paddedinput = new byte[input.length + crypto_secretbox_ZEROBYTES]; byte[] paddedinput = new byte[input.length + curve25519xsalsa20poly1305.crypto_secretbox_ZEROBYTES];
byte[] output = new byte[input.length + crypto_secretbox_ZEROBYTES]; byte[] output = new byte[input.length + curve25519xsalsa20poly1305.crypto_secretbox_ZEROBYTES];
System.arraycopy(input, 0, paddedinput, crypto_secretbox_ZEROBYTES, input.length); System.arraycopy(input, 0, paddedinput, curve25519xsalsa20poly1305.crypto_secretbox_ZEROBYTES, input.length);
curve25519xsalsa20poly1305.crypto_box_afternm(output, paddedinput, paddedinput.length, nonce, this.precomputed); curve25519xsalsa20poly1305.crypto_box_afternm(output, paddedinput, paddedinput.length, nonce, this.precomputed);
char[] resultKey = Base64.encode(output); curve25519xsalsa20poly1305.crypto_box_getpublickey(output, chain);
System.out.println(resultKey);
// TODO BLA : fixe this
Assert.assertEquals(TestConfig.getExpectedPublicKey(), new String(resultKey));
//.crypto_sign_ed25519_seed_keypair();
char[] resultKey = Base64.encode(output);
System.out.println("Expected public key:" + new String(resource.getFixtures().getExpectedPublicKey()));
System.out.println("Result is: " + new String(resultKey));
// String enc = SCryptUtil.scrypt("neb", N, r, p); // TODO BLA : fix this
// System.out.println(enc); Assert.assertEquals(resource.getFixtures().getExpectedPublicKey(), new String(resultKey));
// Mac mac = Mac.getInstance("ed");
// mac.init(new SecretKeySpec(passwd, "HmacSHA256"));
//assertArrayEquals(CryptoTestUtil.decode(DK), chain);
} }
} }
ucoinj.node.host=server.e-is.pro
ucoinj.node.port=9101
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment