Crypto++ AES Decrypt how to? - cryptography

There are next to no noob guides to crypto++ out there. Or none that I've found anyway. What I want to do is decrypt an array of uchars I generate with another AES encrypter. Where would I start? I have the library built and linking grand. Do I need to set anything up or do I just call a function on my array (and if so what function) ?
I'd really appreshiate some help from someone who knows this stuff.
Thanks

I wouldn't say I "know my stuff" too much about this, but here's some test code I put together to encrypt/decrypt strings with AES. Extending this to use some other data shouldn't be too hard.
string output;
CTR_Mode<AES>::Encryption encrypt((const byte*)key,AES::DEFAULT_KEYLENGTH,(const byte*)iv);
StringSource(plaintext, true, new StreamTransformationFilter(encrypt, new StringSink(output)));
cout << "Encrypted: " << output << endl;
string res;
CTR_Mode<AES>::Decryption decrypt((const byte*)key,AES::DEFAULT_KEYLENGTH,(const byte*)iv);
StringSource(output, true, new StreamTransformationFilter(decrypt, new StringSink(res)));
cout << "Decrypted: " << res << endl;
While working on this, I found the source code in the Crypto++ test program (the VisualStudio project called "cryptest") to be a big help. It was a little tough to read at first, but it gets easier as you work with it. I also got a lot of help understanding the available block cipher modes from Wikipedia (http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation).

Here's a couple of resources from a Google search:
http://www.bitvise.com/users-guide.html
http://andreyvit.livejournal.com/37576.html

Related

reading signs in an equation

