Encryption

Discussion in 'Java' started by Scooter, Nov 21, 2008.

  1. Scooter

    Scooter Guest

    I had another thread going about encryption but that thread was dying
    out, and I have a more specific issue this time. I should qualify this
    post by saying I'm very new to cryptography. Having said that, this
    code is bombing out with an "Illegal key size" when I try to "init" my
    cipher. I'm trying to create an ecryption key based off of a string,
    and initialize a Cipher with it. Then use that to encrypte/decrypt
    some string. And as I'd mentioned in my previous thread, this is the
    counter to a C# application that is already being used so I have to
    use AES/SHA256 and Base64. Not sure exactly what I'm doing [wrong]
    here.

    protected static Cipher m_objCrypt;
    protected static Cipher m_objDecrypt;

    try {
    m_objCrypt = Cipher.getInstance("AES/CBC/PKCS5Padding");
    m_objDecrypt = Cipher.getInstance("AES/CBC/PKCS5Padding");
    } catch (NoSuchAlgorithmException e) {

    // TODO Auto-generated catch block
    e.printStackTrace();

    } catch (NoSuchPaddingException e) {

    // TODO Auto-generated catch block
    e.printStackTrace();

    }


    MessageDigest sha256 = null;
    try {
    sha256 = MessageDigest.getInstance("SHA-256");
    } catch (NoSuchAlgorithmException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();

    }


    byte[] aesKey = sha256.digest("A Random String".toLowerCase
    ().getBytes
    ());

    // Sets up a 128 bit (16 byte) IV for CBC mode
    final int BLOCK_BYTES = 16;
    byte[] aesPaddedKey = new byte[BLOCK_BYTES];
    System.arraycopy(aesKey,0,aesPaddedKey,0,BLOCK_BYTES);
    sha256.reset();
    byte[] fullSHA = sha256.digest("3rfdfh6y-34rt-3rkl-9ijh-
    mg94kgjdhsg3".toLowerCase().getBytes());
    byte[] aesIV = new byte[BLOCK_BYTES];
    System.arraycopy(fullSHA, 0, aesIV, 0, BLOCK_BYTES);


    // Set up the IV and two cipher objects, one to encrypt and
    // one to decrypt:
    IvParameterSpec aesParameterSpec = new IvParameterSpec(aesIV);
    AlgorithmParameters aesParameters = AlgorithmParameters.getInstance
    ("AES");
    aesParameters.init(aesParameterSpec);

    SecretKeySpec aesKeySpec = new SecretKeySpec(aesPaddedKey,

    m_objCrypt.init(Cipher.ENCRYPT_MODE, aesKeySpec, aesParameters);
    m_objDecrypt.init(Cipher.DECRYPT_MODE, aesKeySpec, aesParameters);

    ....
    then later I have an encrypt and decrypt method
     
    Scooter, Nov 21, 2008
    #1
    1. Advertising

  2. Scooter

    Arne Vajhøj Guest

    Scooter wrote:
    > I had another thread going about encryption but that thread was dying
    > out, and I have a more specific issue this time. I should qualify this
    > post by saying I'm very new to cryptography. Having said that, this
    > code is bombing out with an "Illegal key size" when I try to "init" my
    > cipher. I'm trying to create an ecryption key based off of a string,
    > and initialize a Cipher with it. Then use that to encrypte/decrypt
    > some string. And as I'd mentioned in my previous thread, this is the
    > counter to a C# application that is already being used so I have to
    > use AES/SHA256 and Base64. Not sure exactly what I'm doing [wrong]
    > here.


    Could you try and post a compilable example that we can work with ?

    ....
    > SecretKeySpec aesKeySpec = new SecretKeySpec(aesPaddedKey,
    >
    > m_objCrypt.init(Cipher.ENCRYPT_MODE, aesKeySpec, aesParameters);
    > m_objDecrypt.init(Cipher.DECRYPT_MODE, aesKeySpec, aesParameters);

    ....

    There is definitely something missing after the comma !

    Arne
     
    Arne Vajhøj, Nov 22, 2008
    #2
    1. Advertising

  3. Scooter

    Arne Vajhøj Guest

    rossum wrote:
    > On Fri, 21 Nov 2008 13:25:54 -0800 (PST), Scooter
    > <> wrote:
    >> I had another thread going about encryption but that thread was dying
    >> out, and I have a more specific issue this time. I should qualify this
    >> post by saying I'm very new to cryptography. Having said that, this
    >> code is bombing out with an "Illegal key size" when I try to "init" my
    >> cipher. I'm trying to create an ecryption key based off of a string,
    >> and initialize a Cipher with it. Then use that to encrypte/decrypt
    >> some string. And as I'd mentioned in my previous thread, this is the
    >> counter to a C# application that is already being used so I have to
    >> use AES/SHA256 and Base64. Not sure exactly what I'm doing [wrong]
    >> here.


    >>byte[] aesKey = sha256.digest("A Random

    String".toLowerCase().getBytes());

    >>final int BLOCK_BYTES = 16;
    >>byte[] aesPaddedKey = new byte[BLOCK_BYTES];
    >>System.arraycopy(aesKey,0,aesPaddedKey,0,BLOCK_BYTES);


    >> SecretKeySpec aesKeySpec = new SecretKeySpec(aesPaddedKey,
    >>
    >> m_objCrypt.init(Cipher.ENCRYPT_MODE, aesKeySpec, aesParameters);
    >> m_objDecrypt.init(Cipher.DECRYPT_MODE, aesKeySpec, aesParameters);


    > If you are outside America then you may have a limited key size (40
    > bits IIRC) for your JCE due to American export laws. Try obtaining
    > code from an alternate provider outside America, such as Bouncy
    > Castle. Alternatively you can try to get a non-limited JCE from Sun.
    > See http://java.sun.com/javase/downloads/index_jdk5.jsp and look for
    > "JCE Unlimited Strength" in the Other Downloads section at the bottom
    > of the page.


    According to:

    http://java.sun.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html#AppC

    then 128 bits are standard today.

    And as far as I can see from the code above the key is only 128 bits.

    Arne

    PS: The latest of "Unlimited Strength Jurisdiction Policy" must be at:

    http://java.sun.com/javase/downloads/?intcmp=1281
     
    Arne Vajhøj, Nov 22, 2008
    #3
  4. Scooter

    Roedy Green Guest

    On Fri, 21 Nov 2008 13:25:54 -0800 (PST), Scooter
    <> wrote, quoted or indirectly quoted someone who
    said :

    >I had another thread going about encryption but that thread was dying
    >out, and I have a more specific issue this time. I should qualify this
    >post by saying I'm very new to cryptography. Having said that, this
    >code is bombing out with an "Illegal key size" when I try to "init" my
    >cipher. I'm trying to create an ecryption key based off of a string,
    >and initialize a Cipher with it. Then use that to encrypte/decrypt
    >some string. And as I'd mentioned in my previous thread, this is the
    >counter to a C# application that is already being used so I have to
    >use AES/SHA256 and Base64. Not sure exactly what I'm doing [wrong]
    >here.


    See http://mindprod.com/jgloss/aes.html
    http://mindprod.com/jgloss/md5.html

    for complete working programs that use AES and md5. Comparing them
    with your code may give you a hint.

    There is also the matter you need the JCE extension available only to
    North Americans in theory to use large keys.

    See http://mindprod.com/jgloss/jce.html

    --
    Roedy Green Canadian Mind Products
    http://mindprod.com
    Your old road is
    Rapidly agin'.
    Please get out of the new one
    If you can't lend your hand
    For the times they are a-changin'.
     
    Roedy Green, Nov 22, 2008
    #4
  5. Scooter

    Scooter Guest

    Someone asked for a compilable example, so here's the entire thing
    (and I'm in North America. Can't you tell from my accent) :

    ~~~~~~~~~~~~~~~~~~
    IQueryString.java
    ~~~~~~~~~~~~~~~~~~
    public interface IQueryString {
    int Count ();
    String QueryString ();
    void Append(String Tag, String Value);
    String Item(String Tag);
    Boolean Load(String QueryString);
    void Reset();
    void Update(String Tag, String Value);

    }

    ~~~~~~~~~~~~~~~~
    QueryString.java
    ~~~~~~~~~~~~~~~~
    import java.io.*;
    import java.util.*;
    import java.lang.StringBuilder;
    import java.security.*;
    import java.net.*;
    import javax.crypto.*;
    import javax.crypto.spec.*;

    import
    com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;
    import com.sun.org.apache.xml.internal.security.utils.Base64;

    public class QueryString implements IQueryString {

    QueryString () throws Exception{

    m_objState = new Hashtable<String, String>();

    try {
    m_objCrypt = Cipher.getInstance("AES/CBC/PKCS5Padding");
    m_objDecrypt = Cipher.getInstance("AES/CBC/PKCS5Padding");

    } catch (NoSuchAlgorithmException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (NoSuchPaddingException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    MessageDigest sha256 = null;
    try {
    sha256 = MessageDigest.getInstance("SHA-256");
    } catch (NoSuchAlgorithmException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    byte[] theTextToDigestAsBytes =ComputeHash("A Random
    String".toLowerCase()).getBytes();
    sha256.update(theTextToDigestAsBytes);

    byte[] aesKey = sha256.digest();
    //printhash(aesKey);
    System.out.println("Digest is " + aesKey.length + " bytes long");

    // Sets up a 128 bit (16 byte) IV for CBC mode
    final int BLOCK_BYTES = 16;

    sha256.reset();
    byte[] fullSHA = sha256.digest(ComputeHash("3rfdfh6y-34rt-3rkl-9ijh-
    mg94kgjdhsg3".toLowerCase()).getBytes());
    //printhash(fullSHA);
    byte[] aesIV = new byte[BLOCK_BYTES];
    System.arraycopy(fullSHA, 0, aesIV, 0, BLOCK_BYTES);

    // Set up the IV and two cipher objects, one to encrypt
    and
    // one to decrypt:
    IvParameterSpec aesParameterSpec = new IvParameterSpec
    (aesIV);
    AlgorithmParameters aesParameters =
    AlgorithmParameters.getInstance("AES");
    aesParameters.init(aesParameterSpec);

    SecretKeySpec aesKeySpec = new SecretKeySpec(aesKey,
    0,aesKey.length,"AES");




    System.out.println("before the init");
    try
    {
    m_objCrypt.init(Cipher.ENCRYPT_MODE, aesKeySpec, aesParameters);
    m_objDecrypt.init(Cipher.DECRYPT_MODE, aesKeySpec, aesParameters);
    }
    catch (Exception e) {
    System.out.println(e.getMessage());
    }


    }

    public int Count() {
    return m_objState.size();
    }


    public String QueryString() {

    StringBuilder stbRetval = new StringBuilder();
    stbRetval.append(URL_START);
    stbRetval.append(HASH_IDENTIFIER);
    String strState = StateToLineFormat();
    stbRetval.append(ComputeHash(strState));
    stbRetval.append(VALUE_IDENTIFIER);
    stbRetval.append(EncryptValue(strState));
    if (stbRetval.length() >= MAX_QUERY_LENGTH)
    {
    try {
    throw new Exception();
    } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    return stbRetval.toString();
    }


    public void Append(String Tag, String Value) {
    if (null == Tag)
    {
    try {
    throw new Exception();
    } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    if (null == Value)
    {
    try {
    throw new Exception();
    } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    m_objState.put(Tag, Value);
    }

    public String Item(String Tag) {
    String strValue = null;
    if (m_objState.containsKey(Tag))
    {
    strValue = m_objState.get(Tag);
    }
    else
    {
    System.out.println("Can't find it");
    }
    return strValue;
    }


    public Boolean Load(String QueryString) {
    Boolean bolRetval = true;

    if (QueryString.length() >= MAX_QUERY_LENGTH)
    {
    try {
    throw new Exception();
    } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }

    if (QueryString.contains("&T="))
    {
    try {
    throw new Exception();
    } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }

    try
    {
    if (false == QueryString.contains(VALUE_IDENTIFIER))
    {
    try {
    throw new Exception();
    } catch (Exception e) {
    e.printStackTrace();
    }

    }
    if (HASH_IDENTIFIER != QueryString.substring
    (0,HASH_IDENTIFIER.length()))
    {
    try {
    throw new Exception();
    } catch (Exception e) {
    e.printStackTrace();
    }

    }
    String strClientHash = QueryString.substring(HASH_IDENTIFIER.length
    (), HASH_LENGTH);
    String strClientValue = QueryString.substring(
    (HASH_IDENTIFIER.length() + HASH_LENGTH + VALUE_IDENTIFIER.length
    ())
    );

    String strDecState = this.DecryptValue( URLDecoder.decode
    (strClientValue,"UTF-8"));
    String strCompatHash = this.ComputeHash(strDecState);

    if (false == strCompatHash.equals(strClientHash))
    {
    throw new Exception();
    }
    String [] astrValues = strDecState.split( ";");

    for (String strRawValue : astrValues)
    {
    if (strRawValue.length() > 0)
    {
    String[] astrReal = strRawValue.split("=");
    m_objState.put(astrReal[0], this.LineDecode(astrReal[1]));
    }
    }
    }
    catch (Exception ignoreTillWeGetLogLog)
    {
    bolRetval = false;
    }
    return bolRetval;
    }



    public void Reset() {
    m_objState.clear();
    }


    public void Update(String Tag, String Value) {
    if (null == Tag)
    {
    try {
    throw new Exception();
    } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }

    m_objState.remove(Tag);

    this.Append(Tag, Value);

    }
    public String ComputeHash(String ValueStream) {

    if (null == ValueStream)
    {
    try {
    throw new Exception();
    } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    MessageDigest sha256 = null;
    try {
    sha256 = MessageDigest.getInstance("SHA-256");
    } catch (NoSuchAlgorithmException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    byte[] SHA256HASH = sha256.digest(ValueStream.getBytes());

    return stringhash(SHA256HASH);
    }

    public String EncryptValue(String Value) {

    String returnValue = null;
    if (Value.length() >= MAX_QUERY_LENGTH)
    {
    try {
    throw new Exception();
    } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }

    byte[] byaRawText = null;
    try {
    byaRawText = Value.getBytes("US-ASCII");
    } catch (UnsupportedEncodingException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
    }
    byte[] byaCipherText = null;
    try {
    byaCipherText = m_objCrypt.doFinal(byaRawText, 0,
    byaRawText.length);
    } catch (IllegalBlockSizeException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (BadPaddingException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    returnValue = b64encode(byaCipherText);
    return returnValue;

    }

    public String DecryptValue(String EncryptedValue) {

    if (EncryptedValue.length() >= MAX_QUERY_LENGTH) {
    try {
    throw new Exception();
    } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    byte[] abyDecText = null;
    try
    {
    System.out.println("before the decode");
    byte[]abyFromBase64=b64decode(EncryptedValue);

    System.out.println("before the buffer");
    abyDecText = m_objDecrypt.doFinal
    (abyFromBase64,0,abyFromBase64.length);

    System.out.println("before the queryString");

    }
    catch (Exception e)
    {
    System.out.println(e.getMessage());
    }


    String returnValue = null;
    try {
    returnValue = new String(abyDecText,"US-ASCII");
    } catch (UnsupportedEncodingException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    return returnValue;


    }

    /*
    public static String b64encodeold(byte[] b) throws
    MessagingException,

    IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    OutputStream b64os = MimeUtility.encode(baos, "base64");
    b64os.write(b);
    b64os.close();
    System.out.println (new String(baos.toByteArray()));
    return new String(baos.toByteArray());
    }
    */

    public static String b64encode(byte[] bIn)
    {
    String base64Encoded = new String(Base64.encode(bIn));
    return base64Encoded;
    }

    /*
    public static byte[] b64decodeold(String s) throws
    MessagingException, IOException {
    ByteArrayInputStream bais = new ByteArrayInputStream
    (s.getBytes());
    InputStream b64is = MimeUtility.decode(bais, "Base64");
    byte[] tmp = new byte[s.length()];
    int n = b64is.read(tmp);
    byte[] res = new byte[n];
    System.arraycopy(tmp, 0, res, 0, n);
    System.out.println("decode length:"+res.length);
    System.out.println("decode:"+byteToString(res));
    return res;
    }
    */

    public static byte[] b64decode(String s) {
    byte[] base64decoded = null;
    try {
    base64decoded = Base64.decode(s);
    } catch (Base64DecodingException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    return base64decoded;
    }

    protected static String byteToString(byte[] myBA){
    String btoString = new String(myBA);
    return btoString;
    }

    protected static void listProviders ()
    {
    Provider[] provider = Security.getProviders();
    for (int i = 0; i< provider.length; i++) {
    System.out.println("Name : " + provider.getName());
    System.out.println(" Info : " + provider.getServices());
    System.out.println
    ("---------------------------------------------------------------------------");
    }
    }

    protected static void printhash (byte hashdigest[])
    {
    StringBuffer hexString = new StringBuffer();
    for (int i=0;i<hashdigest.length;i++) {
    String hex = Integer.toHexString(0xFF & hashdigest);
    if(hex.length()==1) hexString.append('0');
    hexString.append(hex);
    }

    System.out.println("HASH: " +hexString.toString());
    }
    protected String stringhash (byte hashdigest[])
    {
    StringBuffer hexString = new StringBuffer();
    for (int i=0;i<hashdigest.length;i++) {
    String hex = Integer.toHexString(0xFF & hashdigest);
    if(hex.length()==1) hexString.append('0');
    hexString.append(hex);
    }

    return hexString.toString();



    }
    protected String LineDecode(String Value)
    {

    String strRetval = Value;

    strRetval = strRetval.replace("%3D", "=");
    strRetval = strRetval.replace("%3B", ";");
    strRetval = strRetval.replace("%25", "%");

    return strRetval;

    }

    protected String LineEncode(String Value)
    {

    String strRetval = Value;

    strRetval = strRetval.replace("%", "%25");
    strRetval = strRetval.replace(";", "%3B");
    strRetval = strRetval.replace("=", "%3D");

    return strRetval;

    }

    private String StateToLineFormat() {
    String strReturn = "";

    Enumeration<String> keys = m_objState.keys();
    while ( keys.hasMoreElements() )
    {
    String key = (String)keys.nextElement();

    strReturn += key + "=" + this.LineEncode(m_objState.get(key)) +
    ";";
    }

    return strReturn;

    }

    protected static Cipher m_objCrypt;
    protected static Cipher m_objDecrypt;
    protected Hashtable<String,String> m_objState;
    protected static int MAX_QUERY_LENGTH = 2048;
    protected String HASH_IDENTIFIER = "I=";
    protected int HASH_LENGTH = 64;
    protected String VALUE_IDENTIFIER = "&V=";
    protected String URL_START = "?";

    }


    ~~~~~~~~~~~~~~~~~~~~~
    QueryStringTest.java
    ~~~~~~~~~~~~~~~~~~~~~
    import java.io.UnsupportedEncodingException;
    import junit.framework.Assert;
    import org.junit.Before;
    import org.junit.Test;

    public class QueryStringTest {

    public QueryString m_queryString;

    @Before
    public void setUp(){
    try {
    m_queryString = new QueryString();
    } catch (Exception e) {
    System.out.println(e.getMessage()); }
    }

    @Test
    public void TestBlankValueComputeHashEqualsDefaultSha256()
    {
    try {
    Assert.assertEquals
    ("E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855",
    m_queryString.ComputeHash("").toUpperCase());
    } catch (Exception e) {
    System.out.println(e.getMessage());
    }

    }

    @Test
    public void TestAppendValue() {
    try {
    m_queryString.Append("Tag123","123");
    } catch (Exception e) {
    System.out.println(e.getMessage());
    }
    }

    @Test
    public void testCount() {
    m_queryString.Reset();
    m_queryString.Append("Tag123","123");
    Assert.assertEquals(1, m_queryString.Count());
    }


    @Test
    public void testAppend() {
    m_queryString.Reset();
    m_queryString.Append("Tag123","123");
    Assert.assertEquals(1,m_queryString.Count());
    }

    @Test
    public void testItem() {
    m_queryString.Reset();
    m_queryString.Append("Tag123","123");
    Assert.assertEquals("123",m_queryString.Item("Tag123"));
    }

    @Test
    public void testReset() {
    m_queryString.Reset();
    m_queryString.Append("Tag123","123");
    Assert.assertEquals(1, m_queryString.Count());
    m_queryString.Reset();
    Assert.assertEquals(0, m_queryString.Count());
    }

    @Test
    public void testUpdate() {
    m_queryString.Update("Tag123","123");
    m_queryString.Update("Tag123","456");
    Assert.assertEquals("456",m_queryString.Item("Tag123"));
    }

    @Test
    public void testComputeHash() {
    Assert.assertEquals
    ("fa3444fa161e2610e4c1273ccbc572f5091de6550b53581d5044ec80b1ff4064",m_queryString.ComputeHash
    ("A Random String"));
    }

    @Test
    public void testEncryptValue() {
    Assert.assertEquals("jU5JuAVxi3isKWf6SJ9CJA==",
    m_queryString.EncryptValue("Secret"));
    }

    @Test
    public void testDecryptValue() {
    Assert.assertEquals("Secret", m_queryString.DecryptValue
    ("jU5JuAVxi3isKWf6SJ9CJA=="));
    }

    @Test
    public void testBase64Encode() throws UnsupportedEncodingException {
    byte[] btoEncode = "EncodeMe".getBytes("US-ASCII");
    Assert.assertEquals("RW5jb2RlTWU=", m_queryString.b64encode
    (btoEncode));
    }

    @Test
    public void testBase64Decode() {
    Assert.assertEquals("EncodeMe", new String(m_queryString.b64decode
    ("RW5jb2RlTWU=")));
    }
    }
     
    Scooter, Nov 24, 2008
    #5
  6. Scooter wrote:
    > (and I'm in North America. Can't you tell from my accent) :


    Ah yes - Guatemala! No, maybe Netherlands Antilles?

    --
    RGB
     
    RedGrittyBrick, Nov 24, 2008
    #6
  7. In article <492ad965$0$1342$>,
    RedGrittyBrick <> wrote:

    > Scooter wrote:
    > > (and I'm in North America. Can't you tell from my accent) :

    >
    > Ah yes - Guatemala! No, maybe Netherlands Antilles?


    Well, someplace where they've forgotten the main.

    --
    John B. Matthews
    trashgod at gmail dot com
    http://home.roadrunner.com/~jbmatthews/
     
    John B. Matthews, Nov 24, 2008
    #7
  8. On Nov 25, 4:06 am, "John B. Matthews" <> wrote:
    > In article <492ad965$0$1342$>,
    >
    >  RedGrittyBrick <> wrote:
    > > Scooter wrote:
    > > > (and I'm in North America. Can't you tell from my accent) :

    >
    > > Ah yes - Guatemala! No, maybe Netherlands Antilles?

    >
    > Well, someplace where they've forgotten the main.
    >
    > --
    > John B. Matthews
    > trashgod at gmail dot comhttp://home.roadrunner.com/~jbmatthews/


    Scooter, did you happen to notice how Roedy
    managed a self contained example, consisting
    of one class of less than 200 lines?

    OTOH, your example had three classes, one of
    which was over 450 lines, and was not self
    contained.

    You seem to enjoy making it hard for people to
    help you.

    I recommend preparing a very specific form of
    example - an SSCCE. More details here..
    <http://pscode.org/sscce.html>

    --
    Andrew Thompson
    http://pscode.org/
     
    Andrew Thompson, Nov 24, 2008
    #8
  9. Scooter

    Scooter Guest

    Ok sorry for the boneheaded move. I promise I don't enjoy making it
    hard for people to help me. I think the frustration is getting the
    best of me. Following isn't as short as I would like it to be but
    because I'm stumped on this particular issue from start to finish I
    feel the need to post as much as possible. But this is self-contained
    at least, no interfaces or Junit tests. All the code in the main is
    the stuff I'm having the problem with. The two additional methods are
    just included so it will work:

    import java.security.*;
    import java.security.spec.InvalidParameterSpecException;
    import javax.crypto.*;
    import javax.crypto.spec.*;

    public class SSCCEE {

    public static void main(String[] args) throws
    NoSuchAlgorithmException, InvalidParameterSpecException {
    Cipher m_objCrypt = null;
    Cipher m_objDecrypt = null;
    try {
    m_objCrypt = Cipher.getInstance("AES/CBC/
    PKCS5Padding");
    m_objDecrypt = Cipher.getInstance("AES/CBC/
    PKCS5Padding");
    } catch (NoSuchAlgorithmException e) {
    e.printStackTrace();
    } catch (NoSuchPaddingException e) {
    e.printStackTrace();
    }
    MessageDigest sha256 = null;
    try {
    sha256 = MessageDigest.getInstance("SHA-256");
    } catch (NoSuchAlgorithmException e) {
    e.printStackTrace();
    }
    byte[] theTextToDigestAsBytes =ComputeHash("A Random
    String".toLowerCase()).getBytes();
    sha256.update(theTextToDigestAsBytes);
    byte[] aesKey = sha256.digest();
    // Sets up a 128 bit (16 byte) IV for CBC mode
    final int BLOCK_BYTES = 16;
    sha256.reset();
    byte[] fullSHA = sha256.digest(ComputeHash
    ("3rfdfh6y-34rt-3rkl-9ijh-mg94kgjdhsg3".toLowerCase()).getBytes());
    byte[] aesIV = new byte[BLOCK_BYTES];
    System.arraycopy(fullSHA, 0, aesIV, 0, BLOCK_BYTES);

    // Set up the IV and two cipher objects, one to encrypt and
    // one to decrypt:
    IvParameterSpec aesParameterSpec = new IvParameterSpec
    (aesIV);
    AlgorithmParameters aesParameters =
    AlgorithmParameters.getInstance("AES");
    aesParameters.init(aesParameterSpec);
    SecretKeySpec aesKeySpec = new SecretKeySpec(aesKey,
    0,aesKey.length,"AES");
    try
    {
    m_objCrypt.init(Cipher.ENCRYPT_MODE, aesKeySpec,
    aesParameters);
    m_objDecrypt.init(Cipher.DECRYPT_MODE, aesKeySpec,
    aesParameters);
    } catch (Exception e) {
    System.out.println(e.getMessage());
    }
    }

    public static String ComputeHash(String ValueStream) {


    if (null == ValueStream)
    {
    try {
    throw new Exception();
    } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    MessageDigest sha256 = null;
    try {
    sha256 = MessageDigest.getInstance("SHA-256");
    } catch (NoSuchAlgorithmException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    byte[] SHA256HASH = sha256.digest(ValueStream.getBytes());


    return stringhash(SHA256HASH);
    }
    protected static String stringhash (byte hashdigest[])
    {
    StringBuffer hexString = new StringBuffer();
    for (int i=0;i<hashdigest.length;i++) {
    String hex = Integer.toHexString(0xFF & hashdigest);
    if(hex.length()==1) hexString.append('0');
    hexString.append(hex);
    }

    return hexString.toString();

    }


    }
     
    Scooter, Nov 24, 2008
    #9
  10. Scooter

    Lew Guest

    Scooter wrote:
    >>> (and I'm in North America. Can't you tell from my accent) :


    RedGrittyBrick wrote:
    >> Ah yes - Guatemala! No, maybe Netherlands Antilles?


    John B. Matthews wrote:
    > Well, someplace where they've forgotten the main.


    Nice pun.

    --
    Lew
     
    Lew, Nov 25, 2008
    #10
  11. In article <>,
    rossum <> wrote:

    > On Mon, 24 Nov 2008 10:31:37 -0800 (PST), Scooter
    > <> wrote:
    >
    > >Ok sorry for the boneheaded move. I promise I don't enjoy making it
    > >hard for people to help me. I think the frustration is getting the
    > >best of me. Following isn't as short as I would like it to be but
    > >because I'm stumped on this particular issue from start to finish I
    > >feel the need to post as much as possible. But this is self-contained
    > >at least, no interfaces or Junit tests. All the code in the main is
    > >the stuff I'm having the problem with. The two additional methods are
    > >just included so it will work:

    >
    > [snip]
    >
    > > // Set up the IV and two cipher objects, one to encrypt and
    > > // one to decrypt:
    > > IvParameterSpec aesParameterSpec = new IvParameterSpec
    > >(aesIV);
    > > AlgorithmParameters aesParameters =
    > >AlgorithmParameters.getInstance("AES");
    > > aesParameters.init(aesParameterSpec);
    > > SecretKeySpec aesKeySpec = new SecretKeySpec(aesKey,
    > >0,aesKey.length,"AES");

    >
    > It looks like the Sun AES implementation does not like 256 bit keys.
    > It seems to run OK if you give it a 128 bit key:
    >
    > SecretKeySpec aesKeySpec = new SecretKeySpec(aesKey, 0,
    > aesKey.length / 2, "AES");
    > ^^^


    I see no errors on Java 1.5.0_16, either way. Might this be a regression?

    [Or possibly another boat I missed.]

    --
    John B. Matthews
    trashgod at gmail dot com
    http://home.roadrunner.com/~jbmatthews/
     
    John B. Matthews, Nov 25, 2008
    #11
  12. Scooter

    Scooter Guest

    >
    > It looks like the Sun AES implementation does not like 256 bit keys.
    > It seems to run OK if you give it a 128 bit key:
    >
    >   SecretKeySpec aesKeySpec = new SecretKeySpec(aesKey, 0,
    >      aesKey.length / 2, "AES");
    >                    ^^^


    YES!!! This was the issue. I still needed at 256 bit key but this got
    me going in the right direction. I downloaded the Unlimited Strength
    Jurisdiction Policy from Sun and then my app started working as is.

    Now I can head off for Thanksgiving with no worries.
     
    Scooter, Nov 25, 2008
    #12
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Robert Vabo

    Encryption

    Robert Vabo, Oct 8, 2003, in forum: ASP .Net
    Replies:
    1
    Views:
    1,289
    Ed Kaim [MSFT]
    Oct 14, 2003
  2. abhinav

    encryption algorithms

    abhinav, Dec 26, 2004, in forum: VHDL
    Replies:
    2
    Views:
    652
  3. Guenther Sohler

    Encryption Problem

    Guenther Sohler, Oct 17, 2003, in forum: Perl
    Replies:
    1
    Views:
    508
    Jim Gibson
    Oct 20, 2003
  4. Kelvin
    Replies:
    2
    Views:
    592
    Andrew Balmos (abalmos)
    Nov 9, 2004
  5. Acebravo

    About Encryption Question

    Acebravo, Mar 28, 2005, in forum: Perl
    Replies:
    1
    Views:
    2,707
    Jürgen Exner
    Mar 28, 2005
Loading...

Share This Page