Skip to Main Content

Java Security

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Encryption without special charactors.

Kashif IftikharApr 26 2014

Hi Everyone,

I'm trying to encrypt my file names and folders names.

For this I'm using javax.crypto and sun.misc.BASE64Encoder packages with UTF8 Char-set for encrypting strings which will be used as file/folder names..

The problems is that encrypted string contain special characters like (/,\) and they cannot be used in file/folder names.

Please guide me how can i correct this code. I tried different character set along with sun.misc Encoders but they did not work.

import java.io.UnsupportedEncodingException;

import java.security.InvalidKeyException;

import java.security.NoSuchAlgorithmException;

import java.security.spec.KeySpec;

import javax.crypto.Cipher;

import javax.crypto.NoSuchPaddingException;

import javax.crypto.SecretKey;

import javax.crypto.SecretKeyFactory;

import javax.crypto.spec.DESKeySpec;

import javax.crypto.spec.DESedeKeySpec;

import sun.misc.BASE64Encoder;

import sun.misc.BASE64Decoder;

public class MyEnc

{

    public static final String DESEDE_ENCRYPTION_SCHEME = "DESede";

    public static final String DES_ENCRYPTION_SCHEME = "DES";

    public static final String            DEFAULT_ENCRYPTION_KEY    = "This is a fairly long phrase used to encrypt";

    public static final String encryptionKey = "012345678901234567890123456789";

    public static final String encryptionScheme = DESEDE_ENCRYPTION_SCHEME;

    private KeySpec                keySpec;

    private SecretKeyFactory    keyFactory;

    private Cipher                cipher;

    private static final String    UNICODE_FORMAT            = "UTF8";

    public MyEnc( )

            throws EncryptionException

    {

        if ( encryptionKey == null )

                throw new IllegalArgumentException( "encryption key was null" );

        if ( encryptionKey.trim().length() < 24 )

                throw new IllegalArgumentException(

                        "encryption key was less than 24 characters" );

        try

        {

            byte[] keyAsBytes = encryptionKey.getBytes( UNICODE_FORMAT );

            if ( encryptionScheme.equals( DESEDE_ENCRYPTION_SCHEME) )

            {

                keySpec = new DESedeKeySpec( keyAsBytes );

            }

            else if ( encryptionScheme.equals( DES_ENCRYPTION_SCHEME ) )

            {

                keySpec = new DESKeySpec( keyAsBytes );

            }

            else

            {

                throw new IllegalArgumentException( "Encryption scheme not supported: "

                                                    + encryptionScheme );

            }

            keyFactory = SecretKeyFactory.getInstance( encryptionScheme );

            cipher = Cipher.getInstance( encryptionScheme );

        }

        catch (InvalidKeyException e)

        {

            throw new EncryptionException( e );

        }

        catch (UnsupportedEncodingException e)

        {

            throw new EncryptionException( e );

        }

        catch (NoSuchAlgorithmException e)

        {

            throw new EncryptionException( e );

        }

        catch (NoSuchPaddingException e)

        {

            throw new EncryptionException( e );

        }

    }

    public String encrypt( String unencryptedString ) throws EncryptionException

    {

        if ( unencryptedString == null || unencryptedString.trim().length() == 0 )

                throw new IllegalArgumentException(

                        "unencrypted string was null or empty" );

        try

        {

            SecretKey key = keyFactory.generateSecret( keySpec );

            cipher.init( Cipher.ENCRYPT_MODE, key );

            byte[] cleartext = unencryptedString.getBytes( UNICODE_FORMAT );

            byte[] ciphertext = cipher.doFinal( cleartext );

            BASE64Encoder base64encoder = new BASE64Encoder();

            return base64encoder.encode( ciphertext );

        }

        catch (Exception e)

        {

            throw new EncryptionException( e );

        }

    }

    public String decrypt( String encryptedString ) throws EncryptionException

    {

        if ( encryptedString == null || encryptedString.trim().length() <= 0 )

                throw new IllegalArgumentException( "encrypted string was null or empty" );

        try

        {

            SecretKey key = keyFactory.generateSecret( keySpec );

            cipher.init( Cipher.DECRYPT_MODE, key );

            BASE64Decoder base64decoder = new BASE64Decoder();

            byte[] cleartext = base64decoder.decodeBuffer( encryptedString );

            byte[] ciphertext = cipher.doFinal( cleartext );

            return bytes2String( ciphertext );

        }

        catch (Exception e)

        {

            throw new EncryptionException( e );

        }

    }

    private static String bytes2String( byte[] bytes )

    {

        StringBuffer stringBuffer = new StringBuffer();

        for (int i = 0; i < bytes.length; i++)

        {

            stringBuffer.append( (char) bytes[i] );

        }

        return stringBuffer.toString();

    }

    public static class EncryptionException extends Exception

    {

        public EncryptionException( Throwable t )

        {

            super( t );

        }

    }

}

Comments

unknown-7404
Answer

I have read and watched videos regarding creating an Object of a class and calling its method in a different class. I'm still confused about how to properly do this. Using the code below can anyone explain how to properly call the objects method from my main.

Huh? You have NOT posted any 'main' or any 'objects method'.

If you need help with code you have to post the code.

The Java tutorials has dozens of trails on 'Classes and Objects': what they are, how to create them and how to use them.

https://docs.oracle.com/javase/tutorial/java/javaOO/classes.html

1. Create an instance of a class

2. call one or more of the public methods of that class

If the class has public static methods then you do NOT need to create an instance first.

I suggest you work your way thru those tutorials. They include WORKING example code.

Marked as Answer by 2801625 · Sep 27 2020
aJohny

As rp0428 suggested, please go through the tutorials first, add extra debug messages in the samples if needed, get an understanding how things works.

You have not given the full code, so we can't help much.

By looking at the content, it looks like you have written this in the Constructor. Refer the below link to understand about Constructors

https://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html

If the above piece of code is the constructor code, it will get executed when you create the instance of the class itself (with those number of parameters);

ex:= FileContentsObject fileContentsObject = new FileContentsObject( cachecName, lastModifiedTimeStamp,contents, fileName, lines);

I have used the same variable names as the ones defined in the class, which is not necessary. These variables has to be defined first.

Hope it helps.

Cheers

AJ

2801625

Thanks for the advice so far this info has proved to be extremely helpful.

1 - 3
Locked Post
New comments cannot be posted to this locked post.

Post Details

Locked on May 24 2014
Added on Apr 26 2014
0 comments
2,114 views