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

33 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.

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

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

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

inplant

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


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 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 Course 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 Course 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

Data Scientist Course in Dombivli 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

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

Unknown said...

Awesome blog. I enjoyed reading your articles. This is truly a great read for me. I have bookmarked it and I am looking forward to reading new articles. Keep up the good work!ethical hacking training in noida

Lokeswari said...

Excellent blog and I really glad to visit your post. Keep continuing...

internship meaning | internship meaning in tamil | internship work from home | internship certificate format | internship for students | internship letter | Internship completion certificate | internship program | internship certificate online | internship graphic design

Unknown said...

Extraordinary post I should state and a debt of gratitude is in order for the data. Instruction is unquestionably a clingy subject. Be that as it may, is still among the main subjects within recent memory. I value your post and anticipate more.business analytics course in gurgaon

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

Block said...

Your very own commitment to getting the message throughout came
to be rather powerful and have consistently enabled employees just
like me to arrive at their desired goals.
big data hadoop training in chennai
software testing course in chennai
javascript course in chennai

Sarvesh said...

Are you searching for the best AWS Training in Chennai Here is the best software training Institute in Chennai. Infycle Technologies gives you finest courses such as Power BI, Cyber Security, Graphic Design and Animation, Block Security, Java, Oracle, Python, Big data, Azure, Python, Manual and Automation Testing, DevOps, Medical Coding etc., and we also provide best technical trainers with best training 100+ Live Practical Sessions with Real-Time scenarios at the end of the course the freshers, experienced, and Tech professionals will be able to obtain more knowledge of the course and be able to crack interviews on top MNC’s with an amazing package. For more details ring us up on 7504633633, 7502633633.

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

Data Science 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.
business analytics course in warangal

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

Mona 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/

mylearnnest said...

A corporate enterprise cannot function effectively without human resources. He/she is in charge of the tactics that assist a company to grow. HR profe/best-sap-success-factors-training-in-hyderabad/ssionals have a distinct and crucial function in a company.

/best-sap-success-factors-training-in-hyderabad/