Lukas Z's Tech Blog

iOS: Configure a Different App-icon for Debug-builds

When developing an app, it’s sometimes nice to have a different logo for debug builds (play-icon in XCode) and archive builds. Especially when the versions behave differently.

Now, you can configure the different behavior by passing different values in “Preprocessor Macros” (Build Settings of your target in XCode), but here is just a quick tip on how to set different app-icons:

There’s many ways to go about it, including a prefix file, but I’m just setting the name of the icon file in “Preprocessor Definitions” like this:

plist Variables

And then in the plist itself I susbstitute the icon-filename with the variable name set above:

<... omitted ...>
<dict>
        <key>CFBundlePrimaryIcon</key>
        <dict>
                <key>CFBundleIconFiles</key>
                <array>
                        <string>APP_ICON_FILE</string>
                        <string>APP_ICON_FILE</string>
                        <string>Default</string>
                </array>
        </dict>
</dict>
<... omitted ...>

And that’s about it.

Good Read: Informing Ourselves to Death

In this speech titled “Informing outselves to death”, Neil Postman discusses the rise of information technology and puts it into a broader historical context. He muses about wether it can help us to answer the old big questions of humanity.

I think this is a fantastic read, perhaps especially for folks from the industry like myself. (Because we tend to get too enthusiastic about the tools we create at times.) But it also serves as a warning for those in the inner/englightened circle of information professionals, as well as for those being left out.

The Buddy Cloud

Raspberry Pi

The Raspberry Pi board is a delightful device. I use it at home to play music. I just thought about what it would take to use it for file-storage, specifically, as a backup server.

The problem: One can plug in a harddisk and copy some files. But unless the harddisk is in a different place, it’s still vulnerable. If thieves come, they might steal your computer AND your backup-disk. If there is a fire, same problem.

Since the NSA has somewhat killed cloud-computing (or would you stil use Dropbox, etc.?), there’s a need for a new strategy.

Here’s the idea: The Buddy CloudTM.

In my protoype the following things are needed:

  • Raspberry Pi
  • USB-Disk
  • A buddy with the same equipment

Of course the equipment can vary, but the idea is simple: You keep his backups, he keeps yours. Encrypted, so he can’t read your data and you can’t read his.

(The device should always be plugged in so something low-power like the Pi seems useful.)

The syncing can be as simple as FTP, but it can get more sophisticated with rsync and more advanced algorithms.

What do you think? Buddies helping each other out by providing offsite-backups to each other.

Welcome to the post-cloud-computing world.

Average Salary

To calculate the average salary of a group of people anonymously:

Person #1 invents a (high enough) random number and adds his salary to it. He passes the sum to person #2. #2 adds his salary and passes the new sum to person #3. And so forth, until #1 eventually gets the last sum from the last participant.

Person #1 subtracts the initial random number and divides the result by the number of people. The result is the average salary.

Caveats: People can lie and the number of participants should be big enough. (With 2 people person #1 will just find out the other persons salary.)

Minimalist Twitter Follower Tracking

From the “what you can do with your own email-server”-department: Here is a minimalist way to track followers on Twitter.

Bascially, I wondered how much it would take to get a daily email that lists the people that have subscribed to and unsubscribed from my Twitter feed.

To give you an idea how little it takes, here’s the script that can be executed via crond every day:

#!/bin/bash
DIR="<SOME_DIRECTORY>"
SUBJECT="TWITTER-DIFF"
RECIPIENT="lz"
EMAILMESSAGE="./msg.txt"
DATE=`date`
diff $DIR/followers.txt.prev $DIR/followers.txt > diff.txt
cp $DIR/followers.txt $DIR/followers.txt.prev
t followers @lukaszielinski > $DIR/followers.txt
echo -e "Twitter Followers $DATE\n\n" > $EMAILMESSAGE
echo -e "Diff:\n\n" >> $EMAILMESSAGE
cat diff.txt >> $EMAILMESSAGE
echo -e "\n\nFollowers:\n\n" >> $EMAILMESSAGE
cat $DIR/followers.txt >> $EMAILMESSAGE
mail -s "$SUBJECT" "$RECIPIENT" < $EMAILMESSAGE

Because I use sferik/t (line 9 above) to get the list of followers, this particular script requires ruby to run. A Twitter-API key is also required and can be obtained with a few clicks at twitter.com.

The nice thing about this ugly script is actually just the last line: Because “lz” is a user on the server a simple call of “mail” is all it takes to deliver the data. My mail-client delivers it to my desktop using IMAP.

The result isn’t pretty, but it works.

Of course with some work I can write all sorts of fancy analytics and information into my daily email. But I’ll leave this as an exercise for the so inclined reader. ;)

