Skip navigation

Monthly Archives: April 2013

Advertisements

I created an xml file with my newest XCode C++ theme.

It looks like this:

So, gray background, white text, all numeric constants and defines are kinda blue, classes are purple, and C preprocessor macros are red.

The factory pattern is most useful when an object type cannot and should not be used independently of some master managing class.

An analogy would be if you have a Theater as the "Master class" (factory) and the objects that are created in the factory are Tickets. So you have to ask the Master Theater class for a new Ticket() whenever you want one. The Master class can now remember that it has sold you a Ticket and that there is one additional Ticket in the system. Tickets aren’t useful at all if the ticket issuer disappeared. Notice this is much better than having a system where Tickets are created with no reference to a Theater, but then are registered to a theater after creation. That would be like "counterfeit your ticket, then call us and tell us you have a ticket to our Theater".

And so the factory pattern makes perfect sense here.

Objects make the most sense in the context of encapsulating code that:

  • Has some mandatory startup that must run (constructors), otherwise the related functions won’t work
  • Has a family of related functions, but not all of them should be called by the class user (private)
  • Has some cleanup routines that should be called when the user is done (destructor)

An example of this is my SecKeyHelper.h file I wrote today. That file is just C functions, but there is some code that must be called before any of the related functions work. On top of that, only 2 functions should really be called by the class user.

Public key loading, private key loading, it’s all very easy with OpenSSL on Linux. You must link the libcrypto.dylib library in XCode for this to work.

XCode 4.6 project download here

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <openssl/rsa.h>
#include <openssl/engine.h>
#include <openssl/pem.h>
 
// I'm not using BIO for base64 encoding/decoding.  It is difficult to use.
// Using superwills' Nibble And A Half instead 
// https://github.com/superwills/NibbleAndAHalf/blob/master/NibbleAndAHalf/base64.h
#include "base64.h"
 
// The PADDING parameter means RSA will pad your data for you
// if it is not exactly the right size
//#define PADDING RSA_PKCS1_OAEP_PADDING
#define PADDING RSA_PKCS1_PADDING
//#define PADDING RSA_NO_PADDING
 
RSA* loadPUBLICKeyFromString( const char* publicKeyStr )
{
  // A BIO is an I/O abstraction (Byte I/O?)
  
  // BIO_new_mem_buf: Create a read-only bio buf with data
  // in string passed. -1 means string is null terminated,
  // so BIO_new_mem_buf can find the dataLen itself.
  // Since BIO_new_mem_buf will be READ ONLY, it's fine that publicKeyStr is const.
  BIO* bio = BIO_new_mem_buf( (void*)publicKeyStr, -1 ) ; // -1: assume string is null terminated
  
  BIO_set_flags( bio, BIO_FLAGS_BASE64_NO_NL ) ; // NO NL
  
  // Load the RSA key from the BIO
  RSA* rsaPubKey = PEM_read_bio_RSA_PUBKEY( bio, NULL, NULL, NULL ) ;
  if( !rsaPubKey )
    printf( "ERROR: Could not load PUBLIC KEY!  PEM_read_bio_RSA_PUBKEY FAILED: %s\n", ERR_error_string( ERR_get_error(), NULL ) ) ;
  
  BIO_free( bio ) ;
  return rsaPubKey ;
}
 
RSA* loadPRIVATEKeyFromString( const char* privateKeyStr )
{
  BIO *bio = BIO_new_mem_buf( (void*)privateKeyStr, -1 );
  //BIO_set_flags( bio, BIO_FLAGS_BASE64_NO_NL ) ; // NO NL
  RSA* rsaPrivKey = PEM_read_bio_RSAPrivateKey( bio, NULL, NULL, NULL ) ;
  
  if ( !rsaPrivKey )
    printf("ERROR: Could not load PRIVATE KEY!  PEM_read_bio_RSAPrivateKey FAILED: %s\n", ERR_error_string(ERR_get_error(), NULL));
  
  BIO_free( bio ) ;
  return rsaPrivKey ;
}
 
