BlackBerry Forums Support Community
              

Closed Thread
 
Thread Tools
Old 05-14-2008, 01:28 AM   #1
skynetchris
Knows Where the Search Button Is
 
Join Date: Apr 2008
Model: 7100T
PIN: N/A
Carrier: optus
Posts: 24
Default Any Encryption (DES or RSA x509).

Please Login to Remove!

Hi guys,

I've been asked to encrypt a file before its written to SDCard.

I've tried both DES and RSA with no luck.

I wanted to create a certificate that the BB could use to encrypt with and store the private key on the PC to decrypt with.

So i started with RSA(following RIM knowledge base AES example). Which I can run by itself and it works well.

I followed a google code example of creating the necessary public and private keys along with a certificate. That went fine.

The problem comes when I try to import the certificate and use the public key, i tried:

Code:
 try
{
   fconn = (FileConnection)Connector.open("file:///SDCard/cert.pfx",Connector.READ);
   fileStream = fconn.openInputStream();
   X509Certificate cert = new X509Certificate(fileStream);
   RSAPublicKey publicKey = (RSAPublicKey)cert.getPublicKey();
   publicKey.verify();
}
With all appropriate catch statements

Which seems to work without a hitch, but then I pass it to the encrypt method used in the Knowledge base example and it gives Java.lang exception?

Also if I try and verify the x509 certificate, it complains its not RCC signed?


So then I switched to DES and tried the API example:

Code:
 

   String pword = "pass";
   String plain = "Convert me";
   byte[] text = plain.getBytes();
   byte[] secretKey = pword.getBytes();
   byte[] encrypted = null;
   sampleDESEncryption(secretKey,text,encrypted);

    // sampleDESEncryption
    private static int sampleDESEncryption( byte[] secretKey, byte[] plainText, byte[] cipherText )
        throws CryptoTokenException, CryptoUnsupportedOperationException
    {
        // Create a new DES key based on the 8 bytes in the secretKey array
        DESKey key = new DESKey( secretKey );
                
        // Create a new instance of the DES encryptor engine, passing in the newly 
        // created key
        DESEncryptorEngine engine = new DESEncryptorEngine( key );
        // Encrypt one block (8 bytes) of plainText into cipherText
        engine.encrypt( plainText, 0, cipherText, 0 );
    
        // Return the block size of the engine
        return engine.getBlockLength();
    }
But I dont understand how to get the cipher text back? I tried returning it ({cipherText} return encrypted = sampleDESEncryption(...)) and it complained it was null?

What I would love is a code example of importing and using a java created certificate for encryption. Or a simple des encryption decryption example.

Any ideas?

Cheers,
Chris.
Offline  
Old 05-15-2008, 06:08 PM   #2
pacred
New Member
 
Join Date: May 2008
Model: 8800
PIN: N/A
Carrier: tmobile
Posts: 4
Default

You could always roll your own.... Sometimes I need a small algorithm to embed in a microcontroller's firmware so I use TEA.

JavaScript Implementation of Block TEA Tiny Encryption Algorithm (© 2002-2005 Chris Veness)


Code:
//
// TEAencrypt: Use Corrected Block TEA to encrypt plaintext using password
//             (note plaintext & password must be strings not string objects)
//
// Return encrypted text as string
//
function TEAencrypt(plaintext, password)
{
    if (plaintext.length == 0) return('');  // nothing to encrypt
    // 'escape' plaintext so chars outside ISO-8859-1 work in single-byte packing, but keep
    // spaces as spaces (not '%20') so encrypted text doesn't grow too long (quick & dirty)
    var asciitext = escape(plaintext).replace(/%20/g,' ');
    var v = strToLongs(asciitext);  // convert string to array of longs
    if (v.length <= 1) v[1] = 0;  // algorithm doesn't work for n<2 so fudge by adding a null
    var k = strToLongs(password.slice(0,16));  // simply convert first 16 chars of password as key
    var n = v.length;

    var z = v[n-1], y = v[0], delta = 0x9E3779B9;
    var mx, e, q = Math.floor(6 + 52/n), sum = 0;

    while (q-- > 0) {  // 6 + 52/n operations gives between 6 & 32 mixes on each word
        sum += delta;
        e = sum>>>2 & 3;
        for (var p = 0; p < n; p++) {
            y = v[(p+1)%n];
            mx = (z>>>5 ^ y<<2) + (y>>>3 ^ z<<4) ^ (sum^y) + (k[p&3 ^ e] ^ z);
            z = v[p] += mx;
        }
    }

    var ciphertext = longsToStr(v);

    return escCtrlCh(ciphertext);
}

