Posts

Showing posts with the label CPP

VaultBox: A Forward-Secure C++ Library for Replicated, Rateless Storage

Image
VaultBox Forward-secure, replicated, rateless storage & transmission (C++) Secure Buffer Falcon Encoding Integrity Checker Verifier Key Evolution VaultBox is a header-only C++ library for forward-secure, replicated, randomized, and rate-less storage and transmission of data. It builds on the Crypto++ library and is designed for highly adversarial channels where an attacker may eavesdrop on or delete messages. Compiling g++ -I/usr/local/include -L/usr/local/lib test.cpp lib.cpp -lcryptopp Three levels of protection At rest: the VaultBox buffer is secured with Authenticated Encryption. In transit: data is protected with Falcon (fountain/rate-less) encoding. Hardware (optional): secure chips such as TPM/TEE and secure memory such as ECC-RAM or persistent memory can add an extra layer (hardware API support is not implemented in the library itself). The secure data structure The core is a fixed-size secure buffer (DS) of size T = k x n, holding k replicas of n messages....

Measuring Physical and Virtual Memory Usage in FreeBSD

Image
Terminal — memory-usage on FreeBSD $ clang++ memory-usage.cpp -o memory-usage $ ./memory-usage 839 Process ID: 839 Physical memory used: 2228.00 KB Virtual memory used: 12844.00 KB Here is a C++ program to print the physical and virtual memory used by a process on FreeBSD. It uses the kernel's sysctl interface to read process information, so it does not depend on parsing the output of any command line tool. What this program does It includes the necessary headers for system calls and I/O operations. It uses std::atoi() for argument parsing and <iomanip> for formatting output. The main function handles command line arguments: If an argument is provided, it is converted to an integer with std::atoi() . If the converted PID is invalid (0 or negative), an error message is displayed. If no argument is provided, it uses getpid() to get the current process ID. It sets up the Management Information Base (MIB) for the sysctl call to retrieve process ...

[How To] Install SEAL-Python In macOS

Image
Run the following commands from the Terminal in the given order: 1. brew install cmake autoconf automake libtool shtool gflags 2. xcode-select --install 3. git clone https://github.com/Huelse/SEAL-Python.git 4. cd SEAL-Python 5. pip3 install numpy pybind11 6. git submodule update --init --recursive 7. cd SEAL 8. cmake -S . -B build -DSEAL_USE_MSGSL=OFF -DSEAL_USE_ZLIB=OFF -DSEAL_THROW_ON_TRANSPARENT_CIPHERTEXT=OFF -DCMAKE_C_COMPILER=/usr/local/Cellar/llvm/16.0.1/bin/clang -DCMAKE_CXX_COMPILER=/usr/local/Cellar/llvm/16.0.1/bin/clang++ 9. cmake --build build 10. cd .. 11. python3 setup.py build_ext -i 12. cp seal.*.so examples 13. cd examples 14. python3 4_bgv_basics.py This guide installs SEAL-Python on macOS, the Python binding for Microsoft SEAL, by installing the build tools, cloning the project with its submodules, and building the wrapper. Microsoft SEAL is a homomorphic encryption library. Homomorphic encryption lets you compute on encrypted data without decrypting it. The buil...

[Solved] Fix "ld: library not found for -lc++" errors in macOS

Image
Linker Error: Run Build Command(s):/usr/local/Cellar/cmake/3.26.3/bin/cmake -E env VERBOSE=1 /usr/local/bin/gmake -f Makefile cmTC_2eb92/fast && /usr/local/bin/gmake   -f CMakeFiles/cmTC_2eb92.dir/build.make CMakeFiles/cmTC_2eb92.dir/build     gmake[1]: Entering directory '/Users/devharsh/Downloads/SEAL-Python/SEAL/build/CMakeFiles/CMakeScratch/TryCompile-p29bdr'     Building CXX object CMakeFiles/cmTC_2eb92.dir/testCXXCompiler.cxx.o     /Library/Developer/CommandLineTools/usr/bin/c++     -MD -MT CMakeFiles/cmTC_2eb92.dir/testCXXCompiler.cxx.o -MF CMakeFiles/cmTC_2eb92.dir/testCXXCompiler.cxx.o.d -o CMakeFiles/cmTC_2eb92.dir/testCXXCompiler.cxx.o -c /Users/devharsh/Downloads/SEAL-Python/SEAL/build/CMakeFiles/CMakeScratch/TryCompile-p29bdr/testCXXCompiler.cxx     Linking CXX executable cmTC_2eb92     /usr/local/Cellar/cmake/3.26.3/bin/cmake -E cmake_link_script CMakeFiles/cmTC_2eb92.dir/link.txt --verbose=1   ...

