@@ -34,13 +34,14 @@ public class Curve25519DH extends DHBase {
3434
3535 private static final String ALGORITHM = "X25519" ;
3636
37- private static final int ENCODED_ALGORITHM_ID_KEY_LENGTH = 44 ;
37+ private static final int KEY_LENGTH = 32 ;
3838
39- private static final int ALGORITHM_ID_LENGTH = 12 ;
39+ private int encodedKeyLength ;
4040
41- private static final int KEY_LENGTH = 32 ;
41+ private int algorithmIdLength ;
4242
43- private final byte [] algorithmId = new byte [ALGORITHM_ID_LENGTH ];
43+ // Algorithm Identifier is set on Key Agreement Initialization
44+ private byte [] algorithmId = new byte [KEY_LENGTH ];
4445
4546 public Curve25519DH () {
4647 super (ALGORITHM , ALGORITHM );
@@ -81,23 +82,24 @@ public void init(final AlgorithmParameterSpec params, final Factory<Random> rand
8182 private void setPublicKey (final PublicKey publicKey ) {
8283 final byte [] encoded = publicKey .getEncoded ();
8384
85+ // Set key and algorithm identifier lengths based on initialized Public Key
86+ encodedKeyLength = encoded .length ;
87+ algorithmIdLength = encodedKeyLength - KEY_LENGTH ;
88+ algorithmId = new byte [algorithmIdLength ];
89+
8490 // Encoded public key consists of the algorithm identifier and public key
85- if (encoded .length == ENCODED_ALGORITHM_ID_KEY_LENGTH ) {
86- final byte [] publicKeyEncoded = new byte [KEY_LENGTH ];
87- System .arraycopy (encoded , ALGORITHM_ID_LENGTH , publicKeyEncoded , 0 , KEY_LENGTH );
88- setE (publicKeyEncoded );
89-
90- // Save Algorithm Identifier byte array
91- System .arraycopy (encoded , 0 , algorithmId , 0 , ALGORITHM_ID_LENGTH );
92- } else {
93- throw new IllegalArgumentException (String .format ("X25519 unsupported public key length [%d]" , encoded .length ));
94- }
91+ final byte [] publicKeyEncoded = new byte [KEY_LENGTH ];
92+ System .arraycopy (encoded , algorithmIdLength , publicKeyEncoded , 0 , KEY_LENGTH );
93+ setE (publicKeyEncoded );
94+
95+ // Save Algorithm Identifier byte array
96+ System .arraycopy (encoded , 0 , algorithmId , 0 , algorithmIdLength );
9597 }
9698
9799 private KeySpec getPeerPublicKeySpec (final byte [] peerPublicKey ) {
98- final byte [] encodedKeySpec = new byte [ENCODED_ALGORITHM_ID_KEY_LENGTH ];
99- System .arraycopy (algorithmId , 0 , encodedKeySpec , 0 , ALGORITHM_ID_LENGTH );
100- System .arraycopy (peerPublicKey , 0 , encodedKeySpec , ALGORITHM_ID_LENGTH , KEY_LENGTH );
100+ final byte [] encodedKeySpec = new byte [encodedKeyLength ];
101+ System .arraycopy (algorithmId , 0 , encodedKeySpec , 0 , algorithmIdLength );
102+ System .arraycopy (peerPublicKey , 0 , encodedKeySpec , algorithmIdLength , KEY_LENGTH );
101103 return new X509EncodedKeySpec (encodedKeySpec );
102104 }
103105}
0 commit comments