PKCS: Public Key Cryptography Standards

PKCS #1: PKCS #1 defines mathematical definitions and properties of RSA public and private keys.

PKCS #7: PKCS #7 is the Cryptographic Message Syntax (CMS) for storing signed and/or encrypted data. PKCS #7 files can be stored as DER or PEM format.

PKCS #8: PKCS#8 is a syntax for storing private key information.

PKCS #11: PKCS #11 is the programming interface for cryptographic tokens (like smart cards).

PKCS #12: PKCS #12 is the file format for storing a private key and its certificate and/or certificate chain. The file may be encrypted and signed. Its extension can be .p12 or .pfx, though p12 is actually the successor to pfx. P12 files can be created with OpenSSL or with Java’s keytool (see my post about how to do that here).

Kotlin Basics

This information is a collection of my notes from taking Google’s Kotlin Bootcamp for Programmers course.

Types

Kotlin has 4 numerical types: Int, Long, Float, and Double. Math with Ints returns an Int, Math with any decimal numbers returns decimal numbers. Kotlin will autobox, and you can call methods like add, minus, div, and times:

4.times(5) = 20

You can use underscores in numbers to make them more readable:

1_000_000

Cast with myVar.toType():

newInt = oldByte.toInt()

Kotlin is strongly typed, but you do not have to declare the type since the compiler can usually figure out the type. Both of the declarations below are valid and are equivalent:

var i : Int = 2;
var i = 2;

Variables

val – Once declared you cannot change the value.
var – Variables declared with var can be reassigned.

Variable Interpolation is useful when working with Strings. Insert $variableName inside a String, and it will be replaced with its value. You can also include expressions to be evaluated inside curly braces:

"Hello $name, nice to meet you."
"We have ${numDogs + numCats} pets."

Comparison

Comparison in Kotlin is similar to Java. Addtionally, you can check ranges:

if (x in 1..100)

Use “when” like a switch statement. Note that “break” is not necessary and “else” is optional (similar to “default” in a switch statement):

when (numberOfCats) {
0 -> println("Sorry")
1 -> println("Not enough")
in 2..7 -> println("Just right")
else -> println("Too many")
}

Nullability

By default variables cannot be null. If you are not initializing them with a value, you can use the “?” to indicate the variable can be null:

var num: Int? = null

Instead of checking for null explicitly before calling a method on a variable, instead you can use the “?” operator:

num = num?.dec()

Similarly, you can chain null tests with the Elvis operator “?:”. This is like saying, if value is not null do one thing, if it is null do the other thing:

num = num?.dec() ?: 0 // decrements num if non null, sets num to 0 if it is null

The “not null assertion opertator” or “double bang”, “!!”, let’s you throw a NullPointerException when a value is null:

val len = name!!.length // throws NPE is name is null

Arrays & Lists

Create an immutable list with listOf:

val myList = listOf("item1", "item2", "item3")

Create a mutable list with mutableListOf:

val myList = mutableListOf("item1", "item2", "item3")
myList.remove("item2");

Arrays are immutable only. Once created, you cannot add or remove items – but you can still change the values of the elements. Use Arrays.toString to print the array. This is not necessary for lists.

val myArray = arrayOf("item1", "item2", "item3")
println(java.util.Arrays.toString(myArray));

With arrays you can mix type, or declare an array of a defined type:

val mixed = arrayOf("Item1", 2, true)
val intArr = intArrayOf(1, 2, 3
)

Arrays can be combined with “+”:

val newArr = arr1 + arr2

You can initialize arrays with code, where “it” is the index. In the example below we initialize an array of length 5 with values equal to the index * 3:

val newArr = Array(5) {it * 3}

Loops

There are many ways to loop through lists and arrays using for loops:

for (element in myArray) {...}
for ((index, element) in myArray.withIndex()) {...}
for (i in 1..5) {...}
for (i in 10 downTo 1) {...}
for (i in 4..10 step 2) {...}
for (i in 'a'..'z') {...}

Kotlin has traditional while & do while loops. It also has repeat loops:

repeat(xTimes) {...}

Functions

main is declared like so – note how arrays are declared and how they are used.

fun main(args: Array<String>) {
    println("Hello, ${args[0]}")
}

You can assign an expression to a variable.

// This line prints & assigns kotlin.Unit to the variable 
val isUnit = println("This is an expression")
// This line prints kotlin.Unit
println(isUnit) 

Parameters can have default values. You can skip passing in those arguments, override the default value, or assign the value by name. You can also use a function as a default value.

fun swim(speed: String = "fast", funParam: String = getFunParam()) {
   println("swimming $speed")
}
swim()
swim("slow")
swim(speed = "medium")

Single expression functions are like lambdas in that it’s a shorter syntax where you can omit the curly braces and return statement.

