Showing posts with label CPP. Show all posts
Showing posts with label CPP. Show all posts

Saturday, August 12, 2023

[How To] Install SEAL-Python In macOS


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

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


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

    /Library/Developer/CommandLineTools/usr/bin/c++ -Wl,-search_paths_first -Wl,-headerpad_max_install_names CMakeFiles/cmTC_2eb92.dir/testCXXCompiler.cxx.o -o cmTC_2eb92 

    ld: library not found for -lc++

    clang: error: linker command failed with exit code 1 (use -v to see invocation)

    gmake[1]: *** [CMakeFiles/cmTC_2eb92.dir/build.make:100: cmTC_2eb92] Error 1

    gmake[1]: Leaving directory '/Users/devharsh/Downloads/SEAL-Python/SEAL/build/CMakeFiles/CMakeScratch/TryCompile-p29bdr'

    gmake: *** [Makefile:127: cmTC_2eb92/fast] Error 2


Solution:

export CPLUS_INCLUDE_PATH=/usr/local/opt/llvm/include/c++/v1:/Library/Developer/CommandLineTools/SDKs/MacOSX13.3.sdk/usr/include


export LIBRARY_PATH=$LIBRARY_PATH:/Library/Developer/CommandLineTools/SDKs/MacOSX13.3.sdk/usr/lib

Sunday, November 27, 2022

[How To] Install HElib on macOS


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:

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.

Resolving deltas: 100% (10853/10853), done.

  • cd HElib/

  • mkdir build

  • cd build 

  • cmake -DPACKAGE_BUILD=ON -DENABLE_TEST=ON ..

-- The C compiler identification is AppleClang 14.0.0.14000029

-- The CXX compiler identification is AppleClang 14.0.0.14000029

-- Detecting C compiler ABI info

-- Detecting C compiler ABI info - done

-- Check for working C compiler: /Library/Developer/CommandLineTools/usr/bin/cc - skipped

-- Detecting C compile features

-- Detecting C compile features - done

-- Detecting CXX compiler ABI info

-- Detecting CXX compiler ABI info - done

-- Check for working CXX compiler: /Library/Developer/CommandLineTools/usr/bin/c++ - skipped

-- Detecting CXX compile features

-- Detecting CXX compile features - done

-- Performing Test CMAKE_HAVE_LIBC_PTHREAD

-- Performing Test CMAKE_HAVE_LIBC_PTHREAD - Success

-- Found Threads: TRUE  

CMake Warning at CMakeLists.txt:264 (message):

  CAUTION: Package build should not be installed globally as it will

  potentially override dependencies.


Tuesday, August 09, 2022

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


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 such keg: /usr/local/Cellar/gcc


And this failed too, hence this post! After some troubleshooting, I could fix the issue.

Wednesday, July 13, 2022

[Solved] ld: library not found for -lntl

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

[How To] Run MinimaxComp_degrees in macOS


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
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 


Thursday, June 30, 2022

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


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 4: cd HELR

Sunday, February 06, 2022

[Solved] 15 duplicate symbols for architecture x86_64


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.

Thursday, February 03, 2022

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


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;

Thursday, December 09, 2021

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


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 <sys/resource.h>

Thursday, November 25, 2021

[How To] Use Cryptopp in Kali Linux

 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

Monday, November 08, 2021

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


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());

Sunday, October 17, 2021

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

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

[How To] Use Boost in Xcode

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

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

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 valid for use in process using Library Validation: mapped file has no cdhash, completely unsigned? Code has to be at least ad-hoc signed.

Program ended with exit code: 9


Solution:
  • Go to Xcode > Targets > Build Settings
  • Scroll down and go to the Signing tab
  • Click on "Enable Hardened Runtime" and set it to "No"
  • Recompile, and it should be fixed


Thursday, March 11, 2021

Random Number Generation in C++


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;

Friday, February 26, 2021

setsockopt: Protocol not available [Solved]


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


Sunday, February 21, 2021

[How To] Use Cryptopp in Xcode

  • 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 operation ECB, CBC, CBC ciphertext stealing (CTS), CFB, OFB, counter mode (CTR), XTS message authentication codes BLAKE2s, BLAKE2b, CMAC, CBC-MAC, DMAC, GMAC, HMAC, Poly1305, Poly1305 (IETF), SipHash, Two-Track-MAC, VMAC BLAKE2s, BLAKE2b, Keccack (F1600), SHA-1, hash functions SHA-2 (224/256/384/512), SHA-3 (224/256/384/512), SHAKE (128/256), SipHash, SM3, Tiger, RIPEMD (128/160/256/320), WHIRLPOOL RSA, DSA, Deterministic DSA, ElGamal, public-key cryptography Nyberg-Rueppel (NR), Rabin-Williams (RW), LUC, LUCELG, EC-based German Digital Signature (ECGDSA), DLIES (variants of DHAES), ESIGN padding schemes for public-key PKCS#1 v2.0, OAEP, PSS, PSSR, IEEE P1363 systems EMSA2 and EMSA5 Diffie-Hellman (DH), Unified Diffie-Hellman (DH2), key agreement schemes Menezes-Qu-Vanstone (MQV), Hashed MQV (HMQV), Fully Hashed MQV (FHMQV), LUCDIF, XTR-DH elliptic curve cryptography ECDSA, Deterministic ECDSA, ed25519, ECNR, ECIES, ECDH, ECMQV, x25519 insecure or obsolescent MD2, MD4, MD5, Panama Hash, DES, ARC4, SEAL algorithms retained for backwards 3.0, WAKE-OFB, DESX (DES-XEX3), RC2, compatibility and historical SAFER, 3-WAY, GOST, SHARK, CAST-128, Square value

Sunday, March 25, 2018

C++ Array Declaration Stack Overflow Exception

Error: Stack overflow when declaring a huge array in C++.

Unhandled exception at 0x00007FF60B7040C8 in Tutorial.exe: 0xC00000FD: Stack overflow (parameters: 0x0000000000000001, 0x00000081A80D3000). occurred


Problem code:

#include <iostream>
#include <fstream>

int main()
{
    //do something..

    int nar[10000000];

    //do something more..

    return 0;
}


Wednesday, October 04, 2017

Monoalphabetic Substitution Cipher in C++

#include <iostream>
#include <string>
#include <ctime>
#include <chrono>
#include <thread>

int main()
{

  char plain[100] = "devharsh";
  char cipher[100];
 
  char alphabets[26] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
  char mappings[26] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
 
  alphabets[26] = '\0';
  mappings[26] = '\0';
 
  std::cout << alphabets << "\n";
  std::cout << mappings << "\n";
 
  for (int i=0; i<26; i++)
  { 
    srand((int)time(0));
    std::this_thread::sleep_for(std::chrono::milliseconds(300));
    int irand = rand() % 26;
    char temp = mappings[i];
    mappings[i] = mappings[irand];
    mappings[irand] = temp;
  }
 
  std::cout << alphabets << "\n";
  std::cout << mappings << "\n";
 
  for (int i=0; i<sizeof(plain) / sizeof(char); i++)
  {
      for (int j=0; j<26; j++)
      {
          if (plain[i] == alphabets[j])
          {
              cipher[i] = mappings[j];
          }
      }
  }
 
  std::cout << plain << "\n";
  std::cout << cipher << "\n";

}