unsigned char* rsaEncrypt( RSA *pubKey, const unsigned char* str, int dataSize, int *resultLen )
{
  int rsaLen = RSA_size( pubKey ) ;
  unsigned char* ed = (unsigned char*)malloc( rsaLen ) ;
  
  // RSA_public_encrypt() returns the size of the encrypted data
  // (i.e., RSA_size(rsa)). RSA_private_decrypt() 
  // returns the size of the recovered plaintext.
  *resultLen = RSA_public_encrypt( dataSize, (const unsigned char*)str, ed, pubKey, PADDING ) ; 
  if( *resultLen == -1 )
    printf("ERROR: RSA_public_encrypt: %s\n", ERR_error_string(ERR_get_error(), NULL));
 
  return ed ;
}
 
unsigned char* rsaDecrypt( RSA *privKey, const unsigned char* encryptedData, int *resultLen )
{
  int rsaLen = RSA_size( privKey ) ; // That's how many bytes the decrypted data would be
  
  unsigned char *decryptedBin = (unsigned char*)malloc( rsaLen ) ;
  *resultLen = RSA_private_decrypt( RSA_size(privKey), encryptedData, decryptedBin, privKey, PADDING ) ;
  if( *resultLen == -1 )
    printf( "ERROR: RSA_private_decrypt: %s\n", ERR_error_string(ERR_get_error(), NULL) ) ;
    
  return decryptedBin ;
}
 
unsigned char* makeAlphaString( int dataSize )
{
  unsigned char* s = (unsigned char*) malloc( dataSize ) ;
  
  int i;
  for( i = 0 ; i < dataSize ; i++ )
    s[i] = 65 + i ;
  s[i-1]=0;//NULL TERMINATOR ;)
  
  return s ;
}
 
// You may need to encrypt several blocks of binary data (each has a maximum size
// limited by pubKey).  You shoudn't try to encrypt more than
// RSA_LEN( pubKey ) bytes into some packet.
// returns base64( rsa encrypt( <<binary data>> ) )
// base64OfRsaEncrypted()
// base64StringOfRSAEncrypted
// rsaEncryptThenBase64
char* rsaEncryptThenBase64( RSA *pubKey, unsigned char* binaryData, int binaryDataLen, int *outLen )
{
  int encryptedDataLen ;
  
  // RSA encryption with public key
  unsigned char* encrypted = rsaEncrypt( pubKey, binaryData, binaryDataLen, &encryptedDataLen ) ;
  
  // To base 64
  int asciiBase64EncLen ;
  char* asciiBase64Enc = base64( encrypted, encryptedDataLen, &asciiBase64EncLen ) ;
  
  // Destroy the encrypted data (we are using the base64 version of it)
  free( encrypted ) ;
  
  // Return the base64 version of the encrypted data
  return asciiBase64Enc ;
}
 
// rsaDecryptOfUnbase64()
// rsaDecryptBase64String()
// unbase64ThenRSADecrypt()
// rsaDecryptThisBase64()
unsigned char* rsaDecryptThisBase64( RSA *privKey, char* base64String, int *outLen )
{
  int encBinLen ;
  unsigned char* encBin = unbase64( base64String, (int)strlen( base64String ), &encBinLen ) ;
  
  // rsaDecrypt assumes length of encBin based on privKey
  unsigned char *decryptedBin = rsaDecrypt( privKey, encBin, outLen ) ;
  free( encBin ) ;
  
  return decryptedBin ;
}
  
 
 