//
// TEAdecrypt: Use Corrected Block TEA to decrypt ciphertext using password
//
function TEAdecrypt(ciphertext, password)
{
    if (ciphertext.length == 0) return('');
    var v = strToLongs(unescCtrlCh(ciphertext));
    var k = strToLongs(password.slice(0,16)); 
    var n = v.length;

    var z = v[n-1], y = v[0], delta = 0x9E3779B9;
    var mx, e, q = Math.floor(6 + 52/n), sum = q*delta;

    while (sum != 0) {
        e = sum>>>2 & 3;
        for (var p = n-1; p >= 0; p--) {
            z = v[p>0 ? p-1 : n-1];
            mx = (z>>>5 ^ y<<2) + (y>>>3 ^ z<<4) ^ (sum^y) + (k[p&3 ^ e] ^ z);
            y = v[p] -= mx;
        }
        sum -= delta;
    }

    var plaintext = longsToStr(v);

    // strip trailing null chars resulting from filling 4-char blocks:
    plaintext = plaintext.replace(/\0+$/,'');

    return unescape(plaintext);
}


// supporting functions

function strToLongs(s) {  // convert string to array of longs, each containing 4 chars
    // note chars must be within ISO-8859-1 (with Unicode code-point < 256) to fit 4/long
    var l = new Array(Math.ceil(s.length/4));
    for (var i=0; i<l.length; i++) {
        // note little-endian encoding - endianness is irrelevant as long as 
        // it is the same in longsToStr() 
        l[i] = s.charCodeAt(i*4) + (s.charCodeAt(i*4+1)<<8) + 
               (s.charCodeAt(i*4+2)<<16) + (s.charCodeAt(i*4+3)<<24);
    }
    return l;  // note running off the end of the string generates nulls since 
}              // bitwise operators treat NaN as 0

function longsToStr(l) {  // convert array of longs back to string
    var a = new Array(l.length);
    for (var i=0; i<l.length; i++) {
        a[i] = String.fromCharCode(l[i] & 0xFF, l[i]>>>8 & 0xFF, 
                                   l[i]>>>16 & 0xFF, l[i]>>>24 & 0xFF);
    }
    return a.join('');  // use Array.join() rather than repeated string appends for efficiency
}

function escCtrlCh(str) {  // escape control chars etc which might cause problems with encrypted texts
    return str.replace(/[\0\t\n\v\f\r\xa0'"!]/g, function(c) { return '!' + c.charCodeAt(0) + '!'; });
}

function unescCtrlCh(str) {  // unescape potentially problematic nulls and control characters
    return str.replace(/!\d\d?\d?!/g, function(c) { return String.fromCharCode(c.slice(1,-1)); });
}
Offline  
Old 05-15-2008, 07:47 PM   #3
skynetchris
Knows Where the Search Button Is
 
Join Date: Apr 2008
Model: 7100T
PIN: N/A
Carrier: optus
Posts: 24
Default

Cool thanks, will try it out and let you know.
Offline  
Closed Thread


Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


DEC DIGITAL VINTAGE TU80 CONTROL PANEL 77-017654-F picture

DEC DIGITAL VINTAGE TU80 CONTROL PANEL 77-017654-F

$139.99



DEC DIGITAL VINTAGE RA80 Operator Control Panel 5414927 picture

DEC DIGITAL VINTAGE RA80 Operator Control Panel 5414927

$79.99



Lot of 7 Vintage CLARO-DEC Clarostat Decade Model 260 1-7 picture

Lot of 7 Vintage CLARO-DEC Clarostat Decade Model 260 1-7

$49.99



Original New DEC Digital DCJ11-AE 57-19400-09 Vintage CPU x 1pc picture

Original New DEC Digital DCJ11-AE 57-19400-09 Vintage CPU x 1pc

$100.00



Digital Equipment Corporation (DEC) VAX4000-400 Minicomputer picture

Digital Equipment Corporation (DEC) VAX4000-400 Minicomputer

$4450.00



Dec/Adac Corp. D4-10390 Rev 6 Model 1664ATTL Output Pulse Board 1983 (B16) picture

Dec/Adac Corp. D4-10390 Rev 6 Model 1664ATTL Output Pulse Board 1983 (B16)

$189.99







Copyright © 2004-2016 BlackBerryForums.com.
The names RIM © and BlackBerry © are registered Trademarks of BlackBerry Inc.