├── .github └── workflows │ └── c-cpp.yml ├── Array ├── Character_Arrays.cpp └── Navigating Arrays.cpp ├── Class Inheritance └── inheritance.cpp ├── Class Virtual Functions └── tes.cpp ├── CuteCpp └── charts │ └── tes1.cpp ├── Download file ├── README.md └── main.cpp ├── DownloadFile.exe ├── Flow of Control └── main.cpp ├── Json ├── ReadJson.cpp └── data.json ├── LICENSE ├── README.md ├── array └── main.cpp ├── clock_sfml.cpp ├── cryptopp ├── Diffie-Hellman.cpp ├── tes1.cpp ├── tes3.cpp └── tes4.cpp ├── libs └── readme.md ├── makefile ├── factorial.cpp ├── function.h ├── main.cpp ├── makefile ├── multiply.cpp └── print.cpp ├── notepad └── notepad_c.cpp ├── temp └── Constructor │ └── default-copy-move-destructor.cpp └── thread.cpp /.github/workflows/c-cpp.yml: -------------------------------------------------------------------------------- 1 | name: C/C++ CI 2 | 3 | on: 4 | push: 5 | branches: [ "main" ] 6 | pull_request: 7 | branches: [ "main" ] 8 | 9 | jobs: 10 | build: 11 | 12 | runs-on: ubuntu-latest 13 | 14 | steps: 15 | - uses: actions/checkout@v4 16 | - name: configure 17 | run: ./configure 18 | - name: make 19 | run: make 20 | - name: make check 21 | run: make check 22 | - name: make distcheck 23 | run: make distcheck 24 | -------------------------------------------------------------------------------- /Array/Character_Arrays.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | char c = 'a'; 7 | char∗ p = &c; // p menyimpan alamat c; & adalah address-dari operator 8 | char c2 = ∗p; // c2 == ’a’; * adalah dereference operator 9 | 10 | // Input cin 11 | char name[25]; 12 | cout << "Masukan Nama \n"; 13 | cin >> name; 14 | cout << "Halo " << name << endl; 15 | // Input getline 16 | char nama2[25]; 17 | cout << "Masukan Nama \n"; 18 | cin.getline(nama2,25); 19 | cout << "Halo " << nama2 << endl; 20 | 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /Array/Navigating Arrays.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void fi(char v[]); 5 | void fp(char v[]); 6 | void use(char v1[]); 7 | 8 | int main() 9 | { 10 | fi("me"); 11 | } 12 | 13 | void fi(char v[]) 14 | { 15 | for (int i = 0; v[i] != 0; ++i) 16 | use(v[i]); 17 | } 18 | void fp(char v[]) 19 | { 20 | for (char* p = v; *p!=0; ++p) 21 | cout<< *p<setupUi(this); 6 | // 1. Create a new chart 7 | QChart *chart = new QChart(); 8 | chart->setTitle("My First Chart"); 9 | // 2. Create a line series to hold data 10 | QLineSeries *series = new QLineSeries(); 11 | 12 | // 3. Add some data points (x, y) 13 | series->append(0, 1); 14 | series->append(1, 3); 15 | series->append(2, 2); 16 | series->append(3, 5); 17 | series->append(4, 4); 18 | 19 | // 4. Add the series to the chart 20 | chart->addSeries(series); 21 | 22 | // 5. Create default axes for the chart 23 | chart->createDefaultAxes(); 24 | 25 | // 6. Access the axes directly after creating them 26 | QAbstractAxis *xAxis = chart->axes(Qt::Horizontal).first(); 27 | QAbstractAxis *yAxis = chart->axes(Qt::Vertical).first(); 28 | 29 | if (xAxis) { 30 | xAxis->setTitleText("X-Axis"); // Set title for the x-axis 31 | } 32 | if (yAxis) { 33 | yAxis->setTitleText("Y-Axis"); // Set title for the y-axis 34 | } 35 | 36 | // 7. Create a QChartView to display the chart 37 | chartView = new QChartView(chart); 38 | chartView->setRenderHint(QPainter::Antialiasing); // Make the rendering smoother 39 | 40 | // 8. Find the layout of your main window and add the chart view to it 41 | if (ui->verticalLayout) { // Assuming you have a vertical layout in your UI 42 | ui->verticalLayout->addWidget(chartView); 43 | } else { 44 | // If you don't have a layout, you might need to set the central widget directly 45 | setCentralWidget(chartView); 46 | qDebug() << "Warning: No layout found in UI. Setting chart view as central widget."; 47 | } 48 | } 49 | 50 | main.h 51 | 52 | #include 53 | #include 54 | #include 55 | #include 56 | #include 57 | #include 58 | 59 | 60 | QT_BEGIN_NAMESPACE 61 | namespace Ui { class MainWindow; } 62 | QT_END_NAMESPACE 63 | 64 | class MainWindow : public QMainWindow 65 | { 66 | Q_OBJECT 67 | 68 | public: 69 | MainWindow(QWidget *parent = nullptr); 70 | ~MainWindow(); 71 | 72 | private: 73 | Ui::MainWindow *ui; 74 | QChartView *chartView; // To hold our chart view 75 | }; 76 | #endif // MAINWINDOW_H 77 | -------------------------------------------------------------------------------- /Download file/README.md: -------------------------------------------------------------------------------- 1 | 2 | requirements linker: 3 | ``` 4 | -lcurl 5 | ``` 6 | -------------------------------------------------------------------------------- /Download file/main.cpp: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /DownloadFile.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rzlahd/CPP/8d4ce62a7db7b7b0800d12f436b765b23ab94dfc/DownloadFile.exe -------------------------------------------------------------------------------- /Flow of Control/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | main() { 4 | int result = 0, value = 1; 5 | /* Sytax 6 | while (condition) 7 | statement 8 | */ 9 | // keep executing the while as long as value is less than or equal to 10 because value less then 10 10 | while (value <= 10) { 11 | result += value; // assigns result + value to result 12 | ++value; // add 1 to value 13 | } 14 | std::cout<< "Sum of 1 to 10 inclusive is "< 25 | #include 26 | using std::cout; 27 | using std::endl; 28 | 29 | #include 30 | using namespace Json; 31 | 32 | int main(int argc, char* argv[]) { 33 | Reader Baca; 34 | Value Akar; 35 | std::ifstream ifs; 36 | if(argv[1]) { 37 | ifs.open(argv[1]); 38 | } else { 39 | ifs.open("data.json"); 40 | } 41 | 42 | Baca.parse(ifs, Akar); // reader can also read strings 43 | 44 | cout << "Book: " << Akar["Kopi Careh"].asUInt() << endl; 45 | 46 | const Value& buku = Akar["Daftar_isi"]; // array of characters 47 | for (int i = 0; i < buku.size(); i++){ 48 | cout << " Buku : " << buku[i]["Buku"].asUInt()<< endl; 49 | cout << " Nama : " << buku[i]["nama"].asString()<< endl; 50 | cout << " Tahun : " << buku[i]["tahun"].asString()<< endl; 51 | cout << endl; 52 | } 53 | 54 | std::cout << "Patch Data: " << std::endl; 55 | std::cout << Akar << std::endl; 56 | 57 | return EXIT_SUCCESS; 58 | } 59 | -------------------------------------------------------------------------------- /Json/data.json: -------------------------------------------------------------------------------- 1 | { 2 | "Kopi Careh":1, 3 | "Daftar_isi": 4 | [ 5 | 6 | {"Buku":1, "nama":"Kopi Careh", "tahun": 1996 }, 7 | {"Buku":2, "nama":"Tangkal Kopi", "tahun": 1995 }, 8 | {"Buku":3, "nama":"Semangat Kopi", "tahun": 1999}, 9 | {"Buku":4, "nama":"Slow Kopi", "tahun": 2010}, 10 | ] 11 | } 12 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 izal 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # CPP 2 | 3 | g++ your_file.cpp -o your_executable 4 | -------------------------------------------------------------------------------- /array/main.cpp: -------------------------------------------------------------------------------- 1 | int arr[2][3] = { 2 | {1,2,3}, 3 | {4,5,6} 4 | }; 5 | 6 | int arr2[2][2][3] = { 7 | // cars 8 | { 9 | {1,2,3}, 10 | {4,5,6} 11 | }, 12 | // bike 13 | { 14 | {7,8,9}, 15 | {10,11,12} 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /clock_sfml.cpp: -------------------------------------------------------------------------------- 1 | /* ---------- 2 | -lsfml-main 3 | -lsfml-graphics 4 | -lsfml-system 5 | -lsfml-window 6 | */ 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | 15 | using namespace sf; 16 | using namespace std; 17 | 18 | int main() { 19 | HWND hwnd = GetConsoleWindow();//Make the toolbar transparent 20 | if (hwnd != NULL){ 21 | SetWindowLong(hwnd, GWL_EXSTYLE, GetWindowLong(hwnd, GWL_EXSTYLE) | WS_EX_LAYERED); 22 | SetLayeredWindowAttributes(hwnd, 0, 0, LWA_ALPHA); 23 | } 24 | ShowWindow(GetConsoleWindow(), SW_HIDE); 25 | // Window dimensions 26 | const float WINDOW_WIDTH = 800; 27 | const float WINDOW_HEIGHT = 600; 28 | 29 | // Clock radius 30 | const float CLOCK_RADIUS = 250; 31 | const float CENTER_RADIUS = 10; 32 | 33 | // Hand lengths 34 | const float HOUR_HAND_LENGTH = CLOCK_RADIUS * 0.5; 35 | const float MINUTE_HAND_LENGTH = CLOCK_RADIUS * 0.7; 36 | const float SECOND_HAND_LENGTH = CLOCK_RADIUS * 0.9; 37 | 38 | // Hand colors 39 | const Color HOUR_COLOR = Color::White; 40 | const Color MINUTE_COLOR = Color::White; 41 | const Color SECOND_COLOR = Color::Red; 42 | 43 | // Create the window 44 | RenderWindow window(VideoMode(WINDOW_WIDTH, WINDOW_HEIGHT), "Analog Clock", Style::Titlebar | Style::Close); 45 | window.setFramerateLimit(60); // Cap the frame rate 46 | 47 | // ----------------------- 48 | // Clock face 49 | // ----------------------- 50 | CircleShape clockFace(CLOCK_RADIUS); 51 | // Create a gradient for the clock face 52 | VertexArray gradient(TriangleFan, 6); 53 | gradient[0].position = Vector2f(WINDOW_WIDTH / 2, WINDOW_HEIGHT / 2); 54 | gradient[0].color = Color(50, 50, 50); // Darker center 55 | 56 | for (int i = 1; i <= 5; ++i) { 57 | float angle = i * 72.0f * (3.14159f / 180.0f); // 5 points around the circle 58 | float x = WINDOW_WIDTH / 2 + CLOCK_RADIUS * cos(angle); 59 | float y = WINDOW_HEIGHT / 2 + CLOCK_RADIUS * sin(angle); 60 | gradient[i].position = Vector2f(x, y); 61 | gradient[i].color = Color(100, 100, 100); // Lighter edge 62 | } 63 | gradient[5].position = gradient[1].position; 64 | gradient[5].color = gradient[1].color; 65 | 66 | clockFace.setFillColor(Color::Transparent); // Make the circle transparent, so we see the gradient 67 | clockFace.setOutlineColor(Color::White); 68 | clockFace.setOutlineThickness(2); 69 | clockFace.setPosition(WINDOW_WIDTH / 2 - CLOCK_RADIUS, WINDOW_HEIGHT / 2 - CLOCK_RADIUS); 70 | 71 | // Add a shadow to the clock face. This is done by drawing a filled circle underneath, offset a bit. 72 | CircleShape shadow(CLOCK_RADIUS); 73 | shadow.setFillColor(Color(0, 0, 0, 100)); // Semi-transparent black 74 | shadow.setPosition(WINDOW_WIDTH / 2 - CLOCK_RADIUS + 5, WINDOW_HEIGHT / 2 - CLOCK_RADIUS + 5); // Offset the shadow 75 | 76 | // Center point 77 | CircleShape centerPoint(CENTER_RADIUS); 78 | centerPoint.setFillColor(Color::White); 79 | centerPoint.setPosition(WINDOW_WIDTH / 2 - CENTER_RADIUS, WINDOW_HEIGHT / 2 - CENTER_RADIUS); 80 | 81 | // Hour hand 82 | RectangleShape hourHand(Vector2f(7, HOUR_HAND_LENGTH)); // Thicker hand 83 | hourHand.setFillColor(HOUR_COLOR); 84 | hourHand.setOrigin(3.5, HOUR_HAND_LENGTH); 85 | hourHand.setPosition(WINDOW_WIDTH / 2, WINDOW_HEIGHT / 2); 86 | 87 | // Minute hand 88 | RectangleShape minuteHand(Vector2f(5, MINUTE_HAND_LENGTH)); // Thicker hand 89 | minuteHand.setFillColor(MINUTE_COLOR); 90 | minuteHand.setOrigin(2.5, MINUTE_HAND_LENGTH); 91 | minuteHand.setPosition(WINDOW_WIDTH / 2, WINDOW_HEIGHT / 2); 92 | 93 | // Second hand 94 | RectangleShape secondHand(Vector2f(3, SECOND_HAND_LENGTH)); // Slightly thicker 95 | secondHand.setFillColor(SECOND_COLOR); 96 | secondHand.setOrigin(1.5, SECOND_HAND_LENGTH); 97 | secondHand.setPosition(WINDOW_WIDTH / 2, WINDOW_HEIGHT / 2); 98 | 99 | // Tick marks 100 | // vector tickMarks; 101 | // for (int i = 0; i < 60; ++i) { 102 | // float length = (i % 5 == 0) ? 15 : 8; // Longer ticks for hours, shorter for minutes 103 | // float thickness = (i % 5 == 0) ? 3 : 1; // Thicker hour ticks 104 | // // RectangleShape tick(Vector2f(thickness, length)); 105 | // tick.setFillColor(Color::White); 106 | // tick.setOrigin(thickness / 2, length); 107 | // tick.setPosition(WINDOW_WIDTH / 2, WINDOW_HEIGHT / 2); 108 | // tick.setRotation(i * 6); 109 | // tickMarks.push_back(tick); 110 | // } 111 | 112 | // Numbers 113 | Font font; 114 | if (!font.loadFromFile("Roboto-Regular.ttf")) { // Use Roboto font 115 | cerr << "Failed to load font!" << endl; 116 | return 1; 117 | } 118 | vector numbers; 119 | for (int i = 1; i <= 12; ++i) { 120 | Text number; 121 | number.setFont(font); 122 | number.setString(to_string(i)); 123 | number.setCharacterSize(24); // Larger font size 124 | number.setFillColor(Color::White); 125 | // Position the numbers. 126 | float angle = (i - 3) * 30.0f * (3.14159f / 180.0f); 127 | float x = WINDOW_WIDTH / 2 + (CLOCK_RADIUS * 0.8f) * cos(angle); 128 | float y = WINDOW_HEIGHT / 2 + (CLOCK_RADIUS * 0.8f) * sin(angle); 129 | number.setPosition(x, y); 130 | // Center the number 131 | FloatRect bounds = number.getLocalBounds(); 132 | number.setOrigin(bounds.left + bounds.width / 2, bounds.top + bounds.height / 2); 133 | numbers.push_back(number); 134 | } 135 | 136 | // Load the background image 137 | Texture backgroundTexture; 138 | if (!backgroundTexture.loadFromFile("background.jpg")) { // Replace with your image file 139 | cerr << "Failed to load background image!" << endl; 140 | return 1; 141 | } 142 | RectangleShape background(Vector2f(WINDOW_WIDTH, WINDOW_HEIGHT)); 143 | background.setTexture(&backgroundTexture); 144 | 145 | 146 | // Main loop 147 | while (window.isOpen()) { 148 | // Event handling 149 | Event event; 150 | while (window.pollEvent(event)) { 151 | if (event.type == Event::Closed) { 152 | window.close(); 153 | } 154 | } 155 | 156 | // Get current time 157 | time_t now = time(0); 158 | tm* ltm = localtime(&now); 159 | int hour = ltm->tm_hour % 12; 160 | int minute = ltm->tm_min; 161 | int second = ltm->tm_sec; 162 | 163 | // Calculate hand angles 164 | float secondAngle = second * 6.0f; 165 | float minuteAngle = (minute + second / 60.0f) * 6.0f; 166 | float hourAngle = (hour + minute / 60.0f) * 30.0f; 167 | 168 | // Rotate hands 169 | secondHand.setRotation(secondAngle); 170 | minuteHand.setRotation(minuteAngle); 171 | hourHand.setRotation(hourAngle); 172 | 173 | // Clear the window 174 | window.clear(Color(30, 30, 30)); 175 | 176 | // Draw everything 177 | window.draw(background); // Draw background first 178 | window.draw(shadow); // Draw shadow first 179 | window.draw(clockFace); 180 | // window.draw(gradient); // Draw the gradient 181 | // for (const auto& tick : tickMarks) { 182 | // window.draw(tick); 183 | // } 184 | for (const auto& number : numbers) { 185 | window.draw(number); 186 | } 187 | window.draw(centerPoint); 188 | window.draw(hourHand); 189 | window.draw(minuteHand); 190 | window.draw(secondHand); 191 | 192 | // Display the window 193 | window.display(); 194 | } 195 | 196 | return 0; 197 | } 198 | -------------------------------------------------------------------------------- /cryptopp/Diffie-Hellman.cpp: -------------------------------------------------------------------------------- 1 | // g++ -g3 -ggdb -O0 -I. -I/usr/include/cryptopp dh-xport.cpp -o dh-xport.exe -lcryptopp -lpthread 2 | // g++ -g -O2 -I. -I/usr/include/cryptopp dh-xport.cpp -o dh-xport.exe -lcryptopp -lpthread 3 | 4 | #include 5 | using std::cout; 6 | using std::cerr; 7 | using std::endl; 8 | 9 | #include 10 | using std::string; 11 | 12 | #include 13 | using std::runtime_error; 14 | 15 | #include "cryptopp/osrng.h" 16 | using CryptoPP::AutoSeededRandomPool; 17 | 18 | #include "cryptopp/integer.h" 19 | using CryptoPP::Integer; 20 | 21 | #include "cryptopp/nbtheory.h" 22 | using CryptoPP::ModularExponentiation; 23 | 24 | #include "cryptopp/dh.h" 25 | using CryptoPP::DH; 26 | 27 | #include "cryptopp/dh2.h" 28 | using CryptoPP::DH2; 29 | 30 | #include "cryptopp/secblock.h" 31 | using CryptoPP::SecByteBlock; 32 | 33 | #include 34 | using CryptoPP::CMAC; 35 | 36 | #include "cryptopp/aes.h" 37 | using CryptoPP::AES; 38 | 39 | #include "cryptopp/modes.h" 40 | using CryptoPP::ECB_Mode; 41 | 42 | int main(int argc, char** argv) 43 | { 44 | try 45 | { 46 | // Generated offline using Crypto++. 47 | // 3072 bit safe prime. 48 | Integer p("0xbfef6a7e54ba72ba09873e7ad1f3dbac8e4ae5e55534974948d67c38e07baa8036f321b6372" 49 | "9469c02f70089426b6dcbf3b1f0c3574fc73f2509995e32b5a04e983d4363145f7ba599e760e85" 50 | "50991d21716f9b298a636b9a929c68a5ccc9af4f3cf1a8815002026df2853efbc28e9e1d7cc75b" 51 | "a53af6b618bed49b4d447100c4ddfd086d89f90a145ab912e7f335a595715eccb71409f3eaca38" 52 | "6db495d7c9e054001a514c2cb15c4438ca2e573defed0aaa76a4068bc1b2953094713a48f21168" 53 | "fbd30020fbe6e977e6d6908a25bd2983ff5e7e1237cf80b3b5f2f99dde22c63977718e073e7f2f" 54 | "44fea12d82ff53c031874958d6f6d81d156cc78b7a20ef8d31860f0dca106feacc7a2b609dd259" 55 | "3b1b1c1bc0d116a1ed2472f7507059f8108b0b6a3f69f3661e352c546c523ac85908e32f35155e" 56 | "9f4f0abbb70c83e122e51a4fee3184c45ecdfd50b5da59fefefc1f0d441074ed2269dc4b274e59" 57 | "1a8464d2c34f9c2e8cd1db308088503e9bbdf325f67b4830833ca10baae2fd1de7b57"); 58 | 59 | Integer q = (p-1)/2; 60 | 61 | Integer g("0x2"); 62 | 63 | // Safe primes are of the form p = 2q + 1, p and q prime. 64 | // These parameters do not state a maximum security level based 65 | // on the prime subgroup order. In essence, we get the maximum 66 | // security level. There is no free lunch: it means more modular 67 | // mutliplications are performed, which affects performance. 68 | 69 | // For a compare/contrast of meeting a security level, see dh-init.zip. 70 | // Also see http://www.cryptopp.com/wiki/Diffie-Hellman and 71 | // http://www.cryptopp.com/wiki/Security_level . 72 | 73 | DH dh; 74 | AutoSeededRandomPool rnd; 75 | 76 | dh.AccessGroupParameters().Initialize(p, g); 77 | 78 | if(!dh.GetGroupParameters().ValidateGroup(rnd, 3)) 79 | throw runtime_error("Failed to validate prime and generator"); 80 | 81 | size_t count = 0; 82 | 83 | p = dh.GetGroupParameters().GetModulus(); 84 | q = dh.GetGroupParameters().GetSubgroupOrder(); 85 | g = dh.GetGroupParameters().GetGenerator(); 86 | 87 | //cout << "P: " << std::hex << p << endl; 88 | //cout << "Q: " << std::hex << q << endl; 89 | //cout << "G: " << std::hex << g << endl; 90 | 91 | // http://groups.google.com/group/sci.crypt/browse_thread/thread/7dc7eeb04a09f0ce 92 | Integer v = ModularExponentiation(g, q, p); 93 | if(v != Integer::One()) 94 | { 95 | cout << "Verification: " << std::hex << v << endl; 96 | throw runtime_error("Failed to verify order of the subgroup"); 97 | } 98 | 99 | ////////////////////////////////////////////////////////////// 100 | 101 | DH2 dhA(dh), dhB(dh); 102 | 103 | SecByteBlock sprivA(dhA.StaticPrivateKeyLength()), spubA(dhA.StaticPublicKeyLength()); 104 | SecByteBlock eprivA(dhA.EphemeralPrivateKeyLength()), epubA(dhA.EphemeralPublicKeyLength()); 105 | 106 | SecByteBlock sprivB(dhB.StaticPrivateKeyLength()), spubB(dhB.StaticPublicKeyLength()); 107 | SecByteBlock eprivB(dhB.EphemeralPrivateKeyLength()), epubB(dhB.EphemeralPublicKeyLength()); 108 | 109 | dhA.GenerateStaticKeyPair(rnd, sprivA, spubA); 110 | dhA.GenerateEphemeralKeyPair(rnd, eprivA, epubA); 111 | 112 | dhB.GenerateStaticKeyPair(rnd, sprivB, spubB); 113 | dhB.GenerateEphemeralKeyPair(rnd, eprivB, epubB); 114 | 115 | ////////////////////////////////////////////////////////////// 116 | 117 | if(dhA.AgreedValueLength() != dhB.AgreedValueLength()) 118 | throw runtime_error("Shared secret size mismatch"); 119 | 120 | SecByteBlock sharedA(dhA.AgreedValueLength()), sharedB(dhB.AgreedValueLength()); 121 | 122 | if(!dhA.Agree(sharedA, sprivA, eprivA, spubB, epubB)) 123 | throw runtime_error("Failed to reach shared secret (A)"); 124 | 125 | if(!dhB.Agree(sharedB, sprivB, eprivB, spubA, epubA)) 126 | throw runtime_error("Failed to reach shared secret (B)"); 127 | 128 | count = std::min(dhA.AgreedValueLength(), dhB.AgreedValueLength()); 129 | if(!count || 0 != memcmp(sharedA.BytePtr(), sharedB.BytePtr(), count)) 130 | throw runtime_error("Failed to reach shared secret"); 131 | 132 | ////////////////////////////////////////////////////////////// 133 | 134 | // Take the leftmost 'n' bits for the KEK 135 | SecByteBlock kek(sharedA.BytePtr(), AES::DEFAULT_KEYLENGTH); 136 | 137 | // CMAC key follows the 'n' bits used for KEK 138 | SecByteBlock mack(&sharedA.BytePtr()[AES::DEFAULT_KEYLENGTH], AES::BLOCKSIZE); 139 | CMAC cmac(mack.BytePtr(), mack.SizeInBytes()); 140 | 141 | // Generate a random CEK 142 | SecByteBlock cek(AES::DEFAULT_KEYLENGTH); 143 | rnd.GenerateBlock(cek.BytePtr(), cek.SizeInBytes()); 144 | 145 | // AES in ECB mode is fine - we're encrypting 1 block, so we don't need padding 146 | ECB_Mode::Encryption aes; 147 | aes.SetKey(kek.BytePtr(), kek.SizeInBytes()); 148 | 149 | // Will hold the encrypted key and cmac 150 | SecByteBlock xport(AES::BLOCKSIZE /*ENC(CEK)*/ + AES::BLOCKSIZE /*CMAC*/); 151 | CryptoPP::byte* const ptr = xport.BytePtr(); 152 | 153 | // Write the encrypted key in the first 16 bytes, and the CMAC in the second 16 bytes 154 | // The logical layout of xport: 155 | // [ Enc(CEK) ][ CMAC(Enc(CEK)) ] 156 | aes.ProcessData(&ptr[0], cek.BytePtr(), AES::BLOCKSIZE); 157 | cmac.CalculateTruncatedDigest(&ptr[AES::BLOCKSIZE], AES::BLOCKSIZE, &ptr[0], AES::BLOCKSIZE); 158 | 159 | Integer a, b, c; 160 | 161 | a.Decode(kek.BytePtr(), kek.SizeInBytes()); 162 | cout << "Key encryption key: " << std::hex << a << endl; 163 | 164 | b.Decode(cek.BytePtr(), cek.SizeInBytes()); 165 | cout << "Content encryption key: " << std::hex << b << endl; 166 | 167 | c.Decode(xport.BytePtr(), xport.SizeInBytes()); 168 | cout << "Encrypted CEK with CMAC: " << std::hex << c << endl; 169 | } 170 | 171 | catch(const CryptoPP::Exception& e) 172 | { 173 | cerr << e.what() << endl; 174 | return -2; 175 | } 176 | 177 | catch(const std::exception& e) 178 | { 179 | cerr << e.what() << endl; 180 | return -1; 181 | } 182 | 183 | return 0; 184 | } 185 | 186 | -------------------------------------------------------------------------------- /cryptopp/tes1.cpp: -------------------------------------------------------------------------------- 1 | 2 | 3 | // stdafx.h : menyertakan file untuk sistem standar termasuk file, 4 | // atau proyek tertentu menyertakan file yang sering digunakan, namun 5 | // jarang diubah 6 | // 7 | 8 | #pragma once 9 | 10 | #pragma once 11 | 12 | // Makro berikut menentukan platform minimum yang diperlukan. Platform minimum yang diperlukan 13 | // adalah versi paling awal dari Windows, Internet Explorer, dll. yang memiliki fitur yang diperlukan untuk dijalankan 14 | // aplikasi Anda. Makro bekerja dengan mengaktifkan semua fitur yang tersedia pada versi platform hingga dan 15 | // termasuk versi yang ditentukan. 16 | 17 | // Ubah definisi berikut jika Anda harus menargetkan platform sebelum yang ditentukan di bawah. 18 | // Lihat MSDN untuk info terbaru tentang nilai yang sesuai untuk platform berbeda. 19 | #ifndef _WIN32_WINNT // Specifies that the minimum required platform is Windows Vista. 20 | #define _WIN32_WINNT 0x0500 // Change this to the appropriate value to target other versions of Windows. 21 | #endif 22 | 23 | 24 | 25 | #include 26 | #include 27 | 28 | #include 29 | using std::cin; 30 | using std::wcin; 31 | using std::cout; 32 | using std::wcout; 33 | using std::cerr; 34 | using std::wcerr; 35 | using std::endl; 36 | 37 | #include 38 | using std::string; 39 | using std::wstring; 40 | 41 | #ifdef UNICODE 42 | # define tcin wcin 43 | # define tcout wcout 44 | # define tcerr wcerr 45 | # define tstring wstring 46 | #else 47 | # define tcin cin 48 | # define tcout cout 49 | # define tcerr cerr 50 | # define tstring string 51 | #endif 52 | 53 | 54 | 55 | #include 56 | using std::cout; 57 | using std::cerr; 58 | 59 | #include 60 | using std::string; 61 | 62 | #include "cryptopp/hex.h" 63 | using CryptoPP::HexEncoder; 64 | using CryptoPP::HexDecoder; 65 | 66 | #include "cryptopp/osrng.h" 67 | using CryptoPP::AutoSeededRandomPool; 68 | 69 | #include "cryptopp/cryptlib.h" 70 | using CryptoPP::BufferedTransformation; 71 | using CryptoPP::AuthenticatedSymmetricCipher; 72 | 73 | #include "cryptopp/filters.h" 74 | using CryptoPP::Redirector; 75 | using CryptoPP::StringSink; 76 | using CryptoPP::StringSource; 77 | using CryptoPP::AuthenticatedEncryptionFilter; 78 | using CryptoPP::AuthenticatedDecryptionFilter; 79 | 80 | #include "cryptopp/aes.h" 81 | using CryptoPP::AES; 82 | 83 | #include "cryptopp/ccm.h" 84 | using CryptoPP::CCM; 85 | 86 | #include "assert.h" 87 | 88 | int main(int argc, char* argv[]) 89 | { 90 | // The test vectors use both ADATA and PDATA. However, 91 | // as a drop in replacement for older modes such as 92 | // CBC, we only exercise (and need) plain text. 93 | 94 | AutoSeededRandomPool prng; 95 | 96 | byte key[ AES::DEFAULT_KEYLENGTH ]; 97 | prng.GenerateBlock( key, sizeof(key) ); 98 | 99 | // { 7, 8, 9, 10, 11, 12, 13 } 100 | byte iv[ 12 ]; 101 | prng.GenerateBlock( iv, sizeof(iv) ); 102 | 103 | // { 4, 6, 8, 10, 12, 14, 16 } 104 | const int TAG_SIZE = 8; 105 | 106 | string pdata="Authenticated Encryption"; 107 | 108 | // Encrypted, with Tag 109 | string cipher, encoded; 110 | 111 | // Recovered 112 | string rpdata; 113 | 114 | /*********************************\ 115 | \*********************************/ 116 | 117 | // Pretty print 118 | encoded.clear(); 119 | StringSource( key, sizeof(key), true, 120 | new HexEncoder( 121 | new StringSink( encoded ) 122 | ) // HexEncoder 123 | ); // StringSource 124 | cout << "key: " << encoded << endl; 125 | 126 | // Pretty print 127 | encoded.clear(); 128 | StringSource( iv, sizeof(iv), true, 129 | new HexEncoder( 130 | new StringSink( encoded ) 131 | ) // HexEncoder 132 | ); // StringSource 133 | cout << " iv: " << encoded << endl; 134 | 135 | cout << endl; 136 | 137 | /*********************************\ 138 | \*********************************/ 139 | 140 | try 141 | { 142 | cout << "plain text: " << pdata << endl; 143 | 144 | CCM< AES, TAG_SIZE >::Encryption e; 145 | e.SetKeyWithIV( key, sizeof(key), iv, sizeof(iv) ); 146 | e.SpecifyDataLengths( 0, pdata.size(), 0 ); 147 | 148 | StringSource( pdata, true, 149 | new AuthenticatedEncryptionFilter( e, 150 | new StringSink( cipher ) 151 | ) // AuthenticatedEncryptionFilter 152 | ); // StringSource 153 | } 154 | catch( CryptoPP::InvalidArgument& e ) 155 | { 156 | cerr << "Caught InvalidArgument..." << endl; 157 | cerr << e.what() << endl; 158 | cerr << endl; 159 | } 160 | catch( CryptoPP::Exception& e ) 161 | { 162 | cerr << "Caught Exception..." << endl; 163 | cerr << e.what() << endl; 164 | cerr << endl; 165 | } 166 | 167 | /*********************************\ 168 | \*********************************/ 169 | 170 | // Pretty print 171 | encoded.clear(); 172 | StringSource( cipher, true, 173 | new HexEncoder( 174 | new StringSink( encoded ) 175 | ) // HexEncoder 176 | ); // StringSource 177 | cout << "cipher text: " << encoded << endl; 178 | 179 | // Attack the first and last byte 180 | //if( cipher.size() > 1 ) 181 | //{ 182 | // cipher[ 0 ] |= 0x0F; 183 | // cipher[ cipher.size()-1 ] |= 0x0F; 184 | //} 185 | 186 | /*********************************\ 187 | \*********************************/ 188 | 189 | try 190 | { 191 | CCM< AES, TAG_SIZE >::Decryption d; 192 | d.SetKeyWithIV( key, sizeof(key), iv, sizeof(iv) ); 193 | d.SpecifyDataLengths( 0, cipher.size()-TAG_SIZE, 0 ); 194 | 195 | AuthenticatedDecryptionFilter df( d, 196 | new StringSink( rpdata ) 197 | ); // AuthenticatedDecryptionFilter 198 | 199 | // Dtor StringSource akan segera dipanggil 200 | // setelah konstruksi di bawah. Hal ini akan menyebabkan 201 | // penghancuran benda yang dimilikinya. Untuk menghentikan 202 | // perilaku sehingga kita bisa mendapatkan hasil decodingnya 203 | // DecryptionFilter, kita harus menggunakan redirector 204 | // atau secara manual Masukkan(...) ke dalam filter tanpa 205 | // menggunakan StringSource. 206 | StringSource( cipher, true, 207 | new Redirector( df /*, PASS_EVERYTHING */ ) 208 | ); // StringSource 209 | 210 | // If the object does not throw, here's the only 211 | // opportunity to check the data's integrity 212 | bool b = df.GetLastResult(); 213 | assert( true == b ); 214 | 215 | cout << "recovered text: " << rpdata << endl; 216 | } 217 | catch( CryptoPP::HashVerificationFilter::HashVerificationFailed& e ) 218 | { 219 | cerr << "Caught HashVerificationFailed..." << endl; 220 | cerr << e.what() << endl; 221 | cerr << endl; 222 | } 223 | catch( CryptoPP::InvalidArgument& e ) 224 | { 225 | cerr << "Caught InvalidArgument..." << endl; 226 | cerr << e.what() << endl; 227 | cerr << endl; 228 | } 229 | catch( CryptoPP::Exception& e ) 230 | { 231 | cerr << "Caught Exception..." << endl; 232 | cerr << e.what() << endl; 233 | cerr << endl; 234 | } 235 | 236 | /*********************************\ 237 | \*********************************/ 238 | 239 | return 0; 240 | } 241 | -------------------------------------------------------------------------------- /cryptopp/tes3.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #include 5 | using std::cout; 6 | using std::cerr; 7 | using std::endl; 8 | 9 | #include 10 | using std::string; 11 | 12 | #include "cryptopp/hex.h" 13 | using CryptoPP::HexEncoder; 14 | using CryptoPP::HexDecoder; 15 | 16 | #include "cryptopp/cryptlib.h" 17 | using CryptoPP::BufferedTransformation; 18 | using CryptoPP::AuthenticatedSymmetricCipher; 19 | 20 | #include "cryptopp/filters.h" 21 | using CryptoPP::StringSink; 22 | using CryptoPP::StringSource; 23 | using CryptoPP::AuthenticatedEncryptionFilter; 24 | using CryptoPP::AuthenticatedDecryptionFilter; 25 | 26 | #include "cryptopp/aes.h" 27 | using CryptoPP::AES; 28 | 29 | #include "cryptopp/ccm.h" 30 | using CryptoPP::CCM; 31 | 32 | #include "assert.h" 33 | 34 | int main(int argc, char* argv[]) 35 | { 36 | // Human Readable 37 | //byte key[ AES::DEFAULT_KEYLENGTH ]; 38 | //memset( key, '4', sizeof(key) ); 39 | //byte iv[ 12 ]; 40 | //memset( iv, '8', sizeof(iv) ); 41 | //string adata="Authenticated"; 42 | //string pdata="Authenticated Encryption"; 43 | //const int TAG_SIZE = 6; 44 | 45 | // Vector 001 46 | //byte key[]={0x40,0x41,0x42,0x43,0x44,0x45,0x46,0x47, 47 | // 0x48,0x49,0x4a,0x4b,0x4c,0x4d,0x4e,0x4f}; 48 | //byte iv[]={0x10,0x11,0x12,0x13,0x14,0x15,0x16}; 49 | //const byte aa[] = { 0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07 }; 50 | //string adata = string( (const char*)aa, sizeof(aa) ); 51 | //const byte pa[] = { 0x20,0x21,0x22,0x23 }; 52 | //string pdata = string( (const char*)pa, sizeof(pa) ); 53 | //const int TAG_SIZE = 4; 54 | //CTX 7162015b 55 | //TAG 4dac255d 56 | 57 | // Test Vector 003 58 | CryptoPP::byte key[] = { 0x40,0x41,0x42,0x43,0x44,0x45,0x46,0x47, 59 | 0x48,0x49,0x4a,0x4b,0x4c,0x4d,0x4e,0x4f }; 60 | CryptoPP::byte iv[]={ 0x10,0x11,0x12,0x13,0x14,0x15,0x16, 61 | 0x17,0x18,0x19,0x1a,0x1b }; 62 | 63 | const CryptoPP::byte aa[] = { 0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07, 64 | 0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f,0x10,0x11,0x12,0x13 }; 65 | string adata = string( (const char*)aa, sizeof(aa) ); 66 | 67 | const CryptoPP::byte pa[] = { 0x20,0x21,0x22,0x23,0x24,0x25,0x26,0x27, 68 | 0x28,0x29,0x2a,0x2b,0x2c,0x2d,0x2e,0x2f, 69 | 0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37 }; 70 | string pdata = string( (const char*)pa, sizeof(pa) ); 71 | const int TAG_SIZE = 8; 72 | 73 | //CTX e3b201a9f5b71a7a9b1ceaeccd97e70b6176aad9a4428aa5 74 | //TAG 484392fbc1b09951 75 | 76 | // Encrypted, with Tag 77 | string cipher, encoded; 78 | 79 | // Recovered 80 | string radata, rpdata; 81 | 82 | /*********************************\ 83 | \*********************************/ 84 | 85 | try 86 | { 87 | CCM< AES, TAG_SIZE >::Encryption e; 88 | e.SetKeyWithIV( key, sizeof(key), iv, sizeof(iv) ); 89 | e.SpecifyDataLengths( adata.size(), pdata.size(), 0 ); 90 | 91 | AuthenticatedEncryptionFilter ef( e, 92 | new StringSink( cipher ) 93 | ); // AuthenticatedEncryptionFilter 94 | 95 | // AuthenticatedEncryptionFilter::ChannelPut 96 | // defines two channels: "" (empty) and "AAD" 97 | // channel "" is encrypted and authenticated 98 | // channel "AAD" is authenticated 99 | ef.ChannelPut( "AAD", (const CryptoPP::byte*)adata.data(), adata.size() ); 100 | ef.ChannelMessageEnd("AAD"); 101 | 102 | // Authenticated data *must* be pushed before 103 | // Confidential/Authenticated data 104 | ef.ChannelPut( "", (const CryptoPP::byte*)pdata.data(), pdata.size() ); 105 | ef.ChannelMessageEnd(""); 106 | 107 | // Pretty print 108 | StringSource( cipher, true, 109 | new HexEncoder( new StringSink( encoded ), true, 16, " " ) ); 110 | } 111 | catch( CryptoPP::BufferedTransformation::NoChannelSupport& e ) 112 | { 113 | // The tag must go in to the default channel: 114 | // "unknown: this object doesn't support multiple channels" 115 | cerr << "Caught NoChannelSupport..." << endl; 116 | cerr << e.what() << endl; 117 | cerr << endl; 118 | } 119 | catch( CryptoPP::InvalidArgument& e ) 120 | { 121 | cerr << "Caught InvalidArgument..." << endl; 122 | cerr << e.what() << endl; 123 | cerr << endl; 124 | } 125 | 126 | /*********************************\ 127 | \*********************************/ 128 | 129 | // Attack the first and last byte 130 | //if( cipher.size() > 1 ) 131 | //{ 132 | // cipher[ 0 ] |= 0x0F; 133 | // cipher[ cipher.size()-1 ] |= 0x0F; 134 | //} 135 | 136 | /*********************************\ 137 | \*********************************/ 138 | 139 | try 140 | { 141 | // Break the cipher text out into it's 142 | // components: Encrypted and MAC 143 | string enc = cipher.substr( 0, cipher.length()-TAG_SIZE ); 144 | string tag = cipher.substr( cipher.length()-TAG_SIZE ); 145 | 146 | // Sanity checks 147 | assert( cipher.size() == enc.size() + tag.size() ); 148 | assert( enc.size() == pdata.size() ); 149 | assert( TAG_SIZE == tag.size() ); 150 | 151 | // Not recovered - sent via clear channel 152 | radata = adata; 153 | 154 | CCM< AES, TAG_SIZE >::Decryption d; 155 | d.SetKeyWithIV( key, sizeof(key), iv, sizeof(iv) ); 156 | d.SpecifyDataLengths( radata.size(), enc.size(), 0 ); 157 | 158 | // Object will not throw an exception 159 | // during decryption\verification _if_ 160 | // verification fails. 161 | //AuthenticatedDecryptionFilter df( d, NULL, 162 | // AuthenticatedDecryptionFilter::MAC_AT_BEGIN ); 163 | 164 | AuthenticatedDecryptionFilter df( d, NULL, 165 | AuthenticatedDecryptionFilter::MAC_AT_BEGIN | 166 | AuthenticatedDecryptionFilter::THROW_EXCEPTION ); 167 | 168 | // The order of the following calls are important 169 | df.ChannelPut( "", (const CryptoPP::byte*)tag.data(), tag.size() ); 170 | df.ChannelPut( "AAD", (const CryptoPP::byte*)adata.data(), adata.size() ); 171 | df.ChannelPut( "", (const CryptoPP::byte*)enc.data(), enc.size() ); 172 | 173 | df.ChannelMessageEnd( "AAD" ); 174 | df.ChannelMessageEnd( "" ); 175 | 176 | // If the object does not throw, here's the only 177 | // opportunity to check the data's integrity 178 | bool b = false; 179 | b = df.GetLastResult(); 180 | assert( true == b ); 181 | 182 | // Remove data from channel 183 | string retrieved; 184 | size_t n = (size_t)-1; 185 | 186 | // Plain text recovered from enc.data() 187 | df.SetRetrievalChannel( "" ); 188 | n = (size_t)df.MaxRetrievable(); 189 | retrieved.resize( n ); 190 | 191 | if( n > 0 ) { df.Get( (CryptoPP::byte*)retrieved.data(), n ); } 192 | rpdata = retrieved; 193 | assert( rpdata == pdata ); 194 | 195 | // Hmmm... No way to get the calculated MAC 196 | // tag out of the Decryptor/Verifier. At 197 | // least it is purported to be good. 198 | //df.SetRetrievalChannel( "AAD" ); 199 | //n = (size_t)df.MaxRetrievable(); 200 | //retrieved.resize( n ); 201 | 202 | //if( n > 0 ) { df.Get( (byte*)retrieved.data(), n ); } 203 | //assert( retrieved == tag ); 204 | 205 | // All is well - work with data 206 | cout << "Decrypted and Verified data. Ready for use." << endl; 207 | cout << endl; 208 | 209 | cout << "adata length: " << adata.size() << endl; 210 | cout << "pdata length: " << pdata.size() << endl; 211 | cout << endl; 212 | 213 | //cout << "adata: " << adata << endl; 214 | //cout << "pdata: " << pdata << endl; 215 | //cout << endl; 216 | 217 | cout << "cipher text (enc + tag): " << endl << " " << encoded << endl; 218 | cout << endl; 219 | 220 | cout << "recovered adata length: " << radata.size() << endl; 221 | cout << "recovered pdata length: " << rpdata.size() << endl; 222 | cout << endl; 223 | 224 | //cout << "recovered adata: " << radata << endl; 225 | //cout << "recovered pdata: " << rpdata << endl; 226 | //cout << endl; 227 | } 228 | catch( CryptoPP::InvalidArgument& e ) 229 | { 230 | cerr << "Caught InvalidArgument..." << endl; 231 | cerr << e.what() << endl; 232 | cerr << endl; 233 | } 234 | catch( CryptoPP::HashVerificationFilter::HashVerificationFailed& e ) 235 | { 236 | cerr << "Caught HashVerificationFailed..." << endl; 237 | cerr << e.what() << endl; 238 | cerr << endl; 239 | } 240 | 241 | /*********************************\ 242 | \*********************************/ 243 | 244 | return 0; 245 | } 246 | -------------------------------------------------------------------------------- /cryptopp/tes4.cpp: -------------------------------------------------------------------------------- 1 | // Driver.cpp 2 | // 3 | 4 | // stdafx.h : include file for standard system include files, 5 | // or project specific include files that are used frequently, but 6 | // are changed infrequently 7 | // 8 | 9 | #pragma once 10 | 11 | #ifndef _WIN32_WINNT // Allow use of features specific to Windows XP or later. 12 | #define _WIN32_WINNT 0x0501 // Change this to the appropriate value to target other versions of Windows. 13 | #endif 14 | 15 | #ifdef _DEBUG 16 | # pragma comment( lib, "cryptlibd" ) 17 | #else 18 | # pragma comment( lib, "cryptlib" ) 19 | #endif 20 | 21 | 22 | #include "cryptopp/osrng.h" 23 | using CryptoPP::AutoSeededRandomPool; 24 | 25 | #include 26 | using std::endl; 27 | using std::cout; 28 | using std::cerr; 29 | 30 | #include 31 | using std::string; 32 | 33 | #include "cryptopp/cryptlib.h" 34 | using CryptoPP::Exception; 35 | 36 | #include "cryptopp/files.h" 37 | using CryptoPP::FileSink; 38 | using CryptoPP::FileSource; 39 | 40 | #include "cryptopp/filters.h" 41 | using CryptoPP::ArraySink; 42 | using CryptoPP::StringSource; 43 | using CryptoPP::StringSink; 44 | using CryptoPP::StringStore; 45 | using CryptoPP::Redirector; 46 | 47 | using CryptoPP::SignerFilter; 48 | using CryptoPP::SignatureVerificationFilter; 49 | 50 | #include "cryptopp/dsa.h" 51 | using CryptoPP::DSA; 52 | 53 | #include "assert.h" 54 | 55 | void SaveKey( const DSA::PrivateKey& PrivateKey, const string& filename ); 56 | void LoadKey( const string& filename, DSA::PrivateKey& PrivateKey ); 57 | 58 | int main(int argc, char* argv[]) 59 | { 60 | try 61 | { 62 | AutoSeededRandomPool rng; 63 | 64 | // Generate Private Key 65 | DSA::PrivateKey PrivateKey; 66 | PrivateKey.GenerateRandomWithKeySize(rng, 1024); 67 | if (!PrivateKey.Validate(rng, 3)) 68 | { 69 | throw("DSA key generation failed"); 70 | } 71 | SaveKey( PrivateKey, "key.pv.bin" ); 72 | //LoadKey( "key.pv.bin", PrivateKey ); 73 | 74 | // Generate Public Key 75 | DSA::PublicKey PublicKey; 76 | PublicKey.AssignFrom(PrivateKey); 77 | 78 | // Sign and verify 79 | string message = "DSA Signature"; 80 | string signature; 81 | 82 | DSA::Signer signer( PrivateKey ); 83 | StringSource( message, true, 84 | new SignerFilter( rng, signer, 85 | new StringSink( signature ) 86 | ) // SignerFilter 87 | ); // StringSource 88 | 89 | // Tamper 90 | { 91 | // signature[0] |= 0x0F; 92 | // message[0] |= 0x0F; 93 | } 94 | 95 | DSA::Verifier verifier( PublicKey ); 96 | StringSource( message+signature, true, 97 | new SignatureVerificationFilter( 98 | verifier, NULL, 99 | SignatureVerificationFilter::THROW_EXCEPTION 100 | ) 101 | ); 102 | 103 | cout << "Verified signature on message" << endl; 104 | 105 | } 106 | catch( SignatureVerificationFilter::SignatureVerificationFailed& e ) 107 | { 108 | cerr << "caught SignatureVerificationFailed..." << endl; 109 | cerr << e.what() << endl; 110 | } 111 | catch( CryptoPP::Exception& e ) 112 | { 113 | cerr << "caught Exception..." << endl; 114 | cerr << e.what() << endl; 115 | } 116 | 117 | return 0; 118 | } 119 | 120 | void SaveKey( const DSA::PublicKey& PublicKey, const string& filename ) 121 | { 122 | // DER Encode Key - X.509 key format 123 | PublicKey.Save( 124 | FileSink( filename.c_str(), true /*binary*/ ).Ref() 125 | ); 126 | } 127 | 128 | void SaveKey( const DSA::PrivateKey& PrivateKey, const string& filename ) 129 | { 130 | // DER Encode Key - PKCS #8 key format 131 | PrivateKey.Save( 132 | FileSink( filename.c_str(), true /*binary*/ ).Ref() 133 | ); 134 | } 135 | 136 | void LoadKey( const string& filename, DSA::PublicKey& PublicKey ) 137 | { 138 | // DER Encode Key - X.509 key format 139 | PublicKey.Load( 140 | FileSource( filename.c_str(), true, NULL, true /*binary*/ ).Ref() 141 | ); 142 | } 143 | 144 | void LoadKey( const string& filename, DSA::PrivateKey& PrivateKey ) 145 | { 146 | // DER Encode Key - PKCS #8 key format 147 | PrivateKey.Load( 148 | FileSource( filename.c_str(), true, NULL, true /*binary*/ ).Ref() 149 | ); 150 | } 151 | 152 | void VerifyMessageThrow1( const DSA::PublicKey& PublicKey, 153 | const string& message, const string& signature ) 154 | { 155 | DSA::Verifier verifier( PublicKey ); 156 | 157 | StringSource( signature+message, true, 158 | new SignatureVerificationFilter( 159 | verifier, NULL, 160 | SignatureVerificationFilter::THROW_EXCEPTION | 161 | SignatureVerificationFilter::SIGNATURE_AT_BEGIN 162 | ) 163 | ); 164 | } 165 | 166 | void VerifyMessageThrow2( const DSA::PublicKey& PublicKey, 167 | const string& message, const string& signature ) 168 | { 169 | DSA::Verifier verifier( PublicKey ); 170 | 171 | StringSource( message+signature, true, 172 | new SignatureVerificationFilter( 173 | verifier, NULL, 174 | SignatureVerificationFilter::THROW_EXCEPTION 175 | ) 176 | ); 177 | } 178 | 179 | void VerifyMessageNoThrow1(const DSA::PublicKey& PublicKey, 180 | const string& message, const string& signature ) 181 | { 182 | DSA::Verifier verifier( PublicKey ); 183 | 184 | bool result = false; 185 | StringSource( message+signature, true, 186 | new SignatureVerificationFilter( 187 | verifier, 188 | new ArraySink( (CryptoPP::byte*)&result, sizeof(result ) ), 189 | SignatureVerificationFilter::PUT_RESULT 190 | ) 191 | ); 192 | } 193 | 194 | void VerifyMessageNoThrow2(const DSA::PublicKey& PublicKey, 195 | const string& message, const string& signature ) 196 | { 197 | DSA::Verifier verifier( PublicKey ); 198 | 199 | SignatureVerificationFilter svf( 200 | verifier 201 | ); // SignatureVerificationFilter 202 | 203 | StringSource( signature+message, true, 204 | new Redirector( svf ) 205 | ); // StringSource 206 | 207 | bool b = svf.GetLastResult(); 208 | } 209 | -------------------------------------------------------------------------------- /libs/readme.md: -------------------------------------------------------------------------------- 1 | OPEN msys2.exe 2 | 3 | type for 64bit: pacman -S mingw-w64-x86_64-gcc 4 | 5 | type for 32bit: pacman -S mingw-w64-i686-gcc 6 | -------------------------------------------------------------------------------- /makefile/factorial.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | // Definition of factorial function 4 | // is present in function.h file 5 | #include "function.h" 6 | using namespace std; 7 | 8 | // Recursive factorial program 9 | int factorial(int n) 10 | { 11 | if (n == 1) 12 | return 1; 13 | return n * factorial(n - 1); 14 | } -------------------------------------------------------------------------------- /makefile/function.h: -------------------------------------------------------------------------------- 1 | #ifndef FUNCTION_H 2 | #define FUNCTION_H 3 | 4 | void print(); 5 | int factorial(int); 6 | int multiply(int, int); 7 | 8 | #endif -------------------------------------------------------------------------------- /makefile/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | // Note function.h which has all functions 4 | // definitions has been included 5 | #include "function.h" 6 | 7 | using namespace std; 8 | 9 | // Main program 10 | int main() 11 | { 12 | int num1 = 1; 13 | int num2 = 2; 14 | cout << multiply(num1, num2) << endl; 15 | int num3 = 5; 16 | cout << factorial(num3) << endl; 17 | print(); 18 | } -------------------------------------------------------------------------------- /makefile/makefile: -------------------------------------------------------------------------------- 1 | # ----- do not Edit this will it will be cost problem ---- 2 | 3 | # Compiler 4 | CXX = g++ 5 | # Compiler flags 6 | CXXFLAGS = -Wall -g 7 | # Target executable 8 | TARGET = main 9 | # For deleting the target 10 | TARGET_DEL = main.exe 11 | 12 | # Source files 13 | SRCS = main.cpp print.cpp factorial.cpp multiply.cpp 14 | 15 | # Object files 16 | OBJS = $(SRCS:.cpp=.o) 17 | 18 | # Default rule to build and run the executable 19 | all: $(TARGET) run 20 | 21 | # Rule to link object files into the target executable 22 | $(TARGET): $(OBJS) 23 | $(CXX) $(CXXFLAGS) -o $(TARGET) $(OBJS) 24 | 25 | # Rule to compile .cpp files into .o files 26 | %.o: %.cpp 27 | $(CXX) $(CXXFLAGS) -c $< -o $@ 28 | 29 | # Rule to run the executable 30 | run: $(TARGET) 31 | $(TARGET) 32 | 33 | # Clean rule to remove generated files 34 | #clean: 35 | # del $(TARGET_DEL) $(OBJS) 36 | -------------------------------------------------------------------------------- /makefile/multiply.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | // Definition of multiply function 4 | // is present in function.h file 5 | #include "function.h" 6 | using namespace std; 7 | 8 | int multiply(int a, int b) { return a * b; } -------------------------------------------------------------------------------- /makefile/print.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | // Definition of print function is 4 | // present in function.h file 5 | #include "function.h" 6 | using namespace std; 7 | 8 | void print() { cout<<"makefile"< // Required for standard input/output functions like printf, scanf, fopen, fclose 2 | #include // Required for general utilities like exit, malloc, free 3 | #include // Required for string manipulation functions like strcmp 4 | 5 | // Function to display the content of a file 6 | void readFileContent(const char *filename) { 7 | FILE *file; // Declare a file pointer 8 | char ch; // Character to read from the file 9 | 10 | // Open the file in read mode ("r") 11 | file = fopen(filename, "r"); 12 | 13 | // Check if the file was opened successfully 14 | if (file == NULL) { 15 | printf("Error: Could not open file '%s' for reading.\n", filename); 16 | return; // Exit the function if file opening failed 17 | } 18 | 19 | printf("\n--- Content of '%s' ---\n", filename); 20 | // Read character by character until the end of the file (EOF) 21 | while ((ch = fgetc(file)) != EOF) { 22 | printf("%c", ch); // Print each character to the console 23 | } 24 | printf("\n--- End of file ---\n"); 25 | 26 | // Close the file 27 | fclose(file); 28 | } 29 | 30 | // Function to write content to a file (effectively 'Save' or 'Save As') 31 | void writeToFile(const char *filename) { 32 | FILE *file; // Declare a file pointer 33 | char content[1000]; // Buffer to store user input (max 999 characters + null terminator) 34 | 35 | // Open the file in write mode ("w"). 36 | // If the file exists, its content will be truncated (overwritten). 37 | // If the file does not exist, it will be created. 38 | file = fopen(filename, "w"); 39 | 40 | // Check if the file was opened successfully 41 | if (file == NULL) { 42 | printf("Error: Could not open file '%s' for writing.\n", filename); 43 | return; // Exit the function if file opening failed 44 | } 45 | 46 | printf("\nEnter content to write to '%s' (type 'END' on a new line to finish):\n", filename); 47 | printf("------------------------------------------------------------------\n"); 48 | 49 | // Read lines from standard input until "END" is entered 50 | while (fgets(content, sizeof(content), stdin) != NULL) { 51 | // Check if a newline was read. If not, it means the line was longer than the buffer. 52 | // In that case, we need to clear the rest of the input buffer to prevent issues with subsequent fgets calls. 53 | if (strchr(content, '\n') == NULL && strlen(content) == sizeof(content) - 1) { 54 | int c; 55 | while ((c = getchar()) != '\n' && c != EOF); // Consume remaining characters in the line 56 | } 57 | 58 | // Remove the newline character if present (fgets includes it) 59 | content[strcspn(content, "\n")] = 0; 60 | 61 | // Check if the user typed "END" to finish input 62 | if (strcmp(content, "END") == 0) { 63 | break; // Exit the loop 64 | } 65 | 66 | // Write the content to the file, followed by a newline for readability 67 | fprintf(file, "%s\n", content); 68 | } 69 | 70 | printf("------------------------------------------------------------------\n"); 71 | printf("Content successfully written to '%s'.\n", filename); 72 | 73 | // Close the file 74 | fclose(file); 75 | } 76 | 77 | // Main function where the program execution begins 78 | int main() { 79 | char filename[256]; // Buffer to store the filename (max 255 characters + null terminator) 80 | int choice; // Variable to store user's menu choice 81 | 82 | printf("Welcome to the C Console Notepad!\n"); 83 | 84 | while (1) { // Infinite loop for the menu 85 | printf("\n--- Menu ---\n"); 86 | printf("1. Read from a file\n"); 87 | printf("2. Write/Save to a file (creates/overwrites)\n"); // Updated menu option 88 | printf("3. Exit\n"); 89 | printf("Enter your choice: "); 90 | 91 | // Read user's choice 92 | if (scanf("%d", &choice) != 1) { 93 | printf("Invalid input. Please enter a number.\n"); 94 | // Clear the input buffer to prevent infinite loops on bad input 95 | while (getchar() != '\n'); 96 | continue; // Go back to the beginning of the loop 97 | } 98 | 99 | // Consume the newline character left by scanf 100 | while (getchar() != '\n'); 101 | 102 | switch (choice) { 103 | case 1: 104 | printf("Enter the filename to read from: "); 105 | // Read the filename from user input 106 | if (fgets(filename, sizeof(filename), stdin) != NULL) { 107 | // Remove the newline character from the filename 108 | filename[strcspn(filename, "\n")] = 0; 109 | readFileContent(filename); // Call the read function 110 | } 111 | break; 112 | case 2: 113 | printf("Enter the filename to write to: "); 114 | // Read the filename from user input 115 | if (fgets(filename, sizeof(filename), stdin) != NULL) { 116 | // Remove the newline character from the filename 117 | filename[strcspn(filename, "\n")] = 0; 118 | writeToFile(filename); // Call the write function 119 | } 120 | break; 121 | case 3: 122 | printf("Exiting C Console Notepad. Goodbye!\n"); 123 | exit(0); // Exit the program 124 | default: 125 | printf("Invalid choice. Please enter 1, 2, or 3.\n"); 126 | break; 127 | } 128 | } 129 | 130 | return 0; // Indicate successful program execution (though exit(0) handles this for case 3) 131 | } 132 | -------------------------------------------------------------------------------- /temp/Constructor/default-copy-move-destructor.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | class Person { 5 | public: 6 | std::string name; 7 | int age; 8 | 9 | // 1. Overloaded Constructor (Normal Constructor) 10 | // Used for creating new Person objects with initial values 11 | Person(const std::string _name, int _age) : name(_name), age(_age) { 12 | std::cout << " [NORMAL CTOR] Person created: " << name << ", " << age << std::endl; 13 | } 14 | // 2. Copy Constructor 15 | Person(const Person& other) : name(other.name), age(other.age) { 16 | std::cout << " [COPY CTOR] Person copied: " << other.name << ", " << other.age 17 | << " (new object's name: " << this->name << ")" << std::endl; 18 | } 19 | // 3. Move Constructor 20 | Person(const Person&& move) noexcept : name(move.name), age(move.age) { 21 | std::cout << " [MOVE CTOR] Person Move: " << move.name << ", " << move.age 22 | << " (new object's name: " << this->name << ")" << std::endl; 23 | } 24 | void greet() const { 25 | std::cout << "Hello, my name is " << name << " and I am " << age << " years old." << std::endl; 26 | } 27 | // Destructor 28 | ~Person() { 29 | std::cout << "All data Person Destroy. Deallocating " << std::endl; 30 | } 31 | }; 32 | 33 | // Function that returns a Person object by value 34 | // This is a common scenario where the Move Constructor might be invoked 35 | Person createPersonForMoving(const std::string& name, int age) { 36 | std::cout << "\n--- Inside createPersonForMoving function ---" << std::endl; 37 | // This creates a temporary Person object (an rvalue) 38 | return Person(name, age); 39 | } // The temporary Person object would typically be moved from here 40 | 41 | int main() { 42 | std::cout << "===== START OF MAIN =====" << std::endl; 43 | 44 | // Scenario 1: Direct Initialization - Normal Constructor called 45 | Person person1("Alice", 30); 46 | // Copy person1 to person2 47 | Person person2 = person1; 48 | Person Persontemp = createPersonForMoving("dump",25); 49 | std::cout << "--- Back in main after createPersonForMoving ---" << std::endl; 50 | Person personmove = std::move(Persontemp); 51 | 52 | std::cout << "\n===== END OF MAIN (Objects will be destructed) =====" << std::endl; 53 | return 0; 54 | } 55 | -------------------------------------------------------------------------------- /thread.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | void ThreadFunctions(int argm) { 6 | argm+1; 7 | cout<