[How To] Install HElib on macOS

Image
HElib is an open-source (Apache License v2.0) software library that implements homomorphic encryption (HE). Currently, available schemes are the implementations of the Brakerski-Gentry-Vaikuntanathan (BGV) scheme and the Approximate Number scheme of Cheon-Kim-Kim-Song (CKKS), along with many optimizations to make homomorphic evaluation runs faster, focusing mostly on effective use of the Smart-Vercauteren ciphertext packing techniques and the Gentry-Halevi-Smart optimizations. To install HElib on macOS , follow these steps: brew update && brew upgrade && brew autoremove && brew cleanup cd Downloads/ git clone https://github.com/homenc/HElib.git Cloning into 'HElib'... remote: Enumerating objects: 14133, done. remote: Counting objects: 100% (292/292), done. remote: Compressing objects: 100% (211/211), done. remote: Total 14133 (delta 127), reused 172 (delta 54), pack-reused 13841 Receiving objects: 100% (14133/14133), 13.04 MiB | 5.81 MiB/s, done....

[Solved] Error: No such keg: /usr/local/Cellar/gcc

Image
If you are facing issues with Homebrew while installing or updating the GCC package (or any other module), follow this guide. The error occurred for me recently during my periodic homebrew updates on my MacBook Pro. devharsh@Devharshs-MacBook-Pro ~ % brew update && brew upgrade && brew cleanup                                                           Already up-to-date. Warning:  Skipping gcc: most recent version 12.1.0 not installed For some reason, I had a warning flashing up for GCC. So I tried to install the missing version. devharsh@Devharshs-MacBook-Pro ~ % brew install -f gcc@12 Error:  gcc 12.1.0_1 is already installed To install 12.1.0, first run:    brew unlink gcc Which unsurprisingly did not work, so I tried unlinking it.  devharsh@Devharshs-MacBook-Pro ~ % brew unlink gcc Error:  No su...

[Solved] ld: library not found for -lntl

Image
NTL: A Library for doing Number Theory NTL is a high-performance, portable C++ library providing data structures and algorithms for manipulating signed, arbitrary length integers and for vectors, matrices, and polynomials over the integers and over finite fields. You might face a linking error with NTL in macOS using the Apple Clang compiler: % make                                 Consolidate compiler generated dependencies of target degrees [ 25%] Linking CXX executable degrees ld: library not found for -lntl clang: error: linker command failed with exit code 1 (use -v to see invocation) Solution: % brew install NTL % export LIBRARY_PATH=/usr/local/lib % make This linker error means the build was told to link NTL, the C++ number theory library, but cannot find it. NTL provides arbitrary length integers and operations on polynomials and matrices over rings and finite fields. Installing NTL and poin...

[How To] Run MinimaxComp_degrees in macOS

Image
MinimaxComp_degrees This algorithm finds optimized degrees for comparison/max/ReLU algorithms using minimax composite polynomial on the RNS-CKKS scheme, which was proposed in https://ieeexplore.ieee.org/document/9517029 and https://eprint.iacr.org/2021/1215 . How to run on macOS using the Apple Clang compiler: 1. % brew install NTL 2. % export LIBRARY_PATH=/usr/local/lib 3. % git clone  https://github.com/eslee3209/MinimaxComp_degrees 4. % cd MinimaxComp_degrees 5. % cmake -S . -B build 6. % cd build 7. % make 8. % ./degrees Output: ------------------------------------ alpha: 20 epsilon: 0.2002716064453125e-4 mintime: 162 depth: 22 0.39825903512705770933e-4 7 13 15 15 59   This guide runs MinimaxComp_degrees on macOS, an algorithm that finds optimized polynomial degrees for comparison, max, and ReLU operations under the RNS-CKKS homomorphic encryption scheme, based on the referenced research. CKKS can only evaluate polynomials on encrypted data, so non-polyn...

[How To] Run HELR (Homomorphic Encryption Logistic Regression) in macOS