eigener-emailserver.de

own email-server website icon

UPDATE (Dec. 12th 2013): “Emailserver Page Is Offline”

I just launched eigener-emailserver.de.

It’s a little offering I want to make for everyone that would like to have their own dedicated email server, beause Gmail, Hotmail, Yahoomail etc. have become increasingly unsafe.

The idea is that you rent a¡dedicated or virtual Ubuntu server in the cloud and give me your password and 50 bucks. I will log on and install and configure your new email-server. Afterwards you check if it works and change the password.

And then you have your own email-server with as many email accounts as you like. With your own domain-name of course.

Anyway, I am offering this now, and I wonder if anyone is interested.

More to come.

Dark Patterns

Shady Opt-Out

In a post called “The Slippery Slope” the author talks about shady tactics by online-businesses. It’s mostly about UX that tries to hide/obscure certain things from the users. Things like “Sign up for our newsletter”, “buy a subscription” or “enable ad-tracking”.

The examples are great and it’s worth your time to read it.

As with most scams, some consumers will say “That’s nothing new. This has always be happening. Think about Nokia-ringtones in the 90s that would come with a subscription.”

True, but this is a nice reminder. And good examples make consumers more alert the next time they sign up for something.

Btw. even Apple isn’t excluded. They hide their “Ad tracking”-option in some obscure settings-submenu using unnecessarily indirect language in the option-label. Quite shady, Apple!

The Camera Club

Here’s another business idea.

Now we know that our governments are spying on us. They have the capability to intercept and store practically all of our internet traffic, including emails and phone calls. Perhaps it’s time to play around with other ideas concerning massive surveillance.

The business I imagine is a sort of a “camera club”. Users can buy surveillance cameras and connect them to modems. These modems are set up to transmit live video to the camera club, twenty-four hours a day. Each of them is just filming the street. Perhaps looking out of the window of the camera club member’s home.

The data is of course accumulated and analyzed. Useful information is automatically extracted.

The camera club automatically collects things like biometric data (including face recognition) or license plate numbers of cars. Everything is automatically parsed and stored in a database. The data gets packaged and sold to private businesses and government agencies for a nice profit.

The users that hook up the cameras to their modems get to access all the camera data for free in exchange. For example, each of them can download and browse any other user’s video data from, say, the last 24 hours. They also get reminders to reset their modems or check their connections in case their camera goes offline.

All this could lead to a near perfect coverage of all streets in realtime. For bootstrapping one quarter of a city, preferably some place with elevated street crime (for easier acceptance), would be sufficient.

Of course, I wouldn’t want the camera club to exist. I don’t want to live in a country where I’m filmed every moment of the day when stepping outside the building. But I won’t be holding my breath that a company like this won’t happen.

Everybody (governments and service providers) seem to be lying right now. For what it’s worth, the camera club would seem more honest.

The RSA-Algorithm (in Ruby)

It’s been a while since I looked at how public-key encryption actually works. I thought I need to refresh my knowledge, so here’s a quick summary of the RSA algorithm.

The Idea

The idea is that there are two keys, one public and one private. If I wanted to send you an encrypted message, I would encrypt it with your public key. But using the same public key, I could no longer decrypt it.