int main( int argc, const char* argv[] )
{
  ERR_load_crypto_strings();  
  
  puts( "We are going to: rsa_decrypt( unbase64( base64( rsa_encrypt( <<binary data>> ) ) ) )" );
  // public key
  // http://srdevspot.blogspot.ca/2011/08/openssl-error0906d064pem.html
  //1. The file must contain:
  //-----BEGIN CERTIFICATE-----
  //on a separate line (i.e. it must be terminated with a newline).
  //2. Each line of "gibberish" must be 64 characters wide.
  //3. The file must end with:
  //-----END CERTIFICATE-----
  // YOUR PUBLIC KEY MUST CONTAIN NEWLINES.  If it doesn't (ie if you generated it with
  // something like
  // ssh-keygen -t rsa -C "you@example.com"
  // ) THEN YOU MUST INSERT NEWLINES EVERY 64 CHRS (just line it up with how I have it here
  // or with how the ssh-keygen private key is formatted by default)
  const char *b64_pKey = "-----BEGIN PUBLIC KEY-----\n"
  "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCp2w+8HUdECo8V5yuKYrWJmUbL\n"
  "tD6nSyVifN543axXvNSFzQfWNOGVkMsCo6W4hpl5eHv1p9Hqdcf/ZYQDWCK726u6\n"
  "hsZA81AblAOOXKaUaxvFC+ZKRJf+MtUGnv0v7CrGoblm1mMC/OQI1JfSsYi68Epn\n"
  "aOLepTZw+GLTnusQgwIDAQAB\n"
  "-----END PUBLIC KEY-----\n";
  
  // private key
  const char *b64priv_key = "-----BEGIN RSA PRIVATE KEY-----\n"
  "MIICXAIBAAKBgQCp2w+8HUdECo8V5yuKYrWJmUbLtD6nSyVifN543axXvNSFzQfW\n"
  "NOGVkMsCo6W4hpl5eHv1p9Hqdcf/ZYQDWCK726u6hsZA81AblAOOXKaUaxvFC+ZK\n"
  "RJf+MtUGnv0v7CrGoblm1mMC/OQI1JfSsYi68EpnaOLepTZw+GLTnusQgwIDAQAB\n"
  "AoGBAKDuq3PikblH/9YS11AgwjwC++7ZcltzeZJdGTSPY1El2n6Dip9ML0hUjeSM\n"
  "ROIWtac/nsNcJCnvOnUjK/c3NIAaGJcfRPiH/S0Ga6ROiDfFj2UXAmk/v4wRRUzr\n"
  "5lsA0jgEt5qcq2Xr/JPQVGB4wUgL/yQK0dDhW0EdrJ707e3BAkEA1aIHbmcVfCP8\n"
  "Y/uWuK0lvWxrIWfR5MlHhI8tD9lvkot2kyXiV+jB6/gktwk1QaFsy7dCXn7w03+k\n"
  "xrjEGGN+kQJBAMuKf55lDtU9K2Js3YSStTZAXP+Hz7XpoLxmbWFyGvBx806WjgAD\n"
  "624irwS+0tBxkERbRcisfb2cXmAx8earT9MCQDZuVCpjBWxd1t66qYpgQ29iAmG+\n"
  "jBIY3qn9uOOC6RSTiCCx1FvFqDMxRFmGdRVFxeyZwsVE3qNksF0Zko0MPKECQCEe\n"
  "oDV97DP2iCCz5je0R5hUUM2jo8DOC0GcyR+aGZgWcqjPBrwp5x08t43mHxeb4wW8\n"
  "dFZ6+trnntO4TMxkA9ECQB+yCPgO1zisJWYuD46KISoesYhwHe5C1BQElQgi9bio\n"
  "U39fFo88w1pok23a2CZBEXguSvCvexeB68OggdDXvy0=\n"
  "-----END RSA PRIVATE KEY-----\n";
 
  // String to encrypt, INCLUDING NULL TERMINATOR:
  int dataSize=37 ; // 128 for NO PADDING, __ANY SIZE UNDER 128 B__ for RSA_PKCS1_PADDING
  unsigned char *str = makeAlphaString( dataSize ) ;
  printf( "\nThe original data is:\n%s\n\n", (char*)str ) ;
  
  // LOAD PUBLIC KEY
  RSA *pubKey = loadPUBLICKeyFromString( b64_pKey ) ;
  
  int asciiB64ELen ;
  char* asciiB64E = rsaEncryptThenBase64( pubKey, str, dataSize, &asciiB64ELen ) ;
   
  RSA_free( pubKey ) ; // free the public key when you are done all your encryption
  
  printf( "Sending base64_encoded ( rsa_encrypted ( <<binary data>> ) ):\n%s\n", asciiB64E ) ;
  puts( "<<----------------  SENDING DATA ACROSS INTERWEBS  ---------------->>" ) ;
  
  char* rxOverHTTP = asciiB64E ; // Simulate Internet connection by a pointer reference
  printf( "\nRECEIVED some base64 string:\n%s\n", rxOverHTTP ) ;
  puts( "\n * * * What could it be?" ) ;
  
  // Now decrypt this very string with the private key
  RSA *privKey = loadPRIVATEKeyFromString( b64priv_key ) ;
  
  // Now we got the data at the server.  Time to decrypt it.
  int rBinLen ;
  unsigned char* rBin = rsaDecryptThisBase64( privKey, rxOverHTTP, &rBinLen ) ;
  printf("Decrypted %d bytes, the recovered data is:\n%.*s\n\n", rBinLen, rBinLen, rBin ) ; // rBin is not necessarily NULL
  // terminated, so we only print rBinLen chrs
  
  RSA_free(privKey) ;
  
  bool allEq = true ;
  for( int i = 0 ; i < dataSize ; i++ )
    allEq &= (str[i] == rBin[i]) ;
  
  if( allEq ) puts( "DATA TRANSFERRED INTACT!" ) ;
  else puts( "ERROR, recovered binary does not match sent binary" ) ;
  free( str ) ; 
  free( asciiB64E ) ; // rxOverHTTP  
  free( rBin ) ;
  ERR_free_strings();
}

