1 // Copyright 2020 Google LLC 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // https://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 // Utility functions for Java-compatible operations. 16 #ifndef SECURITY_CRYPTAUTH_LIB_SECUREGCM_JAVA_UTIL_H_ 17 #define SECURITY_CRYPTAUTH_LIB_SECUREGCM_JAVA_UTIL_H_ 18 19 #include "securemessage/byte_buffer.h" 20 21 namespace securegcm { 22 namespace java_util { 23 24 // Perform multiplication with Java overflow semantics 25 // (https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html): 26 // If an integer multiplication overflows, then the result is the low-order 27 // bits of the mathematical product as represented in some sufficiently 28 // large two's-complement format. 29 int32_t JavaMultiply(int32_t lhs, int32_t rhs); 30 31 // Perform addition with Java overflow semantics: 32 // (https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html): 33 // If an integer addition overflows, then the result is the low-order bits of 34 // the mathematical sum as represented in some sufficiently large 35 // two's-complement format. 36 int32_t JavaAdd(int32_t lhs, int32_t rhs); 37 38 // To be compatible with the Java implementation, we need to use the same 39 // algorithm as the Arrays#hashCode(byte[]) function in Java: 40 // "The value returned by this method is the same value that would be obtained 41 // by invoking the hashCode method on a List containing a sequence of Byte 42 // instances representing the elements of a in the same order." 43 // 44 // According to List#hashCode(), this algorithm is: 45 // int hashCode = 1; 46 // for (Byte b : list) { 47 // hashCode = 31 * hashCode + (b == null ? b : b.hashCode()); 48 // } 49 // 50 // Finally, Byte#hashCode() is defined as "equal to the result of invoking 51 // Byte#intValue()". 52 int32_t JavaHashCode(const securemessage::ByteBuffer& byte_buffer); 53 54 } // namespace java_util 55 } // namespace securegcm 56 57 #endif // SECURITY_CRYPTAUTH_LIB_SECUREGCM_JAVA_UTIL_H_ 58