Guía de desarrollo

Local Navigation

Ejemplo de código: implementación de cifrado

El siguiente ejemplo de código utiliza Triple DES, un algoritmo simétrico de cifrado de claves. La RIM Cryptographic API simplifica el uso de Triple DES al cifrar y descifrar mensajes.

import java.io.*;
import net.rim.device.api.crypto.*;
import net.rim.device.api.util.*;
import net.rim.device.api.ui.*;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.container.*;
import net.rim.device.api.util.*;
public class EncodeDecodeString extends UiApplication implements FieldChangeListener
{
    private ButtonField _encrypt_button;
    private ButtonField _decrypt_button;
    private TripleDESKey _key;
    private TextField _edit_input_string;
    public static void main( String[] args )
    {
        EncodeDecodeString theApp = new EncodeDecodeString();
        theApp.enterEventDispatcher();
    }
    public void fieldChanged(Field field, int context)
    {
        String strCurrentMessage = _edit_input_string.getText();
        if(field == _encrypt_button)
        {
            _edit_input_string.setText(encrypt(strCurrentMessage));
        }
        else
        {
            _edit_input_string.setText(decrypt(strCurrentMessage));
        }
    }
    public EncodeDecodeString()
    {
        MainScreen screen = new MainScreen();
        screen.setTitle(new LabelField("Crypto Demo", 
               LabelField.ELLIPSIS | LabelField.USE_ALL_WIDTH));
        _edit_input_string = new BasicEditField("Message:", 
               null, 256, BasicEditField.FILTER_DEFAULT);
        screen.add(_edit_input_string);
        _encrypt_button = new ButtonField("Encrypt",ButtonField.CONSUME_CLICK);
        _encrypt_button.setChangeListener(this);
        screen.add(_encrypt_button);
        _decrypt_button = new ButtonField("Decrypt");
        _decrypt_button.setChangeListener(this);
        screen.add(_decrypt_button);
        pushScreen(screen);
    }
    public String encrypt(String plaintext)
    {
        try 
        {
            _key = new TripleDESKey();
            TripleDESEncryptorEngine encryptionEngine = 
                new TripleDESEncryptorEngine(_key);
            // In most cases, the data to encrypt will not fit into the block
            // length of a cipher. When that happens, use a padding algorithm
            // to pad out the last block. This uses PKCS5 to do the padding.
            PKCS5FormatterEngine formatterEngine = new PKCS5FormatterEngine( 
                  encryptionEngine );
            // Use the byte array output stream to catch the encrypted information.
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            // Create a block encryptor to help use the triple DES engine.
            BlockEncryptor encryptor = new BlockEncryptor( formatterEngine, 
                  outputStream );
            // Encrypt the data.
            encryptor.write( plaintext.getBytes() );
            // Close the stream. This forces the extra bytes to be padded out if 
            // there were not enough bytes to fill all of the blocks.
            encryptor.close();
            // Get the encrypted data.
            byte[] encryptedData = outputStream.toByteArray();
            String strEncrypted = new String(encryptedData);
            return(strEncrypted);
        } 
        catch( CryptoTokenException e ) 
        {
            System.out.println(e.toString());
        } 
        catch (CryptoUnsupportedOperationException e) 
        {
            System.out.println(e.toString());
        } 
        catch( IOException e ) 
        {
            System.out.println(e.toString());
        }
        return "error";
    }
    public String decrypt(String ciphertext)
    {
            try
            {
            // Perform the decryption. Since this is a symmetric algorithm, 
            // use the same key as before.
            TripleDESDecryptorEngine decryptorEngine = 
                    new TripleDESDecryptorEngine(_key);
            // Create the unformatter engine to remove padding bytes.
            PKCS5UnformatterEngine unformatterEngine = 
                    new PKCS5UnformatterEngine( decryptorEngine );
            // Set up an input stream to hand the encrypted data to the 
            // block decryptor.
            ByteArrayInputStream inputStream = 
                    new ByteArrayInputStream( ciphertext.getBytes() );
            // Create the block decryptor passing in the unformatter engine and the 
            // encrypted data.
            BlockDecryptor decryptor = 
                    new BlockDecryptor( unformatterEngine, inputStream );
            // Next, read from the stream. This example reads the data 10 bytes 
            // at a time and then adds that new data to the decryptedData array. 
            // For efficiency in a real situation, you should use a value
            // larger than 10. This example uses a small value to demonstrate 
            // several iterations through the loop.
            byte[] temp = new byte[10];
            DataBuffer db = new DataBuffer();
            for( ;; ) 
            {
                int bytesRead = decryptor.read( temp );
                if( bytesRead <= 0 )
                {
                    // No more information to read, so leave loop.
                    break;
                }
                db.write(temp, 0, bytesRead);
            }
            // Make sure that the decrypted data is the same as the data  
            // that was passed into the encryptor.
            byte[] decryptedData = db.toArray();
            String strDecrypted = new String(decryptedData);
            return(strDecrypted);         
        } 
        catch( CryptoTokenException e ) 
        {
            System.out.println(e.toString());
        } 
        catch (CryptoUnsupportedOperationException e) 
        {
            System.out.println(e.toString());
        } 
        catch( IOException e ) 
        {
            System.out.println(e.toString());
        }
        return "error";
   }
}

¿Le ha resultado útil esta información? Envíenos sus comentarios.