Only you can do it, with the private key which, of course, is private and only in your posession.

The public and the private key are just very (very very) big numbers.

It’s impossible (or rather completely, totally unlikely) to calculate the private key from the public key.

Mathematically speaking..

Encryption is, basically, just raising a number (=message) to an exponent (public) modulo some value (public).

Decryption is, basically, just raising a number (=encrypted message) to an exponent (private) modulo some value (public).

It just works with numbers, but any data is bascially a number. If you took this blog post, it would be just one veeeeery long number that, given the encoding (= meaning), represents this post.

So for encryption we have

    c = m ^ e (mod n) 

And for decryption it’s

    m = c ^ d (mod n)

where

    m = plaintext
    c = ciphertext
    e = public exponent
    n = public modulus
    d = private exponent

and the sign = in the above two equasions is actually not “equals to” but “congruent to”, since we are doing modular arithmetic.

That’s it.

The only difficulty is in calculating the keys. the random numbers p * q that make up the product n have to be very large for the cipher ot be secure. And calculating the secret exponent d is a matter of finding the multiplicative inverse for e “under” modulo(phi(n)).

That sounds weird, but it’s very similar to the reciprocal that everyone knows, namely the one, where multiplying the number and its inverse yields 1. For example 5, where the multiplicative inverse is 1/5, because 5 * 1/5 = 1. Same here, except we’re doing modular arithmetic, and we’re dealing with large numbers.

Ruby implementation

Here’s some ruby code that generates keys and uses them to encrypt and decrypt a message.

Note that this only demonstrates the principle. It is probably not entirely secure and definitely not very useful. (See discussion below)

But it runs and you can try it out. :)

class Integer
  # This method to check for primes is not 100% reliable, but almost.
  # Advantage: speed
   def prime?
     n = self.abs
     return true if n == 2
     return false if n == 1 || n & 1 == 0
     return false if n > 3 && n % 6 != 1 && n % 6 != 5

     d = n-1
     d >>= 1 while d & 1 == 0
     20.times do
       a = rand(n-2) + 1
       t = d
       y = Integer.mod_pow( a, t, n )
       while t != n-1 && y != 1 && y != n-1
         y = (y * y) % n
         t <<= 1
       end
       return false if y != n-1 && t & 1 == 0
     end
     return true
   end

   # a^b mod c , using much quicker squaring-method
   # check out https://en.wikipedia.org/wiki/Modular_exponentiation
   # for more information.
   def self.mod_pow( base, power, mod )
     res = 1
     while power > 0
       res = (res * base) % mod if power & 1 == 1
       base = base ** 2 % mod
       power >>= 1
     end
     res
   end
end