Rae Johnston posts about an experience in a Starbucks’ involving a Bioshock Infinite t-shirt.

I am not sticking up for that guy. He sounds like a loser. But I want to explain what I think is behind that behavior.

First of all reading her top tweets you can see she gets a lot of flack for being a girl gamer. That brings us to the first point:

Any guys that give girl gamers flack for being a girl are sexist guys period. They’re losers. The girl is on “their turf” so they subject her to bad treatment. Only losers do that and there’s no excuse for it.

Second is the encounter with that guy that got almost 10k retweets. The thing there is, there is already a bunch of internet memes about gamer girls who pretend to like games, only to get guys’ attention.

Also you have to keep in mind the shock value of hot girl gamers. Although this might not be true nerdy guys immediately think they have a shot at the nerdy hot girl. Because! Finally! A hot chick who digs the things I do. We’re on the same page! Blah blah blah.

He did a stupid thing calling you out rudely for the shirt. He was a moron. But these are just thoughts on what is going through nerds’ heads.

I can never find this when I’m looking for it, so I dedicated a whole blog post to it.

Here.

The easiest way I’ve found to generate a random alphanumeric string involves RAND(), SHA(), and TO_BASE64()

select LEFT( TO_BASE64( SHA(rand()) ), 6 ) ;

You need MySQL 5.6 to execute.

Alternatively some MYSQL Procedures magic

DELIMITER //

drop function if exists randChr //
create function randChr()
returns char
BEGIN
  IF RAND() <= 0.5 THEN -- Lowercase
	return CHAR( 97 + 25*rand() ) ;
  ELSE -- uc
    return CHAR( 65 + 25*rand() ) ;
  END IF;
END //

drop function if exists randString //
create function randString( len int )
returns varchar(255)
BEGIN
  SET @n = 0;
  SET @res = '' ;
  REPEAT
    SET @res = concat( @res, randChr() ) ;
    set @n = @n + 1 ;
  UNTIL @n >= len END REPEAT;
  return @res ;
END //

DELIMITER ;

select randString( 5 );

Starting from my previous program (Windows), connecting in Mac OS X is even EASIER, only there are a couple’a gotchas.

To code with MYSQL in Mac OS X, just install MySQL normally. In fact it comes with the `/include` and `/lib` folders when you installed it. They are in `/usr/local/mysql` (which is a link to the specific version you have).

Ok, now that’s done, here’s your C++ program:

#include <stdio.h>
#include <stdlib.h>
#include "/usr/local/mysql/include/mysql.h"

MYSQL mysql;    // MYSQL global
MYSQL * conn ;  // represents connection to database

