Monday, August 30, 2010

Exploring Java AES encryption algorithm with Clojure

Encryption is one of those library that I use infrequently. It seems that every time I need to work with some encryption algorithm, it passes memory expiration date of my last implementation usage of some encryption algorithm. Recently, I had to implement some password encryption tool in Java and again, I had to revisit Java’s encryption library. In the past, for exploring unfamiliar libraries, I would normally write some code sprinkled with print statements, compile it and run the compiled code and adjust my code afterwards. But in the past couple years, I’ve become a big fan of REPL development environment for purposes of library exploration. In the .NET environment, I would use F# Interactive, Ruby & Python have their own REPL environment. For Java, I could have picked either Groovy or Clojure. I’ve scripted Groovy in the past and certainly liked the shorthand expressions to a lot of the Java code. However, I have heard a lot of positive blog posts about Clojure such that I wanted to try it out.

I never had the chance to program in Lisp in the past. But I have read some of Paul Graham’s articles which seems to make Lisp a programmer’s great secret weapon in becoming a better than average programmer. So I figure Clojure can get my feet wet with another variant of Lisp and help me accomplish my day job goals at the same time. The hardest part about learning Clojure was learning the API. The program structure was not hard to figure out. I used an RPN based HP 11C calculator while in college and Clojure program structure reminds me a lot of working with RPN calculators (albeit with a lot more parenthesis). Once I got the hang of the basic Clojure syntax, it became a great environment to work in. I would define a function, run the code and then interactively explore properties or call methods. After exploring in Clojure, it became fairly trivial task to translate that to the Java code.

While it was certainly fun to work in Clojure, I'm not sure I can substantiate Paul Graham's claim that knowing Lisp makes you a better than average programmer. Maybe it's more of the concept that a polyglot programmer generally makes a better programmer simply because the programmer that goes and learns multiple programming languages has a self driven desire to become a better programmer and therefore becomes a better programmer. I'll leave that discussion to the programmer philosophers out there and return to the more pragmmatic code construction.

Here’s the prototype AES encryption code in Clojure:

(import (javax.crypto KeyGenerator SecretKey Cipher))
(import (javax.crypto.spec SecretKeySpec))
(import ( File FileOutputStream DataInputStream FileInputStream))
(import (java.util Properties))
(import (org.apache.commons.codec.binary Base64))

(def msg "Hello encryption world!")
(defn encode-base64 [raw] (. (new Base64) encode raw))
(defn decode-base64 [coded] (. (new Base64) decode coded))

(def aes (. KeyGenerator getInstance "AES"))
(def cipher (. Cipher getInstance "AES"))
(def encrypt (. Cipher ENCRYPT_MODE))
(def decrypt (. Cipher DECRYPT_MODE))

(defn writekey [rawkey filename]     
    ( let [out (new FileOutputStream (new File filename))]
          (do (. out write rawkey)
              (. out close))))