Using this https://github.com/antlr/grammars-v4/tree/master/cpp antlr grammar Im trying to parse C++ code. Below is the same visitor class I'm using, I don't have much visitor function implemented,
#include <iostream>
#include <antlr4-runtime.h>
#include "parser/CPP14Lexer.h"
#include "parser/CPP14BaseVisitor.h"
#include "parser/CPP14Parser.h"
#include "parser/CPP14Visitor.h"
class TREEVisitor : public CPP14BaseVisitor {
public:
virtual antlrcpp::Any TREEVisitor::visitAdditiveExpression(
CPP14Parser::AdditiveExpressionContext *ctx) override
{
std::cout << "AddExpr : " << ctx->getText() << std::endl;
std::vector<CPP14Parser::MultiplicativeExpressionContext *> mulpExprCtx =
ctx->multiplicativeExpression();
for (CPP14Parser::MultiplicativeExpressionContext *mulpExprLp : mulpExprCtx)
{
std::vector<CPP14Parser::PointerMemberExpressionContext *> ptrMbrExprCtx =
mulpExprLp->pointerMemberExpression();
// ptrMbrExprCtx->pointerMemberExpression()->castExpression()->unaryExpression();
// Different parts of an expression
for (CPP14Parser::PointerMemberExpressionContext *ptrMbrExprLp : ptrMbrExprCtx)
{
std::cout << "=> " << ptrMbrExprLp->getText() << std::endl;
}
}
return visitChildren(ctx);
}
};
int main(int argc, char *argv[]) {
std::ifstream stream;
stream.open(argv[1]);
antlr4::ANTLRInputStream input(stream);
CPP14Lexer lexer(&input);
antlr4::CommonTokenStream tokens(&lexer);
CPP14Parser parser(&tokens);
antlr4::tree::ParseTree *tree = parser.translationunit();
// Visitor
auto *visitor = new TREEVisitor();
visitor->visit(tree);
return 0;
}
Im trying to parse the following C++ code,
int ii = a + b - getLength() * 10 / 1;
What I'm trying to achieve here is to get all of the variables that are used to initilize the variable i and their signs. Something like below, where i can relate each sign to the values/variables(for example to know that + as after a.
a
+
b
-
getLength()
*
10
/
1;
So far I can only get an output as follow,
AddExpr : a+b-c*10/1
=> a
=> b
=> getLength()
=> 10
=> 1
I don't seem to be able to get the signs between each operation.
I seem to have something related to the signs in that equation, I had only Star and Mod.
tree::TerminalNode* startTn = mulpExprLp->Star();
So I tried to change the grammar file to get other signs as well. While that gave me the signs in that equation but again... I wasn't ablel to know the position of each sign in the equation.
multiplicativeExpression:
pointerMemberExpression (
(Star | Div | Mod | Plus | Minus) pointerMemberExpression
)*;
I hope I could describe the problem clearly. I basically want to read the each part of an equation and know what is the position of each sign.
Thanks,
Alex
It looks like you need a better understanding of the structure of your parse tree.
I would suggest going back to the original grammar (there are many problems with your multiplcativeExpression, mostly around it not building a proper parse tree.
Viewing the graphical version of your parse tree should be quite useful. This page gives a brief intro to setting up a grun alias to use TestRig. It’s usually a good idea to “play around” a bit with grun and various input to gain a better understanding of what ANTLR produces (token streams, parse trees, etc.) for your grammar.
Take a look at the documentation and how to run the TestRig utility with the -gui command line option. This will give you a graphical representation of your parse tree. Your immediate issue is that, since you only have a visitor for additiveExpression, it won’t include the sub tree for the mutiplicativeExpression that will hold the structure for multiplication and division.
Also, since you’re not finding the operations you need to take a closer look at the cpp14parser::AdditiveExpressionContext generated for your additiveExpression. The operator(s) should be available at one of the indices of your children nodes (the rule is written to allow multiple addition/subtraction in a single context, so they’ll probably be available in some list/array structure (sorry, not intimately familiar with what ANTLR generates for C++)
BTW, you may find that, for your purposes, a listener is easier to use than a visitor. With Listeners a ParseTreeWalker takes care of walking the tree and calling back to your code as nodes are encountered. With Visitors, it’s up to you to navigate the parse Tree (they can be useful when you need more flexibility, and a bit easier to handle things if you want a value returned from visiting a node, but I find Listeners much simpler for most use cases)

C++ Program that adds positive odd numbers from keyboard, ignores even and stops when negative number or zero are entered - sum odd numbers

So technically I have done what the assignment says because this works:
#include <iostream>
using namespace std;
int main()
{
int number = 0;
int sum = 0;
cout << "Please enter an odd positive integer: " << endl;
cout << "This program will end if number is <= 0 or decimal" << endl;
cin >> number;
while (number > 0)
{
if (number % 2 != 0)
sum = sum + number;
else
cout << "That number was even - please enter odd number \n";
cin >> number;
}
cout << "Sum of odd numbers = " << sum << endl;
return 0;
}
However - it dawned on me that the program quits when someone enters a double or enters a character, rather than just warning that this will happen - I would love to write this in. I have tried using else if statements and I am not getting the desired results. I am not asking for someone to solve this for me per se but if I could just get sent in the right direction. We are currently working on while and for loops and increments (which don't seem to apply here at all)
First off, you'd have to change your number variable to a string to take in "anything", deal with garbage input, and finally convert it to an int if it fit your requirements. This usually isn't too hard, but can get tricky at times. Google is usually your friend here. It's bee a while since I did C++, so I'd have to consult it, too, to get things correct.
And when you say "double", is that the number is 2 digits or is too long to be an int? That little bit of ambiguity is throwing me off. If it's just too big a number being an actual double datatype, the string should help with that, as would a problem a 2 digit number.
And for an increment being useful, you could use sum += number;, depending on your version of C++. Older versions don't allow that, but newer versions do. I'd be surprised of a gcc or other compiler wasn't new enough to have it available, at this point.
Side note
Thank you for not being the "typical homework question". It's good that you are just asking for advice, not for someone to write your code for you.
While I've got you, you should think about reading the How To Ask A Question and Tour pages. The Tour gets you another badge, and the other is just good advice to keep people from downvoting or closing your future questions. You already have a good idea on how to ask a homework question, but reading that page is a good idea, too.
But I digress.
Good luck and I hope I put you on the right path.

How to read byte data from a StorageFile in cppwinrt?

A 2012 answer at StackOverflow (“How do I read a binary file in a Windows Store app”) suggests this method of reading byte data from a StorageFile in a Windows Store app:
IBuffer buffer = await FileIO.ReadBufferAsync(theStorageFile);
byte[] bytes = buffer.ToArray();
That looks simple enough. As I am working in cppwinrt I have translated that to the following, within the same IAsyncAction that produced a vector of StorageFiles. First I obtain a StorageFile from the VectorView using theFilesVector.GetAt(index);
//Then this line compiles without error:
IBuffer buffer = co_await FileIO::ReadBufferAsync(theStorageFile);
//But I can’t find a way to make the buffer call work.
byte[] bytes = buffer.ToArray();
“byte[]” can’t work, to begin with, so I change that to byte*, but then
the error is “class ‘winrt::Windows::Storage::Streams::IBuffer’ has no member ‘ToArray’”
And indeed Intellisense lists no such member for IBuffer. Yet IBuffer was specified as the return type for ReadBufferAsync. It appears the above sample code cannot function as it stands.
In the documentation for FileIO I find it recommended to use DataReader to read from the buffer, which in cppwinrt should look like
DataReader dataReader = DataReader::FromBuffer(buffer);
That compiles. It should then be possible to read bytes with the following DataReader method, which is fortunately supplied in the UWP docs in cppwinrt form:
void ReadBytes(Byte[] value) const;
However, that does not compile because the type Byte is not recognized in cppwinrt. If I create a byte array instead:
byte* fileBytes = new byte(buffer.Length());
that is not accepted. The error is
‘No suitable constructor exists to convert from “byte*” to “winrt::arrayView::<uint8_t>”’
uint8_t is of course a byte, so let’s try
uint8_t fileBytes = new uint8_t(buffer.Length());
That is wrong - clearly we really need to create a winrt::array_view. Yet a 2015 Reddit post says that array_view “died” and I’m not sure how to declare one, or if it will help. That original one-line method for reading bytes from a buffer is looking so beautiful in retrospect. This is a long post, but can anyone suggest the best current method for simply reading raw bytes from a StorageFile reference in cppwinrt? It would be so fine if there were simply GetFileBytes() and GetFileBytesAsync() methods on StorageFile.
---Update: here's a step forward. I found a comment from Kenny Kerr last year explaining that array_view should not be declared directly, but that std::vector or std::array can be used instead. And that is accepted as an argument for the ReadBytes method of DataReader:
std::vector<unsigned char>fileBytes;
dataReader.ReadBytes(fileBytes);
Only trouble now is that the std::vector is receiving no bytes, even though the size of the referenced file is correctly returned in buffer.Length() as 167,513 bytes. That seems to suggest the buffer is good, so I'm not sure why the ReadBytes method applied to that buffer would produce no data.
Update #2: Kenny suggests reserving space in the vector, which is something I had tried, this way:
m_file_bytes.reserve(buffer.Length());
But it didn't make a difference. Here is a sample of the code as it now stands, using DataReader.
buffer = co_await FileIO::ReadBufferAsync(nextFile);
dataReader = DataReader::FromBuffer(buffer);
//The following line may be needed, but crashes
//co_await dataReader.LoadAsync(buffer.Length());
if (buffer.Length())
{
m_file_bytes.reserve(buffer.Length());
dataReader.ReadBytes(m_file_bytes);
}
The crash, btw, is
throw hresult_error(result, hresult_error::from_abi);
Is it confirmed, then, that the original 2012 solution quoted above cannot work in today's world? But of course there must be some way to read bytes from a file, so I'm just missing something that may be obvious to another.
Final (I think) update: Kenny's suggestion that the vector needs a size has hit the mark. If the vector is first prepared with m_file_bytes.assign(buffer.Length(),0) then it does get filled with file data. Now my only worry is that I don't really understand the way IAsyncAction is working and maybe could have trouble looping this asynchronously, but we'll see.
The array_view bridges the gap between Windows APIs and C++ array types. In this example, the ReadBytes method expects the caller to provide some array that it can copy bytes into. The array_view forwards a pointer to the caller's array as well as its size. In this case, you're passing an empty vector. Try resizing the vector before calling ReadBytes.
When you know how many bytes to expect (in this case 2 bytes), this worked for me:
std::vector<unsigned char>fileBytes;
fileBytes.resize(2);
DataReader reader = DataReader::FromBuffer(buffer);
reader.ReadBytes(fileBytes);
cout<< fileBytes[0] << endl;
cout<< fileBytes[1] << endl;

CGAL: Access to Results of find_conflicts()

So I am very confused about the find_conflicts function in CGAL. I thought I knew std::pair, and I thought I knew what was going on in find_conflicts(), but for the life of me, I am not sure how to access the results. I thought that the iterator that is passed to find_conflicts would be enough to then access the values directly. (i.e., I want to get at those facets that I put in the "vector facets,") and it appears as if I'm doing that because I can successfully
typedef std::pair<std::vector<Facet>, std::vector<Cell> > FacetAndCell;
* * *
Cell_handle cell = T.locate(curr_point);
std::vector<Facet> facets;
T.find_conflicts(curr_point, cell, std::back_inserter(facets), CGAL::Emptyset_iterator());
CGAL::First_of_pair_property_map<FacetAndCell> my_p_map();
Delaunay::Finite_facets_iterator ff_iter;
std::vector<Facet>::iterator facet_iter;
// Here, what I'm trying to achieve is figuring out which of the facets
// in conflict are finite. I had wanted to use some kind of test like
// "is_infinite()" on the facet at hand, but this isn't available for
// a facet out of context of the triangulation it's part of.
for(facet_iter = facets.begin(); facet_iter != facets.end(); facet_iter++){
for(ff_iter = T.finite_facets_begin(); ff_iter != T.finite_facets_end(); ff_iter++){
// Since I get an error that facet_iter is actually of type pair, I thought this would work, but it doesn't.
// ERROR!
cout << facet_iter->first << endl;
// This works, which is what led me to believe I was comparing one facet to another facet.
/*
if(*facet_iter == *ff_iter){
cout << "Finite facet!" << endl;
break;
}*/
}
}
In summary:
1) Overall, I want to know which facets from the result of find_conflicts() were finite. If there is an easier way to do this, feel free to let me know.
2) Otherwise, the more specific problem here is that I need to get at that vector of facets that results from find_conflicts() and then get at the vertices of each facet. Am I supposed to be working with the returned "pair" of cells and facets or can I access the vector directly, like I'm trying to do?
Help, please, thanks.
For finiteness testing, use is_infinite(). See http://doc.cgal.org/latest/Triangulation_3/classCGAL_1_1Triangulation__3.html#af024721d3ae4b9327ffe442fb828935c
Otherwise, maybe you are confused because the Facet type is a typedef to a pair (unfortunately).
PS: alternatively, you can use Marc Glisse's suggestion in your other question (using locate(midpoint(p, sphere center))). It might be easier. CGAL Using Locate() to Find Cell on Triangulation Surface

Char not being saved to file correctly

I want to save the contents of a ComboBox to a file. The code below correctly shows a MessageBox with "Marker 4" (the text in the ComboBox), but the saved file contains "03038D8C" instead of "Marker 4", I guess this is the memory address of the variable or something similar? How can I correctly output the "Marker 4"-string to the file?
private: System::Windows::Forms::ComboBox^ cmbMarker;
private: System::String^ strMarkerText;
...
strMarkerText = this->cmbMarker->Text;
...
ofstream myfile;
WIN32_FIND_DATA data;
pin_ptr<const wchar_t> wname = PtrToStringChars(strMarkerText);
FindFirstFile(wname, &data);
::MessageBox(0, wname, L"Marker inserted", MB_OK);
myfile <<"=====MARKER '" << wname << "' INSERTED AT " << datetime << " =====" << endl;
[There may be more than this wrong with this snippet, I'm not from a C++/CLI background but appreciate your help! There are no compiler errors and the code runs fine except for the issue described above, i.e. that not the cleartext-string-contents are written to the file ("Marker 4"), but "03038D8C".]
Thanks,
Nick
The problem is that you're using a narrow stream with a wide string. Use std::wofstream instead of std::ofstream and it should work fine.
That being said, I agree with #jonsca -- why drag iostreams into a C++/CLI app?
I'm not sure of your application's requirements, but have you considered using the .NET "equivalents" of the functions, like System::IO::Directory methods (specifically GetFiles in place of FindFirstFile), and the System::IO::StreamWriter in place of the ofstream object? This way the code in this section jives with the CLR portion of your code.
I know that's not precisely what you were asking for, but I have a feeling that the pointer in your code might need to be handled differently, and I'm unsure if would have to be marshaled across the managed/unmanaged barrier.
I ended up converting the System::String^ to a std:str and directly inserted this (rather than converting it to a wchar_t).
The mix between native c++ and CLI is because I'm building on a SDK-example built in native c++, but wanted to add a form to it (in Visual Studio 2008), which turned it into this "mix". I realize that that's not optimal, but so far, it seems to work :-)! I'll try to only use CLI-equivalents if I run into any more errors going forward. Thanks for your help!