· 7 years ago · Dec 16, 2018, 03:30 PM
1public static void main(final String[] args)
2{
3 final BitsProvider bitsProvider = Random256BitsProvider.INSTANCE;
4
5 System.out.format("Example #%02d%n", i);
6 final byte[] identityUnlockKey = bitsProvider.get();
7 dumpInHex("Identity Unlock Key", identityUnlockKey);
8 final IdentityLock identityLock = new IdentityLock(identityUnlockKey);
9
10 final byte[] randomLockVal = bitsProvider.get();
11 dumpInHex("Random Lock Val", randomLockVal);
12 final IdentityLockForSite identityLockForSite = identityLock.getLockForSite(randomLockVal);
13}
14
15
16final class IdentityLock
17{
18 private final byte[] identityLockKey;
19 private final byte[] identityUnlockKey;
20
21 public IdentityLock(final byte[] identityUnlockKey)
22 {
23 this.identityUnlockKey = identityUnlockKey.clone();
24 identityLockKey = makePublic(identityUnlockKey);
25 dumpInHex("Identity Lock Key", identityLockKey);
26 }
27
28 public IdentityLockForSite getLockForSite(final byte[] siteLockVal)
29 {
30 final byte[] serverUnlockKey = makePublic(siteLockVal);
31 dumpInHex("Server Unlock Key", serverUnlockKey);
32
33 final byte[] keyAgreementVal1 = dhka(identityLockKey, siteLockVal);
34 dumpInHex("DH Key Agreement Val 1", keyAgreementVal1);
35
36 final byte[] verifyUnlockKey = getPublicKeyForSeed(keyAgreementVal1);
37 dumpInHex("Verify Unlock Key", verifyUnlockKey);
38
39 // Now make sure it works
40 System.out.println();
41 System.out.println("Steps and values for verifying identity unlock:");
42 final byte[] keyAgreementVal2 = dhka(serverUnlockKey, identityUnlockKey);
43 dumpInHex("DH Key Agreement Val 2", keyAgreementVal2);
44
45 final byte[] unlockRequestSigningKey = getPrivateKeyForSeed(keyAgreementVal2);
46 dumpInHex("Unlock Request Signing Key", unlockRequestSigningKey);
47 }
48}
49
50
51byte[] getPublicKeyForSeed(final byte[] seedForKeyPair)
52{
53 final byte[] privateKeyBytes = new byte[SECRETKEYBYTES];
54 final byte[] publicKeyBytes = new byte[PUBLICKEYBYTES];
55 crypto_sign_seed_keypair(publicKeyBytes, privateKeyBytes, seedForKeyPair);
56 return publicKeyBytes;
57}
58
59
60byte[] getPrivateKeyForSeed(final byte[] seedForKeyPair)
61{
62 final byte[] privateKeyBytes = new byte[SECRETKEYBYTES];
63 final byte[] publicKeyBytes = new byte[PUBLICKEYBYTES];
64 crypto_sign_seed_keypair(publicKeyBytes, privateKeyBytes, seedForKeyPair);
65 return Arrays.copyOfRange(privateKeyBytes, 32, 64);
66}
67
68
69public static byte[] makePublic(final byte[] secretKey)
70{
71 byte[] result = new byte[PUBLICKEYBYTES];
72 crypto_scalarmult_base(result, secretKey);
73 return result;
74}
75
76
77public static byte[] dhka(final byte[] publicKey, final byte[] secretKey)
78{
79 byte[] result = new byte[SCALARMULT_BYTES];
80 if (crypto_scalarmult(result, secretKey, publicKey) == 0)
81 {
82 return result;
83 }
84 throw new IllegalStateException("crypto_scalarmult failed");
85}