fun isTooHot(temperature: Int) = temperature > 30
fun isDirty(dirty: Int) = dirty > 30
fun isSunday(day: String) = day == "Sunday"

Lambdas

Lambdas can be assigned to variables and then used like functions.

var dirtyLevel = 20;
val filterWaterLambda = {dirt: Int -> dirt / 2}
filterWaterLambda(dirtyLevel)

Function Types

val filterWaterFunction : (Int) -> Int = {dirt -> dirt / 2}

In the code above we’re setting filterWaterFunction equal to a function that takes an Int as a parameter and returns an it. After the equals sign is the lambda that defines the function. Unlike the lambda above, we don’t have to specify the type for “dirt” (but we can).

Higher Order Functions

A higher order function can take another function as an argument.

fun updateDirty(dirty: Int, operation: (Int) -> Int) : Int {
return operation(dirty)
}
val operation: (Int) -> Int = {dirty -> dirty / 2}
// call the higher order function with a lambda
println( updateDirty(20, operation))
// call the higher order function with a regular function
fun increaseDirty(start: Int) : Int {
return start + 1
}
println(updateDirty(20, ::increaseDirty)
)

Last Parameter Call Syntax

Kotlin prefers for parameters that take functions to be the last parameter. In this case you can pass a lambda outside parentheses.

var dirtyLevel = 19
dirtyLevel = updateDirty(dirtyLevel) {dirty -> dirty + 5}
println(dirtyLevel)

Constructors

Define a constructor like a function to pass in parameters. Or define fields in the constructor. Additional initialization takes place in init blocks

// Parameters, they can only be seen when initializing fields or in init blocks
Aquarium(length :Int = 20, width: Int = 30, height: Int = 40)
// Fields, they can be seen anywhere in the class
Aquarium(var length:Int = 20, var width: Int = 30, var height: Int = 40)

init{
println("$length")
}

Hot Corn Dip

This is a recipe I made a few times many years ago, loved it, then completely forgot about it – until today! Thankfully I had a link to it in my email and the website still worked. This is not my recipe, the original is from Gina Marie’s Kitchen.

Ingredients:

2 cups shredded Cheddar cheese
1 cup shredded Monterey Jack
2 Tbsp chipotle peppers in adobo sauce, diced small
4oz can diced green chilies, undrained
1/2 cup Mayo
1/4 tsp garlic powder
11 oz can of corn, drained

Toppings:
1 small tomato
2 tbs cilantro, chopped
2 tbs green onions, sliced thin

Directions:

Preheat oven to 350 degrees.
Mix all ingredients except the toppings together in a bowl.
Pour into an oven safe dish and bake 20 minutes or until golden brown and bubbly.
Top with diced tomatoes, green onions, and cilantro. Serve immediately with tortilla chips.

C++ Pointer Rundown

There are a few operators in C++ that mean different things depending on their context. Here’s a quick guide gathered from the Reference and Pointer tutorials found at www.w3schools.com:

// Create a variable
string food = “Pizza”;
cout << food << “\n”; // Pizza
cout << &food << “\n”; // memoryLocation1

// Used in a variable definition, “&” creates a reference to food (meal refers to the same “Pizza”)
string &meal = food;
cout << meal << “\n”; // Pizza
cout << &meal << “\n”; // memoryLocation1

// Create a copy of food (new pizza is also “Pizza”, but not the same pizza as food)
string newPizza = food;
cout << newPizza << “\n”; // Pizza
cout << &newPizza << “\n”; // memoryLocation2

// Used in front of an existing variable, “&” gets the address of the variable (a pointer stores an address as its value)
string* address = &newPizza;
cout << address << “\n”; // memoryLocation2

// Used in front of a var defined as a pointer, “*” dereferences that pointer
cout << *address << “\n”; // Pizza

// Changing the value of a pointer will change what’s stored there (“address” was storing the address of newPizza)
*address = “Burger”;
cout << *address << “\n”; // Burger
cout << newPizza << “\n”; // Burger

Android: Lifecycle

The following diagram is helpful in understanding the Android Activity Lifecycle. This diagram is from a google code lab which can be found here.

onCreate(): This is only called once, before the activity is visible. Handle any one-time initializations such as inflate the layout, define click listeners, initialize variables, or set up view binding. The Bundle parameter will be null the first time an activity is started, but if it’s been destroyed and recreated, the Bundle will contain any info that was saved in onSaveInstanceState().

onRestart(): This is not called when the activity first starts, but only after being restarted after having been previously stopped, such as when a user has gone back to the home screen, then reopens the Activity from the recents screen. This is where you can put code you want to call only if your app is not being started for the first time.

