private static PublicKey readKeyAndGetPublic(String keyFilePath) throws IOException { PublicKey key; if (keyFilePath.endsWith(".private.unikey")) key = new PrivateKey(Do.read(keyFilePath)).getPublicKey(); else if (keyFilePath.endsWith(".public.unikey")) key = new PublicKey(Do.read(keyFilePath)); else { try { key = new PrivateKey(Do.read(keyFilePath)).getPublicKey(); } catch (EncryptionError e) { key = new PublicKey(Do.read(keyFilePath)); } } return key; }
/** * Each adapter will try to send blocks until have got special {@link Packet} with type {@link PacketTypes#ACK}, * that means receiver have got block. So when we got block, but something went wrong - call this method. Note that * for success blocks needs to call {@link UDPAdapter#sendAck(SessionReader, Integer)} * @param nodeNumber node id in which sending is * @param packetId is id of block we have got. */ private void sendNack(Integer nodeNumber, Integer packetId) { try { NodeInfo destination = netConfig.getInfo(nodeNumber); if (destination != null) { report(logLabel, ()->"send nack to "+nodeNumber, VerboseLevel.DETAILED); byte[] randomSeed = Do.randomBytes(64); byte[] data = Boss.dumpToArray(Arrays.asList(packetId, randomSeed)); byte[] sign = new PrivateKey(ownPrivateKey.pack()).sign(data, HashType.SHA512); byte[] payload = Boss.dumpToArray(Arrays.asList(data, sign)); Packet packet = new Packet(0, myNodeInfo.getNumber(), nodeNumber, PacketTypes.NACK, payload); sendPacket(destination, packet); } } catch (EncryptionError e) { callErrorCallbacks("(sendNack) can't send NACK, EncryptionError: " + e); } }
@Override public byte[] decrypt(final byte[] encrypted) throws EncryptionError { // mini-pooling of keys for parallel processing: if (inUse.getAndSet(true)) { // our copy is in use - create a copy for later use synchronized (copyMutex) { // we lock only to create a copy if (copy == null) copy = new PrivateKey(pack()); } // now the copy will do the same: encrypt or create a copy... return copy.decrypt(encrypted); } else { try { return privateKey.decrypt(encrypted); } finally { inUse.set(false); } } }
/** * Sign the data with a given key. * * @param key is {@link PrivateKey} to sign with. * @param data to be sign with key. * @param savePublicKey if true key will stored in the {@link ExtendedSignature}. * * @return binary signature */ static public byte[] sign(PrivateKey key, byte[] data, boolean savePublicKey) { try { byte[] targetSignature = ExtendedSignature.createTargetSignature(key.getPublicKey(),data,savePublicKey); return ExtendedSignature.of(targetSignature, key.sign(targetSignature, HashType.SHA512), key.sign(targetSignature, HashType.SHA3_384)); } catch (EncryptionError e) { throw new RuntimeException("signature failed", e); } }
private static void doGenerateKeyPair() throws IOException { PrivateKey k = new PrivateKey((Integer) options.valueOf("s")); String name = (String) options.valueOf("g"); if(options.has("password")) { new FileOutputStream(name + ".private.unikey").write(k.packWithPassword((String) options.valueOf("password"))); } else { new FileOutputStream(name + ".private.unikey").write(k.pack()); } new FileOutputStream(name + ".public.unikey").write(k.getPublicKey().pack()); if (options.has("base64")) { new FileOutputStream(name + ".public.unikey.txt") .write(Base64.encodeLines(k.getPublicKey().pack()).getBytes()); } System.out.println("New key pair ready"); }
@Override public byte[] fingerprint() { return getPublicKey().fingerprint(); }
@Override public Object deserialize(Binder binder, BiDeserializer deserializer) { try { return new PrivateKey(binder.getBinaryOrThrow("packed")); } catch (EncryptionError encryptionError) { return null; } }
@Test public void sign() throws Exception { PrivateKey key1 = new PrivateKey(2048); PrivateKey key2 = new PrivateKey(2048); Files.write(Paths.get(basePath + "signKey1.privateKey.unikey"),key1.pack(), StandardOpenOption.CREATE, StandardOpenOption.WRITE); Files.write(Paths.get(basePath + "signKey2.privateKey.unikey"),key2.pack(), StandardOpenOption.CREATE, StandardOpenOption.WRITE); HashSet<PrivateKey> issuers = new HashSet<>(); issuers.add(key1); HashSet<PublicKey> owners = new HashSet<>(); owners.add(key1.getPublicKey()); Contract contract = ContractsService.createTokenContract(issuers, owners, new BigDecimal("10000.50"), new BigDecimal("0.01")); SimpleRole issuer1 = new SimpleRole("issuer1",new KeyRecord(key1.getPublicKey())); SimpleRole issuer2 = new SimpleRole("issuer2",new KeyRecord(key2.getPublicKey())); ListRole issuer = new ListRole("issuer",ListRole.Mode.ALL,Do.listOf(issuer1,issuer2)); contract.registerRole(issuer); contract.seal(); contract.check(); assertFalse(contract.isOk()); Files.write(Paths.get(basePath + "sign.unicon"),contract.getPackedTransaction(), StandardOpenOption.CREATE, StandardOpenOption.WRITE); assertFalse(CLIMain.loadContract(basePath + "sign.unicon").check()); callMain("--sign",basePath + "sign.unicon","--keys",basePath + "signKey2.privateKey.unikey"); callMain("--sign",basePath + "sign.unicon","--keys",basePath + "signKey2.privateKey.unikey","--output", basePath + "sign_2.unicon"); assertTrue(CLIMain.loadContract(basePath + "sign_2.unicon").check()); }
reporter.verbose("Loading private key from " + keyFileName); try { privateKey = new PrivateKey(Do.read(keyFileName)); } catch (IOException e) { reporter.warning("can't read privte Key file: " + keyFileName); reporter.warning("\nUser private key is not set, generating new one."); reporter.message("new private key has been generated"); privateKey = new PrivateKey(2048); out.write(privateKey.pack());
@Test public void concurrencyTest() throws Exception { PrivateKey privateKey = new PrivateKey(2048); PublicKey publicKey = privateKey.getPublicKey(); ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(128); AtomicInteger errorsCount = new AtomicInteger(0); for (int i = 0; i < 10000; ++i) { executorService.submit(() -> { try { byte[] data = Bytes.random(128).getData(); byte[] encrypted = publicKey.encrypt(data); byte[] decrypted = privateKey.decrypt(encrypted); assertArrayEquals(data, decrypted); } catch (Exception e) { e.printStackTrace(); errorsCount.incrementAndGet(); } }); } executorService.shutdown(); executorService.awaitTermination(120, TimeUnit.SECONDS); assertEquals(0, errorsCount.get()); }
@Test public void concurrencyTestSignatures() throws Exception { PrivateKey privateKey = new PrivateKey(2048); PublicKey publicKey = privateKey.getPublicKey(); ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(128); AtomicInteger errorsCount = new AtomicInteger(0); try { byte[] data = Bytes.random(128).getData(); byte[] signature = privateKey.sign(data, HashType.SHA512); if(!publicKey.verify(data,signature,HashType.SHA512)) { errorsCount.incrementAndGet(); try { byte[] data = Bytes.random(128).getData(); byte[] signature = privateKey.sign(data, HashType.SHA3_384); if(!publicKey.verify(data,signature,HashType.SHA3_384)) { errorsCount.incrementAndGet();
@Test public void passwordProtectedKeyTest() throws Exception { PrivateKey key = TestKeys.privateKey(3); String password = UUID.randomUUID().toString(); byte[] packed = key.pack(); byte[] packedWithPassword = key.packWithPassword(password); //try unpack password protected try { new PrivateKey(packedWithPassword); fail("exception expected"); } catch (PrivateKey.PasswordProtectedException e) { assertEquals(e.getMessage(),"key is password protected"); } //try unpack password with wrong password try { PrivateKey.unpackWithPassword(packedWithPassword,UUID.randomUUID().toString()); fail("exception expected"); } catch (PrivateKey.PasswordProtectedException e) { assertEquals(e.getMessage(),"wrong password"); } //try unpack plain key with password assertEquals(PrivateKey.unpackWithPassword(packed,UUID.randomUUID().toString()),key); assertEquals(PrivateKey.unpackWithPassword(packedWithPassword,password),key); }
Answer a = requestOrThrow("connect", "client_key", privateKey.getPublicKey().pack()); "signature", privateKey.sign(data, HashType.SHA512), "data", data, "session_id", this.session.getSessionId() privateKey.decrypt( params.getBinaryOrThrow("encrypted_token")
@Test public void testKeys() throws Exception { // Test vectors are for key #1 PrivateKey key = (PrivateKey) TestKeys.privateKey(1); byte[] encrypted = Bytes.fromBase64(encrypted64).toArray(); byte[] decrypted = key.decrypt(encrypted); assertEquals(plainText, new String(decrypted)); PublicKey publicKey = key.getPublicKey(); byte[] encrypted2 = publicKey.encrypt(plainText); assertEquals(plainText, new String(key.decrypt(encrypted2))); publicKey = new PublicKey(Do.decodeBase64(publicKey64)); encrypted2 = publicKey.encrypt(plainText); assertEquals(plainText, new String(key.decrypt(encrypted2))); }
@Test public void passwordProtectedJsCompatibilityTest() throws Exception { byte[] encrypted = Base64.decodeCompactString("NhDIoIYBvB1jb20uaWNvZGljaS5jcnlwdG8uUHJpdmF0ZUtleVtITUFDX1NIQTI1NsQaAe01NLf/Ffcye5nVmAOsYV5uy/Q/OXqbVfH4baSo5rgdtYl3xmTrkwfHEerHVjyB/raQcJ6b96k3oVIHu6I/wDtZ3TMkQ8gpjzlEnzOs6LQ+0OzObrjxFfpiXZdPMLzu4XPMSJINSZtkPkSOeBEqItCf2C2CfPgdI1MniiDAN9qmuWMuGkD4o6UgaGfCjy0WGv8vY0rgkkQUanf8ctcIEgbLCcpu2irJY+OUhh1qC+Dwm3uSDFarXC/94i/YWpSbo2Apyxjq6ynpXVyc2aQiOmOf13iHulq5t9eyoqP4uSXL4xHff23onQRnvvc4OC+vbQvHType64zPTxVCFDpw6rlUhT/bEJ6IOh8XhX+LHZeTEuaTy0LXE055xiT1P375"); byte[] packed = Base64.decodeCompactString("JgAcAQABvIEA96FWTEq/Wjmd7kYbx04I/Ax3OQV+6e4YWu7xBr8k/SexvYvFEE3c9dRsZSsEj7KzYrNpIXezCsxO+j1sHADmeojwuveDdQQM6M6fbvygHq/mxKGllDoJTpzX/CnkuXDwC+lpRkkMTIF48GaYDM525951HYW1pAIYaVr+V5ctVQW8gQDGM71OC1yBLv6n23dEuu9Vqna2lvDpEWNO7MgKY0Ri9vUPwp+F+dUiKsRTbjnukDFqiYiNj+jkcWgiXqnjqdAGf9LUWHfF80W1PwUhkFw7torLJfaAr6bZ6FRzGcxTMad0x7Rz+5lkBjliKqOt8AUAIvMVe45G0c0StJSoqdqc4Q=="); PrivateKey pk1 = PrivateKey.unpackWithPassword(encrypted,"some-password"); PrivateKey pk2 = new PrivateKey(packed); assertEquals(pk1,pk2); try { PrivateKey.unpackWithPassword(encrypted,"some-password1"); fail("should throw"); } catch (PrivateKey.PasswordProtectedException e) { } }
@Test public void fingerprint() throws Exception { PrivateKey k = TestKeys.privateKey(0); byte[] f1 = k.getPublicKey().fingerprint(); assertEquals(33, f1.length); byte[] f2 = k.fingerprint(); assertArrayEquals(f1, f2); assertEquals(AbstractKey.FINGERPRINT_SHA256, f1[0]); }
@Test public void registerContractWithAnonymousId() throws Exception { TestSpace ts = prepareTestSpace(); PrivateKey newPrivateKey = new PrivateKey(Do.read("./src/test_contracts/keys/u_key.private.unikey")); byte[] myAnonId = newPrivateKey.createAnonymousId(); Contract contract = new Contract(); contract.setExpiresAt(ZonedDateTime.now().plusDays(90)); Role r = contract.setIssuerKeys(AnonymousId.fromBytes(myAnonId)); contract.registerRole(new RoleLink("owner", "issuer")); contract.registerRole(new RoleLink("creator", "issuer")); contract.addPermission(new ChangeOwnerPermission(r)); contract.addSignerKey(newPrivateKey); contract.seal(); assertTrue(contract.isOk()); System.out.println("contract.check(): " + contract.check()); contract.traceErrors(); ts.client.getSession().setPrivateKey(newPrivateKey); ts.client.restart(); ItemResult itemResult = ts.client.register(contract.getPackedTransaction(), 5000); assertEquals(ItemState.APPROVED, itemResult.state); ts.nodes.forEach(x -> x.shutdown()); }
@Override public Binder serialize(Object object, BiSerializer serializer) { return Binder.fromKeysValues("packed", ((PrivateKey) object).pack()); }
public byte[] packWithPassword(String password) throws EncryptionError { byte[] packedKey = pack(); byte[] salt = getClass().getCanonicalName().getBytes(); int rounds = getKDFRounds(); KeyInfo.PRF function = KeyInfo.PRF.HMAC_SHA256; SymmetricKey key = new KeyInfo(function, rounds, salt, null) .derivePassword(password); byte[] packedEncryptedKey = key.encrypt(packedKey); return Boss.dumpToArray(new Object[]{ 2, rounds, salt, function.name(), packedEncryptedKey, new Crc32().update(packedKey).digest() }); }
byte[] receipt = callbackKey.sign(id.getDigest(), HashType.SHA512);