Image
HELR is a software project for performing a logistic regression training on encrypted data (Secure Logistic Regression based on Homomorphic Encryption: Design and Evaluation ( https://medinform.jmir.org/2018/2/e19/ )). Step 1: brew install GMP Step 2: brew install NTL Step 3: git clone  https://github.com/K-miran/HELR.git Step 4: cd HELR

[Solved] 15 duplicate symbols for architecture x86_64

Image
Error: If you are getting build failures in Xcode for a C++ program with similar errors, then try this fix. 15 duplicate symbols for architecture x86_64 ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation) Solution: You can avoid declaring variables in the header and move them to implementation. Or you can declare all the variables in the header file as static.

[How To] Calculate hash of a vector in C++

Image
This is a sample code to generate SHA256 in C++ using CryptoPP. For the first string in a vector: std::vector<std::string> stringVector{"abcde", "fghij", "klmno", "pqrst", "uvwxyz"}; byte digest[SHA256::DIGESTSIZE]; SHA256().CalculateDigest(digest, (const byte*)stringVector.data(), stringVector.size()); For an entire vector of string: std::vector<std::string> stringVector{"abcde", "fghij", "klmno", "pqrst", "uvwxyz"}; HexEncoder encoder(new FileSink(std::cout)); std::string digest; SHA256 hash; for(auto str: stringVector) {  hash.Update((const byte*)str.data(), str.size());  }  digest.resize(hash.DigestSize());  hash.Final((byte*)&digest[0]); std::cout << "Digest: "; StringSource(digest, true, new Redirector(encoder)); std::cout << std::endl; This sample computes a SHA-256 hash in C++ with the Crypto++ library, applied to data held in a vector of s...

[Solved] error: ‘getrusage’ was not declared in this scope

Image
Error: vb_perf.cpp: In function ‘int main(int, const char**)’: vb_perf.cpp:63:23: error: variable ‘main(int, const char**)::rusage rusage’ has initializer but incomplete type    63 |         struct rusage rusage = { };       |                       ^~~~~~ vb_perf.cpp:64:19: error: ‘RUSAGE_SELF’ was not declared in this scope    64 |         getrusage(RUSAGE_SELF, &rusage);       |                   ^~~~~~~~~~~ vb_perf.cpp:64:9: error: ‘getrusage’ was not declared in this scope; did you mean ‘rusage’?    64 |         getrusage(RUSAGE_SELF, &rusage);       |         ^~~~~~~~~       |         rusage Solution: Include this header to your source code: #include <...

[How To] Use Cryptopp in Kali Linux

Image
 Crypto++ is a popular C++ library for cryptography. Instruction in this article can be used to install Cryptopp for all operating systems similar to Kali Linux. Check out this article if you want to use it with Xcode in macOS. Step 1: Download Crypto++ using this link Step 2: Extract Crypto++ and switch to that directory from the terminal or shell. Step 3: $ make Step 4: $ make test Step 5: $ sudo make install Step 6: Compile your program using g++ -I/usr/local/include -L/usr/local/lib yourCode.cpp -lcryptopp

[How To] Generate KEY and IV for CryptoPP in C++

Image
In this tutorial, I will share strategies to generate random keys and initialization vector in C++ using CryptoPP library. Approach 1: SecByteBlock key(32), iv(24); AutoSeededRandomPool prng; prng.GenerateBlock(key, key.size()); prng.GenerateBlock(iv, iv.size()); Approach 2: SecByteBlock key(16), iv(16); std::string password = "Super secret password"; DeriveKeyAndIV(password, "encryption example", 100, key, key.size(), iv, iv.size());

[Solved] 'cryptopp/aes.h' file not found; Expected namespace name

Image
If you are facing errors like " 'cryptopp/aes.h' file not found " or getting "Expected namespace name" error for " using namespace CryptoPP; " or similar compilation errors, refer to the following settings: Add "/usr/local/include" in Header search paths Add "/usr/local/lib" in Library search paths Add -lcryptopp as a Linker flag Refer to this article for more information:  https://com.puter.tips/2021/02/how-to-use-cryptopp-in-xcode.html These C++ build errors mean the compiler cannot find the Crypto++ headers or library, so the CryptoPP namespace looks undefined. The include and library search paths are not set. Adding /usr/local/include to the header search paths and the matching library path to the linker settings points the build at Crypto++ and clears both errors at once.

[How To] Use Boost in Xcode

Image
Using Boost C++ Libraries ( https://www.boost.org/ ) is relatively easier than setting up Cryptopp. [Ref.:  https://com.puter.tips/2021/02/how-to-use-cryptopp-in-xcode.html ] Step-1: Install boost libraries $ brew install boost Step-2: Link boost in Build Settings Navigate to Linking >> Other Linker Flags Add following flags as per your requirement -lboost_chrono -lboost_system -lboost_timer -lboost_regex This guide sets up the Boost C++ libraries in an Xcode project, which is simpler than wiring up some other libraries. After installing Boost with Homebrew, you add the linker flags so the project finds it. Boost is a large, widely used collection of peer reviewed C++ libraries, many of which later influenced the standard library. Getting the link settings right once lets you use any of them.

[Solved] code signature not valid for use in process using Library Validation

Image
So I was working on a C++ project on Xcode, and I updated to the latest version of Xcode with recommended default settings; then I started having the following errors: dyld: Library not loaded: /usr/local/lib/libcryptopp.dylib    Referenced from: /Users/devharsh/Library/Developer/Xcode/DerivedData/server-bohvcuztzndrrzhcoglrvuijfasj/Build/Products/Debug/server    Reason: no suitable image found.    Did find: /usr/local/lib/libcryptopp.dylib: code signature in (/usr/local/lib/libcryptopp.dylib) not valid for use in process using Library Validation: mapped file has no cdhash, completely unsigned? Code has to be at least ad-hoc signed. /usr/local/lib/libcryptopp.dylib: code signature in (/usr/local/lib/libcryptopp.dylib) not valid for use in process using Library Validation: mapped file has no cdhash, completely unsigned? Code has to be at least ad-hoc signed. /usr/local/lib/libcryptopp.dylib: code signature in (/usr/local/lib/libcryptopp.dylib) not vali...

Random Number Generation in C++

Image
Code: // //   main.cpp //   VaultBox // //   Created by Devharsh Trivedi on 3/11/21. // #include <iostream> #include <iomanip> #include <string> #include <map> #include <random> #include <cmath> #include <vector> int main ( int argc, const char * argv[]) {     std :: random_device ranDev;     unsigned int num_ranDev = ranDev();     std :: cout << num_ranDev << std :: endl ;     std :: mt19937 mtGen(num_ranDev);     std :: vector < unsigned long > indexes( 10 );          iota (indexes. begin (), indexes. end (), 0 );     for ( int i= 0 ; i< 10 ; i++) {         std :: cout << indexes[i] << "\t" ;     }     std :: cout << std :: endl ;

setsockopt: Protocol not available [Solved]

Image
Problem code: if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT , &opt, sizeof(opt)))  {  perror("setsockopt");  exit(EXIT_FAILURE);  } Solution: if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR , &opt, sizeof(opt)))  {  perror("setsockopt");  exit(EXIT_FAILURE);  } Ref.:  https://stackoverflow.com/a/59807281/4064166 This error appears when a socket option is not supported on the current platform. Here the combination of SO_REUSEADDR and SO_REUSEPORT fails because SO_REUSEPORT is unavailable, so the call returns Protocol not available. Setting SO_REUSEADDR on its own fixes it, which is widely supported and enough for the common case of rebinding a recently used address. SO_REUSEPORT behaves differently across operating systems and is not always present.

[How To] Use Cryptopp in Xcode

Image
Crypto++ Library is a free C++ class library of cryptographic schemes. Currently the library contains the following algorithms: algorithm type name authenticated encryption schemes GCM, CCM, EAX, ChaCha20Poly1305 and XChaCha20Poly1305 high speed stream ciphers ChaCha (8/12/20), ChaCha (IETF), Panama, Salsa20, Sosemanuk, XSalsa20, XChaCha20 AES and AES candidates AES (Rijndael), RC6, MARS, Twofish, Serpent, CAST-256 ARIA, Blowfish, Camellia, CHAM, HIGHT, IDEA, Kalyna (128/256/512), LEA, SEED, RC5, SHACAL-2, other block ciphers SIMON (64/128), Skipjack, SPECK (64/128), Simeck, SM4, Threefish (256/512/1024), Triple-DES (DES-EDE2 and DES-EDE3), TEA, XTEA block cipher modes of operati...