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 (java.io 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)
              rawkey
          )))
          
(defn get-propfile [filename]   
    (let [prop (new Properties)]
        (do (. prop load (new FileInputStream filename)))
        prop))
    

(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")
)         

18 comments:

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.

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.

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

encryption

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

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

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


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

hussain d said...

This web site definitely has all of the information and facts I needed
concerning this subject and didn’t know who to ask.UI Development Training in Bangalore
Data Science with Python Training in Bangalore
Python Training in Bangalore
AWS Training in Bangalore
Machine Learning with Python Training in Bangalore
Devops Training in Bangalore

Mrbk30 said...

Very Informative blog thank you for sharing. Keep sharing.

Best software training institute in Chennai. Make your career development the best by learning software courses.

best devops training in chennai
php training in chennai
informatica training in chennai
uipath training in chennai

360DigiTMG said...

Here at this site is really a fastidious material collection so that everybody can enjoy a lot.
data analytics training in hyderabad

Unknown said...

Going to graduate school was a positive decision for me. I enjoyed the coursework, the presentations, the fellow students, and the professors. And since my company reimbursed 100% of the tuition, the only cost that I had to pay on my own was for books and supplies. Otherwise, I received a free master’s degree. All that I had to invest was my time. data scientist course in surat

trublogger said...

that is a however you would prefer extreme article.i am pretty parcels great as well as your however you would prefer con.You supplement truth profoundly amiable to relief have adequate offer exhortation. hold it inside the works. protect contributing to a blog. attempting to investigating your abutting announce. KMPlayer Crack

Unknown said...


Thank you so much for writing such a helpful and insightful article. All the work you put into this essay is greatly appreciated.
https://easyserialkeys.com/plagiarism-checker-x-crack/