onStart(): This can be called many times and the activity is visible after onStart() runs. It gets called when the Activity returns to the foreground such as when screen is turned back on or when returning to the activity from the home screen or another activity.

onRestoreInstanceState(): You can restore data that was save in onSaveInstanceState(), though generally it is better to restore it in onCreate(). Restore it here in case it needs to be stored after onCreate(). The same Bundle is passed to both methods.

onResume(): This is always called after onStart() even if the activity is just starting and there is nothing to resume. This is where the app gains focus and the user can interact with it. When the activity has been paused, onResume() will be called when it regains focus.

onPause(): This is called when an Activity no longer has focus but is still visible on the screen. For example, when a user chooses to “share”, a dialog pops up which then has focus, but the Activity can still be seen behind the dialog. Code that runs in this method can block other things from displaying, so it should be kept light weight.

onStop(): This is called when an activity moves into the background, such as when a user returns to the home screen. After onStop() is called, the Activity is no longer visible on the screen, but it is still in memory in the background and resources are still in use.

onSaveInstanceState(): This is where you save any data you might need in case the activity is destroyed. It is called after onStop() even if onDestroy() is not called. Any data saved to the Bundle can be restored either in onCreate() or in onRestoreInstanceState().

onDestroy(): This is called once to clean up any resources used by the activity when it is shut down. Once an activity is destroyed, an Activity can be garbage collected. Activities can be destroyed by rotating the device, hitting the back button, by calling Activity.finish(), or when a user force-quits the app. Activities that have not been used for a long time may also be destroyed. First, it will be paused and stopped.

Fragment Lifecycle

Fragments have their own lifecycle depicted in the diagram below. You can learn more about the Fragment Lifecycle and see the original diagram in this codelab.

You can access the 5 Fragment states in the Lifecycle.State enum:

INITIALIZED: A new instance has been instantiated.
CREATED: The fragment lifecycle methods are called. The view associated with the fragment is created.
STARTED: The fragment is visible on screen but does not have focus.
RESUMED: The fragment is visible and has focus.
DESTROYED: The fragment has been de-instantiated.

Override the following methods in Fragment to respond to lifecycle events:

onCreate(): The fragment has entered the CREATED state. It has been instantiated but there is no view yet.

onCreateView(): This is where you inflate the layout (note this is different than Activity).

onViewCreated(): This is called after the view is created and is when you would bind views to properties (with findViewById()).

onStart(): The fragment has entered the STARTED state,

onResume(): The fragment has entered the RESUMED state. It has focus and can respond to user input.

onPause(): The fragment has re-entered the STARTED state and is visible.

onStop(): The fragment has re-entered the CREATED state. It is still instantiated but is not present on screen.

onDestroyView(): The view has been removed from memory but the fragment object still exists.

onDestroy(): The fragment has entered the DESTROYED state.

Java Keytool

As someone who frequently works with digital ids and signatures, keytool is a must have. Here are a few common commands I use when working with keytool. You can also find the complete documentation here.

Generate a new digital id:

keytool -genkey -keystore c:\test\keystore.p12 -storetype pkcs12 -storepass password -keypass password -alias myAlias -keyalg RSA -validity 3650

To create a chained certificate, generate both the parent and the child using the command above. Then use the command below to chain the two and export the child certificate:

keytool -alias child -keystore c:\test\child.p12 -storepass password -certreq |keytool -alias parent -keystore c:\test\parent.p12 -storepass password -gencert > child.cert

Or to add the chained certificate to the digital id, create both keys in chain.p12 as in the first example. Then chain the two together like this:

keytool -alias child -certreq -keystore chain.p12 -storepass password | keytool -alias parent -gencert -ext san=dns:child -keystore chain.p12 -storepass password | keytool -alias child -importcert -keystore chain.p12 -storepass password

Android: Intents (Kotlin)

There are two types of intents: Explicit and Implicit. The following examples and info come from this codelab.

Explicit intents are generally used to start another activity within your app. You can construct it with the constructor that takes the Context and the Activity class as parameters. Use Intent.putExtra to send parameters to the new activity. For example:

val intent = Intent(context, DetailActivity::class.java)
intent.putExtra(DetailActivity.LETTER, item.toString())
context.startActivity(intent)

Implicit intents are generally used to start an activity of the user’s choosing. For example you may have several browsers on your device that could be used to open a URL. You can construct it with the constructor that takes the Intent type and the Uri. For example:

val query = Uri.parse(DetailActivity.SEARCH_PREFIX + item)
val intent = Intent(Intent.ACTION_VIEW, query)
context.startActivity(intent)

Android: RecyclerView (Kotlin)

XML Layout
Create a new layout file with a LinearLayout at the top level if you plan to display multiple Views for each item. If you will only have one view, i.e. a TextView, you can make that your top level View instead. Give it an id and set the layout_width and layout_height to “wrap_content”.

