public static string Encryptor(string plainText, string EncryptionKey)
{
byte[] clearBytes = Encoding.Unicode.GetBytes(plainText);
Aes encryptor = Aes.Create();
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
MemoryStream ms = new MemoryStream();
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(clearBytes, 0, clearBytes.Length);
cs.Close();
}
plainText = Convert.ToBase64String(ms.ToArray());
return plainText;
}
this is the code I use to make filenames safe but the problem is that sometimes characters such as / which is not acceptable for file creating and if I want to open it, System.IO.FileStream detects the part behind / as a folder which clearly doesn't exist.
I'm fairly new to Aes So what can I do to make sure / will not appear in the ciphered code?
Related
How do I set the UTF-8 encoding for reading string. example
// outData = "абцд" -> Cyrillic alphabet
QMessageBox::information(this,"title",outData,"ok");
void MainWindow::read() {
myProcess = new QProcess();
myProcess->start(QDir::currentPath() + "program.exe args args");
connect(myProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readOutput()));
}
void MainWindow::readOutput() {
QString outData = myProcess->readAllStandardOutput();
}
I'm using Windows Media Foundation WMV encoder on Win10 64bit. While it can be used to encode correctly, I failed to set VBR quality.
Below is the sample code
const PROPERTYKEY MFPKEY_VBRENABLED = { { 0xe48d9459, 0x6abe, 0x4eb5, { 0x92, 0x11, 0x60, 0x8, 0xc, 0x1a, 0xb9, 0x84 } }, 0x14 };
const PROPERTYKEY MFPKEY_DESIRED_VBRQUALITY = { { 0x6dbdf03b, 0xb05c, 0x4a03, { 0x8e, 0xc1, 0xbb, 0xe6, 0x3d, 0xb1, 0x0c, 0xb4 } }, 0x00 + 25 };
CLSID* pCLSIDs = NULL; // Pointer to an array of CLISDs. UINT32 nCount = 0;
MFT_REGISTER_TYPE_INFO encoderInfo; encoderInfo.guidMajorType = MFMediaType_Video;
encoderInfo.guidSubtype = MFVideoFormat_WMV3;
HRESULT hr = fpMFTEnum(MFT_CATEGORY_VIDEO_ENCODER, 0, NULL, &encoderInfo, NULL, &pCLSIDs, &nCount);
if (FAILED(hr) || (nCount == 0)) {} ciEncoder.CreateObject(pCLSIDs[0], IID_IMFTransform);
if (ciEncoder.IsInvalid()) {}
LComInterface<IPropertyStore> ciPropertyStore; // WMV Encoder codec setting interface
hr = ciEncoder->QueryInterface(IID_IPropertyStore, (void**)ciPropertyStore.GetAssignablePtrRef());
if (SUCCEEDED(hr)) {
PROPVARIANT propVal;
propVal.vt = VT_BOOL;
propVal.boolVal = VARIANT_TRUE;
hr = ciPropertyStore->SetValue(MFPKEY_VBRENABLED, propVal);
propVal.vt = VT_UI4;
propVal.ulVal = 90;
hr = ciPropertyStore->SetValue(MFPKEY_DESIRED_VBRQUALITY, propVal);
While ciPropertyStore->SetValue(MFPKEY_VBRENABLED, propVal) returns S_OK,
ciPropertyStore->SetValue(MFPKEY_DESIRED_VBRQUALITY, propVal) failed and hr = "The property ID does not match any property supported by the transform"
Thanks
I've just found the root cause: seems I should use MFPKEY_VBRQUALITY instead of MFPKEY_DESIRED_VBRQUALITY
in https://msdn.microsoft.com/en-us/library/windows/desktop/dd206749%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396 seems MFPKEY_VBRQUALITY is for video, MFPKEY_DESIRED_VBRQUALITY is for audio?
Is there a possibility to set the padding for encryption with AES128 in Poco Crypto? I can't find any option for this.
std::string Crypto::Encrypt(const std::string &input, const std::string &key)
{
Poco::Crypto::Cipher::ByteVec iv { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
Poco::Crypto::Cipher::ByteVec key2 {key.begin(), key.end()};
Poco::Crypto::Cipher::Ptr pCipher = Poco::Crypto::CipherFactory::defaultFactory()
.createCipher(Poco::Crypto::CipherKey("aes128", key2, iv));
std::string output = pCipher->encryptString(input);
return std::move(output);
}
In simple OpenSSL I have this option:
EVP_CIPHER_CTX *ctx;
EVP_CIPHER_CTX_set_padding(ctx, 0)
By default padding is enabled.
From comment in Crypto/include/Poco/Crypto/CryptoTransform.h or https://pocoproject.org/docs/Poco.Crypto.CryptoTransform.html#230, encryption operations are padded by default.
...
virtual int setPadding(int padding);
/// Enables or disables padding. By default encryption operations are padded using standard block
/// padding and the padding is checked and removed when decrypting. If the padding parameter is zero then
/// no padding is performed, the total amount of data encrypted or decrypted must then be a multiple of
/// the block size or an error will occur.
...
If you want to change padding option, you should override createEncryptor(), creatoreDecryptor() in Poco::Crypto::Cipher like below
class CipherWithPadding : public Poco::Crypto::Cipher
{
public:
// by default no padding, for more information refer to CryptoTransform::setPadding
CipherWithPadding(Poco::Crypto::Cipher::Ptr cipher_impl, int padding = 0)
: cipher_(cipher_impl)
, padding_(padding)
{
}
virtual ~CipherWithPadding()
{
}
virtual const std::string& name() const
{
return cipher_->name();
}
virtual Poco::Crypto::CryptoTransform* createEncryptor() override
{
auto ptransform = cipher_->createEncryptor();
if (ptransform)
ptransform->setPadding(padding_);
return ptransform;
}
virtual Poco::Crypto::CryptoTransform* createDecryptor() override
{
auto ptransform = cipher_->createDecryptor();
if (ptransform)
ptransform->setPadding(padding_);
return ptransform;
}
protected:
int padding_;
Poco::Crypto::Cipher::Ptr cipher_;
protected:
CipherWithPadding();
private:
CipherWithPadding(const CipherWithPadding&);
CipherWithPadding& operator= (const CipherWithPadding&);
};
Then your function should be like below
std::string Crypto::Encrypt(const std::string &input, const std::string &key)
{
Poco::Crypto::Cipher::ByteVec iv { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
Poco::Crypto::Cipher::ByteVec key2 {key.begin(), key.end()};
CipherWithPadding cipher(Poco::Crypto::CipherFactory::defaultFactory()
.createCipher(Poco::Crypto::CipherKey("aes128", key2, iv)));
std::string output = cipher.encryptString(input);
return std::move(output);
}
I have the following code:
#define PRIVATE_KEY "729308A8E815F6A46EB3A8AE6D5463CA7B64A0E2E11BC26A68106FC7697E727E37011"
To Encrypt:
QString Encryption::AESEncrypt(const QString &data)
{
string plain = data.toStdString();
string ciphertext;
// Hex decode symmetric key:
HexDecoder decoder;
decoder.Put( (byte *)PRIVATE_KEY, 32*2 );
decoder.MessageEnd();
word64 size = decoder.MaxRetrievable();
char *decodedKey = new char[size];
decoder.Get((byte *)decodedKey, size);
// Generate Cipher, Key, and CBC
byte key[ AES::MAX_KEYLENGTH ];
byte iv[ AES::BLOCKSIZE ];
StringSource( reinterpret_cast<const char *>(decodedKey), true,
new HashFilter(*(new SHA256), new ArraySink(key, AES::MAX_KEYLENGTH)) );
memset( iv, 0x00, AES::BLOCKSIZE );
CBC_Mode<AES>::Encryption Encryptor( key, sizeof(key), iv );
StringSource( plain, true, new StreamTransformationFilter( Encryptor,
new HexEncoder(new StringSink( ciphertext ) ) ) );
return QString::fromStdString(ciphertext);
}
To Decrypt:
QString Encryption::AESDecrypt(const QString &data)
{
string plain;
string encrypted = data.toStdString();
// Hex decode symmetric key:
HexDecoder decoder;
decoder.Put( (byte *)PRIVATE_KEY,32*2 );
decoder.MessageEnd();
word64 size = decoder.MaxRetrievable();
char *decodedKey = new char[size];
decoder.Get((byte *)decodedKey, size);
// Generate Cipher, Key, and CBC
byte key[ AES::MAX_KEYLENGTH ];
byte iv[ AES::BLOCKSIZE ];
StringSource( reinterpret_cast<const char *>(decodedKey), true,
new HashFilter(*(new SHA256), new ArraySink(key, AES::MAX_KEYLENGTH)) );
memset( iv, 0x00, AES::BLOCKSIZE );
try
{
CBC_Mode<AES>::Decryption Decryptor( key, sizeof(key), iv );
StringSource( encrypted, true,
new HexDecoder(new StreamTransformationFilter( Decryptor,
new StringSink( plain ) ) ) );
}
catch (Exception &e) { // ...
}
catch (...) { // ...
}
return QString::fromStdString(plain);
}
If I run the following:
Encryption encrypt;
QString encdata = encrypt.AESEncrypt("This is my data");
qDebug() << "encrypt: " << encdata;
qDebug() << "decrypt" << encrypt.AESDecrypt(encdata);
I get the following output:
encrypt: "4E712EFDE13DA42FF798C193D17BE5D2"
decrypt ""
So I'm not sure why its not decrypting properly. I took the code from the following conversation. The code is failing on the second StringSource on decrypt and landing on the first Exception. Any ideas on what am I doing wrong?
I was getting a PKCS#7 padding error with the provided code. The code I used was modified to remove the Qt stuff and remove the function calls, so I'm not sure if I accidentally added/removed an error.
I was able to fix the padding issue by modifying the encoding/decoding of the key. I think the problem was here:
StringSource( reinterpret_cast<const char *>(decodedKey), true,
new HashFilter(*(new SHA256), new ArraySink(key, AES::MAX_KEYLENGTH)) );
In the code above, there was no guarantee decodedKey was NULL terminated. The fix was easy - store it in a string and then use length().
The key you listed is 35 bytes in length (after decoding).
#define COUNTOF(x) (sizeof(x)/sizeof(x[0]))
#define PRIVATE_KEY "729308A8E815F6A46EB3A8AE6D5463CA7B64A0E2E11BC26A68106FC7697E727E37011"
string plain1 = "Now is the time for all good men...";
string decoded1, cipher1;
// Hex decode symmetric key:
StringSource ss1((const byte*)PRIVATE_KEY, COUNTOF(PRIVATE_KEY), true,
new HexDecoder(new StringSink(decoded1)));
// Generate Cipher, Key, and CBC
byte key1[ AES::MAX_KEYLENGTH ];
byte iv1[ AES::BLOCKSIZE ];
SHA256 sha1;
StringSource ss2( decoded1, true,
new HashFilter(sha1, new ArraySink(key1, sizeof(key1))) );
memset( iv1, 0x00, AES::BLOCKSIZE );
CBC_Mode<AES>::Encryption encryptor( key1, sizeof(key1), iv1 );
StringSource ss3( plain1, true, new StreamTransformationFilter( encryptor,
new HexEncoder(new StringSink( cipher1 ) ) ) );
string plain2, decoded2;
string cipher2 = cipher1;
// Hex decode symmetric key:
StringSource ss4((const byte*)PRIVATE_KEY, COUNTOF(PRIVATE_KEY), true,
new HexDecoder(new StringSink(decoded2)));
// Generate Cipher, Key, and CBC
byte key2[ AES::MAX_KEYLENGTH ];
byte iv2[ AES::BLOCKSIZE ];
SHA256 sha2;
StringSource ss5( decoded2, true,
new HashFilter(sha2, new ArraySink(key2, sizeof(key2))) );
memset( iv2, 0x00, AES::BLOCKSIZE );
CBC_Mode<AES>::Decryption decryptor( key2, sizeof(key2), iv2 );
StringSource ss6( cipher2, true,
new HexDecoder(new StreamTransformationFilter( decryptor,
new StringSink( plain2 ) ) ) );
cout << "Plain 1: " << plain1 << endl;
cout << "Cipher: " << cipher1 << endl;
cout << "Plain 2: " << plain2 << endl;
Output from those three cout's is:
Plain 1: Now is the time for all good men...
Cipher: 3073448F4A71BC26CF81441F1DEE69C5DE700DF86294181B5E72E19D260DDF1E725DB3EFC74415982FFF45F9F7E290AE
Plain 2: Now is the time for all good men...
I have an sqlite database and it's loaded into a tableview, now when i click a row to see its details..i go to another view controller in which details are displayed and a AddToFav button exists.
When i click it..and go to another view controller...i can see the changes correctly, my database is updating correctly, but if i try to add another entry..i notice that my database is not updated anymore..The addToFav button only updates the database once. Any ideas?
This is my Addbut IBaction :
- (IBAction)AddButClick:(UIButton *)sender {
[AddBut setImage:[UIImage imageNamed:#"apple-logo copy.png"] forState:UIControlStateSelected];
[AddBut setImage:[UIImage imageNamed:#"apple-logo copy.png"] forState:UIControlStateHighlighted];
Favo = [[NSMutableArray alloc] initWithCapacity:1000000];
#try {
// NSFileManager *fileMgr = [NSFileManager defaultManager];
// NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"dictionary.sqlite"];
//NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"authorsDb2.sqlite"];
// NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"FinalDb.sqlite"];
//NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"xxJuridique-FINAL-OK.sqlite"];
// [self createEditableCopyOfDatabaseIfNeeded];
// NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"data.sqlite"];
// [self.tableView reloadData];
sqlite3_stmt *compiled_statement1;
if(sqlite3_open([PathDB UTF8String], &db) == SQLITE_OK) {
// UIAlertView *DbO = [[UIAlertView alloc]
// initWithTitle:#"PATH" message:#"Database still open !" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
//
// [DbO show];
NSString *formatedSql = [NSString stringWithFormat:#"UPDATE Sheet1 SET Fav = 'YES' WHERE field3 = '%#'" , authorNAme2];
// UIAlertView *messageAlert = [[UIAlertView alloc]
// initWithTitle:#"Query" message:formatedSql delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
//
// [messageAlert show];
//
UIAlertView *PAth = [[UIAlertView alloc]
initWithTitle:#"PATH" message:PathDB delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[PAth show];
// NSLog(PathDB);
const char *sql = [formatedSql UTF8String];
NSLog(#" !!!!!!!! In the middle of it !!!!!!!!!!!!");
if (sqlite3_prepare_v2(db, sql, -1, &compiled_statement1, NULL) != SQLITE_OK) {
NSLog(#"!!!!!!!!!!!!!!!!!!!ERRRRROOOOOOORRRRRRRRR!!!!!!!!!!!!!!!!!!!!!!!!!");
//NSAssert1(0, #"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(database));
}
NSLog(#"This is the query %#",formatedSql);
}
// sqlite3_bind_text(compiled_statement1, 1, [authorNAme2 UTF8String], -1, SQLITE_TRANSIENT);
int success = sqlite3_step(compiled_statement1);
// sqlite3_reset(compiled_statement1);
if (success != SQLITE_ERROR) {
NSLog(#"Successfully inserted");
sqlite3_last_insert_rowid(db);
}
//
// BOOL success = [fileMgr fileExistsAtPath:dbPath];
//
// if(!success)
// {
// NSLog(#"Cannot locate database file '%#'.", dbPath);
// }
// if(!(sqlite3_open([dbPath UTF8String], &db) == SQLITE_OK))
// {
// NSLog(#"An error has occured: %#", sqlite3_errmsg(db));
//
// }
// const char *sql = "SELECT F_Keyword FROM wordss";
const char *sql = "SELECT * FROM Sheet1";
NSLog(#"Successfully selected from database");
sqlite3_stmt *sqlStatement;
if(sqlite3_prepare(db, sql, -1, &sqlStatement, NULL) != SQLITE_OK)
{
NSLog(#"Problem with prepare statement: %#", sqlite3_errmsg(db));
}else{
NSLog(#"Got in the else tag");
while (sqlite3_step(sqlStatement)==SQLITE_ROW /*&& PAss == NO*/) {
NSLog(#"Got in the while tag");
Author * author = [[Author alloc] init];
NSLog(#"Author initialized");
author.name = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,10)];
NSLog(#"Initialization ok");
// NSLog(author.name);
if(/*author.name == #"NO" &&*/ HighLighted == NO){
//const char *sql2 = "INSERT INTO Sheet1 ";
[AddBut setImage:[UIImage imageNamed:#"apple-logo copy.png"] forState:UIControlStateNormal];
NSLog(#"We have not selected it as fav yet");
// [AddBut setSelected:NO]; //btn changes to normal state
NSLog(#"The button was NOt highlighted and now is");
HighLighted = YES;
break;
}
else
{
NSLog(#"We have selected it as fav");
[AddBut setImage:[UIImage imageNamed:#"apple-logo.png"] forState:UIControlStateNormal];
[AddBut setSelected:NO]; //btn changes to normal state
NSLog(#"The button was highlighted and now is NOt");
HighLighted = NO;
break;
// [self viewDidLoad];
// PAss = YES;
}
// [Favo release];
// NSLog(Favo);
// author.name = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,2)];
// author.title = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,2)];
// author.genre = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 4)];
// [theauthors addObject:author];
}
}
}
#catch (NSException *exception) {
NSLog(#"Problem with prepare statement: %#", sqlite3_errmsg(db));
}
#finally {
// sqlite3_finalize(sqlStatement);
// sqlite3_close(db);
UIAlertView *fin = [[UIAlertView alloc]
initWithTitle:#"Query" message:#"DOne with Click Button" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[fin show];
return Favo;
}
Thank you #crazyCreator for your answer !!!!
[self authorList2];
[self.tableView reloadData];