(defn readkey [filename]
    (let [file (new File filename)
          rawkey (byte-array (. file length))
          in  (new DataInputStream (new FileInputStream file))]
          (do (. in readFully rawkey)
              (. in close)
(defn get-propfile [filename]   
    (let [prop (new Properties)]
        (do (. prop load (new FileInputStream filename)))

(defn genkey [keygen] 
    (do (. keygen init  128)
        (. (. keygen generateKey ) getEncoded)
(defn do-encrypt [rawkey plaintext]
    (let [cipher (. Cipher getInstance "AES")]
        (do (. cipher init encrypt (new SecretKeySpec rawkey "AES"))
            (. cipher doFinal (. plaintext getBytes)))))
(defn do-decrypt [rawkey ciphertext]
    (let [cipher (. Cipher getInstance "AES")]
        (do (. cipher init  decrypt (new SecretKeySpec rawkey "AES"))
            (new String(. cipher doFinal ciphertext)))))
(defn get-password [key rawkey filename]
    (let [ props (get-propfile filename)
           coded (. props getProperty key)
           cipher (decode-base64 coded)]
         (do (do-decrypt rawkey cipher))))
(comment "Example usage"
(get-password "jms" (readkey "test.key") "data.out")


Elmira said...

Custom software is the most expensive type of development due to it’s nature - unique functionality and utilization of new challenging technologies. The most important thing to understand is that java software development outsourcing is a significant decision that can have lasting ramifications for an organization

web designing company said...

This is a nice script..presented with high quality information..Thanks for this nice blog.

Unknown said...

This is a great website, so many people need this information, thanks for providing it. I love your color scheme too!


stackhunter vs airbrake said...

Very helpful article ! I was always curious about all these complex algorithms that are being used in these ssl encryptions.

digital signature certificate said...

Every 3 years, Oracle decides the previous version of free Java is “End of Life”, and stops making security updates for it — even though the vast majority of Java users are not free to upgrade, due to application incompatibility.

Priya Kannan said...

Pretty section of content. I simply stumbled upon your site and in accession capital to say that I get actually loved to account your blog posts.
PHP Training in Chennai

moeez said...

I was surfing net and luckily ran over this site and discovered extremely fascinating stuff here. Its truly amusing to peruse. I delighted in a ton. Much obliged for sharing this great data


Tanika Co Valda said...

Very much useful article. Kindly keep blogging

Java Training in Chennai

Java Online Training India

Praylin S said...

Thank you for sharing this wonderful post with us. Looking forward for more posts from you.
Unix Training in Chennai | Unix Shell Scripting Training in Chennai | Unix Course in Chennai | Unix Certification Courses | LINUX Training in Chennai | Excel Training in Chennai | Wordpress Training in Chennai

priya said...

Really great post, I simply unearthed your site and needed to say that I have truly appreciated perusing your blog entries. I want to say thanks for great sharing.
Data Science Training in Indira nagar
Data Science training in marathahalli
Data Science Interview questions and answers
Data Science training in btm layout
Data Science Training in BTM Layout
Data science training in bangalore

Akash Kumar said...

Hey Nice Blog!! Thanks For Sharing!!!Wonderful blog & good post.Its really helpful for me, waiting for a more new post. Keep Blogging!
SEO company in coimbatore
SEO Service in Coimbatore
web design company in coimbatore

Chethu Apponix said...

Very good information. Its very useful for me. We need learn from real time examples and for this we choose good training institute, we need to learn from experts . So we make use of demo classes . Recently we tried java demo class of Apponix Technologies.

smartdeveloper said...

inplant training in chennai

implant training in chennai

internship for cse 3rd year students

inplant training

in plant training in chennai

inplant traning in chennai

internship for bca 2nd year

internship in chennai for ece

internship in chennai for cse


smartdeveloper said...

the c.p of 15 books is equal to the s.p of 18 books. find his gain% or loss%?
integer a=40 b=35 c=20 d=10
javascript int max
react native resume
a merchant sold an article at 10% loss. if he had sold it rs 450 more, 8% would have been gained on the cost price. find the cost price?
a watch was sold at a loss of 10%. if it was sold for rs.140 more, there would have been a gain of 4%. what is the cost price?
flipkart hack apk
hack flipkart
how to hack mobile phones with computer using cmd

vijay said...

Nice post.this post is very useful for us keep it up.

aws Training in Bangalore
python Training in Bangalore
hadoop Training in Bangalore
angular js Training in Bangalore
bigdata analytics Training in Bangalore
python Training in Bangalore
aws Training in Bangalore

Durai Moorthy said...

I am really happy with your blog because your article is very unique and powerful for new reader.
aws Training in Bangalore
python Training in Bangalore
hadoop Training in Bangalore
angular js Training in Bangalore
bigdata analytics Training in Bangalore
python Training in Bangalore
aws Training in Bangalore

Rajesh Anbu said...

Your article is very informative. Thanks for sharing the valuable information.
aws Training in Bangalore
python Training in Bangalore
hadoop Training in Bangalore
angular js Training in Bangalore
bigdata analytics Training in Bangalore
python Training in Bangalore
aws Training in Bangalore

offpageseo70 said...

Nice blog,I understood the topic very clearly,And want to study more like this.
Data Scientist Course

ravali said...

I like viewing web sites which comprehend the price of delivering the excellent useful resource free of charge. I truly adored reading your posting. Thank you!

data science course

cathrine juliet said...

I am reading your post from the beginning, it was so interesting to read & I feel thanks to you for posting such a good blog, keep updates regularly.

Web Designing Course Training in Chennai | Web Designing Course Training in annanagar | Web Designing Course Training in omr | Web Designing Course Training in porur | Web Designing Course Training in tambaram | Web Designing Course Training in velachery

priyash said...

Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article. This article inspired me to read more. keep it up.
Correlation vs Covariance
Simple linear regression
data science interview questions

hema said...

This content is written very well. Your use of formatting when making your points makes your observations very clear and easy to understand. Thank you.

Web design Training in Chennai

Web design Training in Velachery

Web design Training in Tambaram

Web design Training in Porur

Web design Training in Omr
Web design Training in Annanagar

Anonymous said...

You can get Apple-certified repairs and service at the Apple Store or with one of our Apple Authorized Service Providers.
mobile phone repair in North Olmsted
Worked as a Senior SEO & Digital & Social Media & Graphics Design & cpa & Drop shipping & Video Editing And Youtube & Web Design And Development & Affiliate Marketing trainer at BITM (BASIS Institute of Technology & Management) since 2014-2018. Successfully completed 50+ SEO batches, 20+
Affiliate Marketing batches and 30+ workshop on Freelancing under SEIP (Skills for Employment Investment Program).
outsourcing training courses in uttara

Mallela said...

Thanks for posting the best information and the blog is very helpful.Data science course in Faridabad

data scientist london said...

Honestly speaking this blog is absolutely amazing in learning the subject that is building up the knowledge of every individual and enlarging to develop the skills which can be applied in to practical one. Finally, thanking the blogger to launch more further too.
Data Analytics online course

Data Science Course said...

Great to become visiting your weblog once more, it has been a very long time for me. Pleasantly this article i've been sat tight fosuch a long time. I will require this post to add up to my task in the school, and it has identical subject along with your review. Much appreciated, great offer. data science course in nagpur

Data Science Training in Bhilai - 360DigiTMG said...

Wonderful blog found to be very impressive to come across such an awesome blog. I should really appreciate the blogger for the efforts they have put in to develop such an amazing content for all the curious readers who are very keen of being updated across every corner. Ultimately, this is an awesome experience for the readers. Anyways, thanks a lot and keep sharing the content in future too.

Data Science Course in Bhilai

Data Science Training in Bhilai - 360DigiTMG said...

Impressive blog to be honest definitely this post will inspire many more upcoming aspirants. Eventually, this makes the participants to experience and innovate themselves through knowledge wise by visiting this kind of a blog. Once again excellent job keep inspiring with your cool stuff.

Data Science Training in Bhilai

cloud computing course in bangalore said...

Extremely overall quite fascinating post. I was searching for this sort of data and delighted in perusing this one. Continue posting. A debt of gratitude is in order for sharing. data scientist course in delhi