You Are Here:

Community: Wiki

This page was last modified on 30 March 2009, at 16:04.

CS001314 - Encrypting and decrypting in Java ME

From Forum Nokia Wiki



ID CS001314 Creation date March 30, 2009
Platform S60 3rd Edition, FP2, S60 5th Edition Tested on devices Nokia 6220 Classic, Nokia N85, Nokia 5800 XpressMusic
Category Java ME Subcategory Files/Data, Security


Keywords (APIs, classes, methods, functions): javax.crypto.Cipher, javax.crypto.spec.SecretKeySpec


Overview

This code snippet shows how you can encrypt and decrypt text strings with Java ME, using methods of the Cipher object.

Source file: EnDecryptingMIDlet.java

/**
* Executes the snippet.
* Implementation executes the cryptingDecrypting() method with
* "Test string!" parameter.
*/

private void executeSnippet() {
String text = "Snippet executed...";
printString(text);
 
cryptingDecrypting("Test string!");
try {
logPrintString(text);
} catch (IOException ex) {
printString(ex.getMessage());
}
}
 
/**
* This function encrypts and decrypts the input parameter string
* @param textToCrypting - string that will be encrypted and decrypted
*/

protected void cryptingDecrypting(String textToCrypting) {
//Object of this class provides the functionality for
//encryption and decryption.
Cipher cipher;
 
try {
//parameter "DES" specifies type of cipher we want to create
//through the factory method. It includes algorithm, mode and
//padding. You can define only algorithm and in that case default
//values will be used for mode and padding.
cipher = Cipher.getInstance("DES");
} catch (NoSuchAlgorithmException ex) {
//requested cryptographic algorithm is not available
printString(ex.toString());
printString("Error! Snippets execution stopped.");
return;
} catch (NoSuchPaddingException ex) {
//requested padding mechanism is not available in the environment.
printString(ex.toString());
printString("Error! Snippets execution stopped.");
return;
}
 
//The lenght of keyString is 8. It's important characteristic
//for encryption
String keyString = "testtest";
 
byte[] keyData = keyString.getBytes();
 
//key object specifies a secret key
//it uses to construct the secret key for our cipher object from a byte
//array
SecretKeySpec key = new SecretKeySpec(keyData, 0, keyData.length,
"DES");
 
try {
//initializing with setting up the type of operation it's to be
//used for. In this case - for encryption.
cipher.init(Cipher.ENCRYPT_MODE, key);
} catch (InvalidKeyException ex) {
//given key object is inappropriate for initializing this cipher
printString(ex.toString());
printString("Error! Snippets execution stopped.");
return;
}
 
int cypheredBytes = 0;
 
printString("Source string: " + textToCrypting);
 
byte[] inputBytes = textToCrypting.getBytes();
byte[] outputBytes = new byte[100];
 
try {
//doFinal method encrypts data to outputBytes array.
//for unknown or big counts of data update method more recomended
//counts of crypted bytes saved inside cypheredBytes variable
cypheredBytes = cipher.doFinal(inputBytes, 0, inputBytes.length,
outputBytes, 0);
} catch (IllegalStateException ex) {
printString(ex.toString());
printString("Error! Snippets execution stopped.");
return;
} catch (ShortBufferException ex) {
printString(ex.toString());
printString("Error! Snippets execution stopped.");
return;
} catch (IllegalBlockSizeException ex) {
printString(ex.toString());
printString("Error! Snippets execution stopped.");
return;
} catch (BadPaddingException ex) {
printString(ex.toString());
printString("Error! Snippets execution stopped.");
return;
}
 
String str = new String(outputBytes, 0, cypheredBytes);
inputBytes = str.getBytes();
printString("Crypted string:" + str);
 
try {
//change state of the cipher object for decrypting
cipher.init(Cipher.DECRYPT_MODE, key);
} catch (InvalidKeyException ex) {
printString(ex.toString());
printString("Error! Snippets execution stopped.");
return;
}
 
try {
//decrypts data
cypheredBytes = cipher.doFinal(inputBytes, 0, inputBytes.length,
outputBytes, 0);
} catch (IllegalStateException ex) {
printString(ex.toString());
printString("Error! Snippets execution stopped.");
return;
} catch (ShortBufferException ex) {
printString(ex.toString());
printString("Error! Snippets execution stopped.");
return;
} catch (IllegalBlockSizeException ex) {
printString(ex.toString());
printString("Error! Snippets execution stopped.");
return;
} catch (BadPaddingException ex) {
printString(ex.toString());
printString("Error! Snippets execution stopped.");
return;
}
 
str = new String(outputBytes, 0, cypheredBytes);
printString("Decrypted string:" + str);
printString(" Ok! " + str);
}