class RSA
  # E is the public-exponent, must be positive and smaller than φ(n) = φ(p * q)
  # greatest common divisor of e and φ(n) is 1 (= they are coprime).
  # usually 65537, because we use binary exponentiation and this number is prime
  # and only has two 1's in binary representation (= less cpu-time).
  E = 65537

  class << self

    # Returns the public modulus, the public exponent and the private key.
    def generate_keys( bits )
      n, e, d = 0
      p = random_prime( bits )
      q = random_prime( bits )
      n = p * q
      d = get_d( p, q, E )
      [n, E, d]
    end

    # Encrypts a message with the public modulus (of the receiver).
    # First encode string as a (large) number.
    def encrypt( m, n )
      m = s_to_n( m )
      Integer.mod_pow( m, E, n )
    end

    # Decrypts using the private exponent
    def decrypt( c, n, d )
      m = Integer.mod_pow( c, d, n )
      n_to_s( m )
    end

    private

    # Convert number to string
    def n_to_s( n )
      s = ""
      while( n > 0 )
        s = ( n & 0xFF ).chr + s
        n >>= 8
      end
      s
    end
    
    # Convert string to number
    def s_to_n( s )
      n = 0
      s.each_byte do |b| 
        n = n * 256 + b 
      end
      n
    end

    # Generate a random number and check if
    # it's prime until a prime is found.
    def random_prime( bits )
      begin
        n = random_number( bits )
        return n if n.prime?
      end while true
    end

    # Concatenate string (begins and ends with 1)
    # to get desired length and an uneven value.
    def random_number( bits )
      m = (1..bits-2).map{ rand() > 0.5 ? '1' : '0' }.join
      s = "1" + m + "1"
      s.to_i( 2 )
    end

    # Euler's totient function, φ(p,q)
    # needed so a multiplicative inverse (private key)
    # can be calculated. https://en.wikipedia.org/wiki/Euler%27s_totient_function
    def phi( a, b )
      (a - 1) * (b - 1)
    end

    # Check out https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm
    # for the maths.
    def extended_gcd( a, b )
      return [0,1] if a % b == 0
      x, y = extended_gcd( b, a % b )
      [y, x - y * (a / b)]
    end

    # Calculate the multiplicative inverse d with d * e = 1 (mod φ(p,q)),
    # using the extended euclidian algorithm.
    def get_d(p, q, e)
      t = phi( p, q )
      x, y = extended_gcd( e, t ) 
      x += t if x < 0
      x
    end
  end
end

# (n,e) = public key
# (n,d) = private key
n,e,d = RSA.generate_keys( 256 )

# Something we can't possibly say in public
m = "The Fast And The Furious is a great movie!"

puts "public exponent: %x" % e
puts "public modulus : %x" % n
puts "private exp    : %x" % d

puts ""
puts "Message        : %s" % m
puts ""

c = RSA.encrypt( m, n )

puts "Encrypted      : %x" % c
puts ""
puts "Decrypt again  : %s" % RSA.decrypt( c, n, d )

Discussion

So the above code implements RSA. However, there are some downsides to this implementation.

  1. The message cannot be longer than the key.
  2. The cipher can probably be broken.

Actually, both problems are addressed with the same solution. (And please, take this with a grain of salt, I am a total amateur just scratching the surface here.)

What is missing here is a formatting or padding scheme. If we want to encrypt long messages (arbitrary length) we need to be able to split them up so they are in chunks that can be encrypted.

Also, we need to harden the algorithm against attacks. One such hardening measure is adding random noise to each block, which is used as padding. The result is that the ciphertext will be completely different each time, but the receiver, since he knows how to apply (or un-apply) the padding, will be able to remove it again.

These things are complicated, but the core algorithm is easy. However, they are necesary to avoid certain weaknesses. That’s why, generally, just because a software encrypts data, it does not necessarily mean they do it right. You have to know what you do and/or use well known and well tested libraries. (OpenSSL comes to mind.)

As you can see there’s also some “trickery” involved. And I just mean that you need to use special algorithms, because you can’t just tell the computer to take a number with 500 digits and raise it to the power of another number of 500 digits. It would typically fail or be very slow. Same thing with checking if such a large number is prime. Thus the “good enough” algorithm above.

That’s it

I don’t know. I just wanted to write this down. Just so you can see that it’s not very difficult. Even if the proofs why it’s secure, why it works in the first place, may be not.

Btw. this whole code is based on this great Github repository. This guy also has implementations of other algorithms and some great explanation docs.

Encrypted Notifications

Just a quick thought.

I was talking about encrypted e-mail today and I wonder if it could be a selling point for web applications.

The idea:

Pick a web-service, doesn’t matter if it’s a project management-tool, an open-source code repo, a pizza delivery service or a pornographic website. The point is that you often (possibly always, given the disadvantages of openID) still sign up with an email address. You get a confirmation mail, click the link, and they send you email-notificatitons from then on. Yadayada.

What if they sent out encrypted emails?

Doesn’t matter if it’s PGP/GPG or S/MIME or something else. I think some people would appreciate it. It would also send a positive message that the company cares about these things.

And it would help spread the technology.