int main()
{
  mysql_init( &mysql ) ;
  
  //   http://dev.mysql.com/doc/refman/5.0/en/mysql-real-connect.html
  conn = mysql_real_connect(  &mysql,
                              "localhost",// synonymous with 127.0.0.1
                              "root",     // connect as user="root".  Uh, bad security here..
                              "",         // my root password is blank.  REALLY bad security :)
                              "mysql",    // connect to the 'mysql' _database_ within MySQL itself.
                               0, 0, 0 ) ;
  
  // Check if connection succeeded.
  if( !conn )
  {
    printf( "Couldn't connect to MySQL database server!\n" ) ;
    printf( "Error: %s\n", mysql_error( &mysql ) ) ;
    return 1 ;
  }
  //else  puts( "Connect success" ) ;
  
  // Here, we are connected.
  // form a sql string to execute.
  if( mysql_query( conn, "select * from user" ) )
  {
    printf("Whoops!  The query failed.  Error:  %s\n", mysql_error( conn ) );
    return 1 ;
  }

  // here, query succeeded, so we can proceed to pull out results.
  MYSQL_RES * resultset ;
  MYSQL_ROW row;  // MYSQL_ROW is #defined as (char **)
  // Data ALWAYS comes back from MySQL as
  // an array of strings.  To convert it
  // to ints or whatever is YOUR JOB as the programmer.

  // mysql_store_result basically fetches
  // the entire array of results and dumps them
  // into our local program memory space (all
  // in the resultset variable.
  resultset = mysql_store_result( conn );

  // How many rows will there be?
  my_ulonglong numRows = mysql_num_rows( resultset ) ;
  printf( "There are %llu ROWS (records) of data\n", numRows ) ;
  
  // Now tell me what columns there are
  // in the result set.
  int numFields = mysql_num_fields( resultset ) ;
  printf( "There are %d FIELDS (columns) of data\n", numFields ) ;

  // Print all those column by name
  MYSQL_FIELD * fields = mysql_fetch_fields( resultset ) ;
  for( int i = 0 ; i < numFields ; i++ )
  {
    printf( "%25s", fields[i].name ) ;
  }

  printf( "\n" ) ;
  // print all results
  while( (row = mysql_fetch_row( resultset )) )
  {
    // row is 2d array of char
    // underlying type is char **
    for ( int i = 0; i < numFields ; i++ )
      printf( "%5s", row[ i ] ) ;
    
    puts( "" ) ;    // next row
  }
  
  mysql_free_result( resultset );  // Now free the result
  mysql_close( conn ) ;  // And close down.
  return 0;
}


GOTCHA #1: An easy one, but you need to link up your TARGET with the libmysqlclient.a library file. So goto your TARGETS / BUILD PHASES tab, under “Link Binary With Libraries” go select “libmysqlclient.a” from /usr/local/mysql/lib.
GOTCHA #2: This is the stupid one, COPY /usr/local/mysql/lib/libmysqlclient.18.dylib to /usr/lib/. ISN’T THAT DUMB??? Well it’s the eq of copying a DLL to C:\Windows\System32 on Windows. Just something you have to do.

If you don’t copy the .dylib you’ll get Library not loaded: libmysqlclient.16.dylib reason: image not found.

The easiest.

1. Mac OS X

sudo apachectl start

Make sure cgi is enabled in your Apache settings

sudo vi /etc/apache2/httpd.conf

Create and build the following:

#include <stdio.h>

int main(int argc, const char * argv[])
{
  //puts( "HTTP/1.1 200 OK" ) ;
  puts( "Content-Type: text/plain; charset=UTF-8" ) ;
  puts( "Status: 200 OK" ) ;
  puts( "" ) ;
  puts( "HELLO INTERNET" ) ;
}

The default folder Xcode 4.6 dumps the exec in is

/Users/YOURUSERNAME/Library/Developer/Xcode/DerivedData/PROJECTNAME-andabunchofrandomcharacters/Build/Products/Debug/PROJECTNAME

Take the exec (called PROJECTNAME) and drop it into:

/Library/WebServer/CGI-Executables/

hit http://localhost/cgi-bin/YOUREXECNAME

It should say HELLO INTERNET.

You are on your way to C++ internet freedom

I simulated some game results. In the sim, Player 2 was so bad, he was 0 for 680. The ranking algorithm ranked him first though, because he sucked so bad, he kept on losing increasingly large quantities of negative points for each match he lost.

It is possible! This table shows it as a sort of nested table.

All you have to do to achieve glow in pixelmator:

1) Take an image

2) Duplicate the layer (Make sure View/Show Layers is on, then Right click/Duplicate)

3) View / Show Effects must be on. From the little Effects window, choose Gaussian Blur. Make it something like 10-15px of blur radius. Your duplicate layer should look like that:

4) Under Blending in your Layers dialog select LINEAR DODGE, then drag the opacity to get your desired level of glow. Make sure the blurred texture appears ON TOP of the original.

5) The result should look something like that

You could compute them using factorials, but this is far more efficient.

// Computes n CHOOSE k
// ( n )
// ( k )
int binomial( int n, int k )
{
  // must accumulate nums/dens separately
  // to avoid roundoff error
  int nums = 1;
  int dens = 1;
  for( int i = 1 ; i <= k ; i++ )
  {
    nums *= ( n - k + i ) ;
    dens *= i ;
  }
  return nums/dens ;
}

//test
int p=7;
for( int i = 0  ; i <= p ; i++ )
  printf( "%dx^%d +", binomial(p, i), p-i ) ;
puts("");