Postconditions

After choosing the command Execute snippet, the MIDlet displays 'Test string!' in the text field. This message is then encrypted, and the encrypted message is displayed. Finally, the encrypted message is decrypted, and the decrypted message is displayed.

Supplementary material

This code snippet is part of the stub concept, which means that it has been patched on top of a template application in order to be more useful for developers. The version of the Java ME stub application used as a template in this snippet is v1.1.

  • The patched, executable application that can be used to test the features described in this snippet is available for download at Media:EncryptingAndDecrypting.zip.
  • You can view all the changes that are required to implement the above-mentioned features. The changes are provided in unified diff and colour-coded diff (HTML) formats in Media:EncryptingAndDecrypting.diff.zip.
  • For general information on applying the patch, see Using Diffs.
  • For unpatched stub applications, see Example stub.

Related Wiki Articles

No related wiki articles found

Rate This

 
Bookmark this page: DeliciousDiggFacebookGoogleYahooStumbleUponRedditDiigoTechnocratiTwitter  Share this page Share this page Print this Page Print this page Invite a friend Invite a friend
京ICP备05048969号    Email Newsletters Press Terms & Conditions Privacy Policy Sitemap Contact Us © 2009 Nokia 
RDF Facets: qdcZdescriptionQSxEa0E20WikiE20javaE20symbianE5fosE20s60E20maemoE20cE2bE2bE20WikiE20HomeE20WikiE20HelpE20OverviewE20GlossaryE20CreateE20PageE20ProposeE20anE20ArticleE20SpotlightE20TopicE20E2dE20WE52TE20WidgetsE20ProgrammingE20E4canguageE20E2dE20SymbianE20CE2bE2bE20E2dE20OpenE20CE2fCE2bE2bE20E2dE20JavaE20E2dE20FlashE20E4citeE20E2dE20PythonE20WebE20TechnologiesE20E2dE20WE52TE20WidgetsE20E2dE20WidSetsE20ToolsE20andE20SE44KE20CodeE20E45E78amplesE20KnowledgeE20BaseE20TechnologyE20AreasE20SoftwareE20PlatformsE20E44evelopmentE20ProcessE20E3fE3fWikiE20ChineseE20E3fE3fE3fWikiE20JapaneseE20PortugueseE2fBrazilianE20E52ussianE20WhatE20linksE20hereE20UploadE20fileE20SpecialE20pagesE20PrintableE20versionE44ownloadE20asE20PE44FE20GoE20ToE20E2eE2eE2eX qdcZidentifierQSxhttpE3aE2fE2fwikiE2eforumE2enokiaE2ecomE2findeE78E2ephpE2fE45ncryptE2dE44ecryptE5fMessagesX qdcZpublisherQUxhttpE3aE2fE2fswE2enokiaE2ecomE2fidE2fc764fd1cE2d8b06E2d499aE2d9a6aE2d17c3903d5a65E2fforumE5fnokiaE5fcrawlerE5fagentX qdcZtitleQSxE45ncryptE2dE44ecryptE20MessagesE20E2dE20ForumE20NokiaE20WikiX qdcZtypeQUqfnZE45E78cludedFromGeneralE4cistingsQ qdcZtypeQUqfntypeZCommunityContentQ qdcZtypeQUqfntypeZE52esourceQ qdcZtypeQUqfntypeZWebpageQ qdcZtypeQUqfntypeZWikiContentQ qdcZtypeQUqmarsZManagedE52esourceQ qdcZtypeQUqwebZInformationE52esourceQ qdcZtypeQUqwebZPageQ qdcZtypeQUqwebZE52esourceQ qdcZtypeQUqrdfsZE52esourceQ qrssZdescriptionQSxEa0E20WikiE20javaE20symbianE5fosE20s60E20maemoE20cE2bE2bE20WikiE20HomeE20WikiE20HelpE20OverviewE20GlossaryE20CreateE20PageE20ProposeE20anE20ArticleE20SpotlightE20TopicE20E2dE20WE52TE20WidgetsE20ProgrammingE20E4canguageE20E2dE20SymbianE20CE2bE2bE20E2dE20OpenE20CE2fCE2bE2bE20E2dE20JavaE20E2dE20FlashE20E4citeE20E2dE20PythonE20WebE20TechnologiesE20E2dE20WE52TE20WidgetsE20E2dE20WidSetsE20ToolsE20andE20SE44KE20CodeE20E45E78amplesE20KnowledgeE20BaseE20TechnologyE20AreasE20SoftwareE20PlatformsE20E44evelopmentE20ProcessE20E3fE3fWikiE20ChineseE20E3fE3fE3fWikiE20JapaneseE20PortugueseE2fBrazilianE20E52ussianE20WhatE20linksE20hereE20UploadE20fileE20SpecialE20pagesE20PrintableE20versionE44ownloadE20asE20PE44FE20GoE20ToE20E2eE2eE2eX qfnZdistributionQUxhttpE3aE2fE2fwikiE2eforumE2enokiaE2ecomE2fX qfnZtypeQUqfntypeZCommunityContentQ qfnZtypeQUqfntypeZE52esourceQ qfnZtypeQUqfntypeZWebpageQ qfnZtypeQUqfntypeZWikiContentQ qfnZupdatedQDx2008E2d10E2d02X qfnZuserE5ftagQSxfolderX qfnZuserE5ftagQSxpop3X qfnZuserE5ftagQSxprivateX qmarsZdescriptionQSxEa0E20WikiE20javaE20symbianE5fosE20s60E20maemoE20cE2bE2bE20WikiE20HomeE20WikiE20HelpE20OverviewE20GlossaryE20CreateE20PageE20ProposeE20anE20ArticleE20SpotlightE20TopicE20E2dE20WE52TE20WidgetsE20ProgrammingE20E4canguageE20E2dE20SymbianE20CE2bE2bE20E2dE20OpenE20CE2fCE2bE2bE20E2dE20JavaE20E2dE20FlashE20E4citeE20E2dE20PythonE20WebE20TechnologiesE20E2dE20WE52TE20WidgetsE20E2dE20WidSetsE20ToolsE20andE20SE44KE20CodeE20E45E78amplesE20KnowledgeE20BaseE20TechnologyE20AreasE20SoftwareE20PlatformsE20E44evelopmentE20ProcessE20E3fE3fWikiE20ChineseE20E3fE3fE3fWikiE20JapaneseE20PortugueseE2fBrazilianE20E52ussianE20WhatE20linksE20hereE20UploadE20fileE20SpecialE20pagesE20PrintableE20versionE44ownloadE20asE20PE44FE20GoE20ToE20E2eE2eE2eX qmarsZlanguageQUxhttpE3aE2fE2fswE2enokiaE2ecomE2flanguageE2d1E2fenX qrdfZtypeQUqfnZE45E78cludedFromGeneralE4cistingsQ qrdfZtypeQUqfntypeZCommunityContentQ qrdfZtypeQUqfntypeZE52esourceQ qrdfZtypeQUqfntypeZWebpageQ qrdfZtypeQUqfntypeZWikiContentQ qrdfZtypeQUqmarsZManagedE52esourceQ qrdfZtypeQUqwebZInformationE52esourceQ qrdfZtypeQUqwebZPageQ qrdfZtypeQUqwebZE52esourceQ qrdfZtypeQUqrdfsZE52esourceQ