@Override public Binder serialize(Object object, BiSerializer serializer) { return Binder.fromKeysValues("packed", ((PrivateKey) object).pack()); }
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"); }
/** * Given the {@link RSAOAEPPrivateKey}, create the .unikey-format byte array. */ @NonNull public static byte[] toUnikey(@NonNull PrivateKey privateKey) { assert privateKey != null; return privateKey.pack(); } }
@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); }
@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); } } }
out.write(privateKey.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() }); }
statement.setBytes(9, nodeKey.pack());
/** * 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); } }
byte[] packed = Boss.pack(data); byte[] encrypted = new PublicKey(session.remoteNodeInfo.getPublicKey().pack()).encrypt(packed); byte[] sign = new PrivateKey(ownPrivateKey.pack()).sign(encrypted, HashType.SHA512);
byte[] sign = session.handshake_sessionPart2; if (new PublicKey(session.remoteNodeInfo.getPublicKey().pack()).verify(encrypted, sign, HashType.SHA512)) { byte[] decryptedData = new PrivateKey(ownPrivateKey.pack()).decrypt(encrypted); List data = Boss.load(decryptedData); byte[] sessionKey = ((Bytes) data.get(0)).toArray();
String targetFile = FileTool.writeFileContentsWithRenaming(new FilenameTool(keyPath).setPath(walletPath).toString(), pk.pack()); keys.add(new FilenameTool(targetFile).getFilename()); keysAdded++;
report(logLabel, ()->"received both parts of key_req from " + sessionReader.remoteNodeInfo.getNumber(), VerboseLevel.BASE); byte[] encrypted = sessionReader.handshake_keyReqPart1; byte[] packed = new PrivateKey(ownPrivateKey.pack()).decrypt(encrypted); byte[] sign = sessionReader.handshake_keyReqPart2; List nonceList = Boss.load(packed);
/** * When someone send us {@link PacketTypes#HELLO} typed {@link UDPAdapter.Packet}, * we should respond with {@link PacketTypes#WELCOME}. * @param sessionReader is {@link UDPAdapter.SessionReader} in which sending is. */ private void sendWelcome(SessionReader sessionReader) { try { report(logLabel, () -> "send welcome to " + sessionReader.remoteNodeInfo.getNumber(), VerboseLevel.BASE); byte[] data = sessionReader.localNonce; byte[] sign = new PrivateKey(ownPrivateKey.pack()).sign(data, HashType.SHA512); byte[] payload = Boss.dumpToArray(Arrays.asList(data, sign)); Packet packet = new Packet(getNextPacketId(), myNodeInfo.getNumber(), sessionReader.remoteNodeInfo.getNumber(), PacketTypes.WELCOME, payload); sendPacket(sessionReader.remoteNodeInfo, packet); sessionReader.removeHandshakePacketsFromRetransmitMap(); sessionReader.addPacketToRetransmitMap(packet.packetId, packet, sessionReader.localNonce); } catch (EncryptionError e) { callErrorCallbacks("(sendWelcome) EncryptionError: " + e); } }
@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()); }
PrivateKey splitJoinKey3 = new PrivateKey(2048); Files.write(Paths.get(basePath + "splitJoinKey1.privateKey.unikey"),splitJoinKey1.pack(), StandardOpenOption.CREATE, StandardOpenOption.WRITE); Files.write(Paths.get(basePath + "splitJoinKey2.privateKey.unikey"),splitJoinKey2.pack(), StandardOpenOption.CREATE, StandardOpenOption.WRITE); Files.write(Paths.get(basePath + "splitJoinKey3.privateKey.unikey"),splitJoinKey3.pack(), StandardOpenOption.CREATE, StandardOpenOption.WRITE);
@Test public void testFromToUnikeyPublicMethods() throws Exception { final PrivateKey pk1 = new PrivateKey(pk1Bytes); assertArrayEquals(pk1Bytes, pk1.pack()); final PrivateKey pk2 = UnikeyFactory.fromUnikey(pk1Bytes); assertEquals(pk1, pk2); assertArrayEquals(pk1Bytes, UnikeyFactory.toUnikey(pk2)); } }
@Test public void serializationTest() throws Exception { byte[] packedPublicKey = Do.decodeBase64(publicKey64); PublicKey publicKey = new PublicKey(packedPublicKey); byte[] packedPublicKey2 = publicKey.pack(); assertArrayEquals(packedPublicKey, packedPublicKey2); byte[] packedPrivateKey = Do.decodeBase64(TestKeys.binaryKeys[3]); PrivateKey privateKey = new PrivateKey(packedPrivateKey); byte[] packedPrivateKey2 = privateKey.pack(); assertArrayEquals(packedPrivateKey, packedPrivateKey2); }
/** * Someone who sent {@link PacketTypes#HELLO} typed {@link Packet}, * send us new KEY_REQ typed {@link Packet} - if all is ok we send session keys to. * SESSION's payload is more than 512 bytes, so used two parts here. * From now we ready to data exchange. * @param sessionReader is {@link SessionReader} in which sending is. */ private void sendSessionKey(SessionReader sessionReader) throws EncryptionError { report(logLabel, ()->"send session_key to "+sessionReader.remoteNodeInfo.getNumber(), VerboseLevel.BASE); List data = Arrays.asList(sessionReader.sessionKey.getKey(), sessionReader.remoteNonce); byte[] packed = Boss.pack(data); byte[] encrypted = new PublicKey(sessionReader.remoteNodeInfo.getPublicKey().pack()).encrypt(packed); byte[] sign = new PrivateKey(ownPrivateKey.pack()).sign(encrypted, HashType.SHA512); Packet packet1 = new Packet(getNextPacketId(), myNodeInfo.getNumber(), sessionReader.remoteNodeInfo.getNumber(), PacketTypes.SESSION_PART1, encrypted); Packet packet2 = new Packet(getNextPacketId(), myNodeInfo.getNumber(), sessionReader.remoteNodeInfo.getNumber(), PacketTypes.SESSION_PART2, sign); sendPacket(sessionReader.remoteNodeInfo, packet1); sendPacket(sessionReader.remoteNodeInfo, packet2); sessionReader.addPacketToRetransmitMap(packet1.packetId, packet1, encrypted); sessionReader.addPacketToRetransmitMap(packet2.packetId, packet2, sign); }