Adapter
MyAdapter extends RecyclerView.Adapter<MyViewHolder>
Once you have created the Adapter class, go ahead and create the inner ViewHolder class so the implemented methods will have the correct type. Then implement the Adapter classes:
onCreateViewHolder – Inflate the xml layout, and use it to create and return an instance of your ViewHolder.

val adapterLayout = LayoutInflater.from(context).inflate(R.layout.list_item, parent, false)

onBindViewHolder – Get the item from the cached list of items, and use it to set the content of the View inside the ViewHolder (be sure to handle a null list of items).
getItemCount – Return the size of the cached list of items – handle null case.

ViewHolder
MyViewHolder extends RecyclerView.ViewHolder. This can be an inner class of the Adapter. The constructor takes a View as a parameter. This is the layout that gets inflated by the adapter. Get any Views from the parent and store them as a member variables. You can call findViewById on the parent View to get its children.

MainActivity
onCreate – Set up the RecyclerView

// Kotlin
// Initialize data.
val myDataset = Datasource().loadAffirmations()
val recyclerView = findViewById<RecyclerView>(R.id.recycler_view)
recyclerView.adapter = ItemAdapter(this, myDataset)

// Java
RecyclerView recyclerView = findViewById(R.id.recyclerview);
recyclerView.setAdapter(new MyAdapter(this));
// a layout manager must be provided for the RecyclerView to function
recyclerView.setLayoutManager(new LinearLayoutManager(this));

Android: View Binding

In your app build.gradle file, add the following lines to the “android” section:

buildFeatures {
    viewBinding = true
}

In your main class, create a member variable called, “binding”, where the name of the binding class is the name of the layout converted to camelCase:

 lateinit var binding: ActivityMainBinding

In onCreate(), initialize the view binding:

binding = ActivityMainBinding.inflate(layoutInflater)

Call setContentView with “binding.root” instead of the main layout file:

setContentView(binding.root)

Now you can access views using the binding object like this, where the name of the view is its id converted to camelCase.:

binding.myViewId

Options Trading Rundown

The following info was gathered from E*TRADE’s Options Trading for Beginners Series.

Call

This is a strategy to use if you expect the price to go up.

Buying a call is like buying a coupon. Maybe I don’t want to buy pizza today even though it’s only $8, but I think the price is going up so I can buy a coupon for $10 to use if/when the price goes above $10 (factoring in the cost I paid for the coupon). Same with stocks – I buy the choice, “option”, to buy it at a certain price even if the price goes above that. If it doesn’t hit that certain price I do not have to buy it. This is great if I can use a $10 coupon on a $20 pizza!

You earn/save money if the price goes up beyond the value of the coupon plus what you paid for that coupon. If you pay $1 for the option to buy at $10, you won’t make a profit selling the stock until the price is at least $11+.

You lose money with this strategy if you’ve paid for a coupon, “option”, that you never get to use when the price doesn’t go up as expected. i.e. You paid $1 for the option to buy at $10, but the price doesn’t rise beyond $10 before the option expires.

Put

This is a strategy to use if you expect the price to drop.

Buying a put is like buying insurance. I already own my car, but I expect the value to drop. Buying a put allows me to sell my $8000 car (or stock) for $7000 even if the actual value drops below that.

You earn/save money if the value drops below the value of the option. If I buy a stock for $10 but I’m worried the price will fall, I can buy a put for $9 and if the price drops to $5, I can still sell for $9. If I paid $1 for the option to do this, I essentially get rid of this stock for $8 instead of only $5. So this is a strategy to use if you expect the price to drop.

You lose the amount you paid for the option if the stock doesn’t drop.

Covered Call

This is a strategy to use if you expect the price to drop.

This is when I’m on the other side of a call, selling someone else a coupon for a stock I own. If I’m willing to sell a stock I paid $10 for once it reaches $12, I make not only the $2 profit, but the amount I was paid to sell it (which I get up front).

You earn money if the stock doesn’t go up and the “coupon” is never used.

You lose money if the stock rises more than anticipated and you have to sell your stock that’s worth $20 for only $12.

Cash Secured Put

This is a strategy to use if you expect the price to go up.

This is when I’m selling someone else insurance (agreeing to buy their stock if it drops). If a stock costs more than I’m willing to pay for it, someone pays me to buy it from them if/when it drops. I get the premium even if it doesn’t drop, but if it does drop I get the stock at the price I wanted it for.

You gain money if the stock doesn’t drop (because you keep the premium) or if it drops to the price you’ve agreed to buy it for, but not lower.

You lose money if the stock drops below what you’ve agreed to pay for it. i.e. A stock is currently worth $100, I agree to buy if/when it drops to $95, but it drops all the way to $90.