# Java Kryptographie ( AES oder 3DES )



## daslicht (13. Apr 2009)

Hallo,

ich stelle gerade den Backend einer Flex eCommerce Lösung von PHP auf Java(BlazeDS) um.

Bisher verwende ich 3des mit php welches auch relativ einfach ist.

Ich versuche jetzt diese Verschlüsselung in Java zu lösen doch bisher nur mir wenig 

Erfolg. Meine Funde auf Google sind alle zu komplex für den Anfang. 

Ein Beispiel welches einen String ver-/ und entschlüsselt hilft mir hier mit Sicherheit weiter.

Grüße
dl

So weit bin ich, jetzt brauche ich nbur noch den "key" irgendwie sichern

```
package security;


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


public class AES {

  public static void main(String[] args) throws Exception 
  {
    String dataToEncrypt="My secret Data";

    // Get the KeyGenerator
    KeyGenerator kgen = KeyGenerator.getInstance("AES");
    kgen.init(128); // 192 and 256 bits may not be available

    // Generate the secret key specs.
    SecretKey skey = kgen.generateKey();
    byte[] raw = skey.getEncoded();
    SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");

    // Instantiate the cipher
    Cipher cipher = Cipher.getInstance("AES");

    //encrypt **********************************************************************
    cipher.init( Cipher.ENCRYPT_MODE, skeySpec );
    byte[] encrypted = cipher.doFinal( dataToEncrypt.getBytes() );

    String encryptedString = new String( encrypted );
    System.out.println("Encrypted string: " + encryptedString );
    
    //decrypt **********************************************************************
    cipher.init(Cipher.DECRYPT_MODE, skeySpec);
    byte[] decrypted = cipher.doFinal(encrypted);
    
    String decryptedString = new String( decrypted );
    System.out.println("Decrypted string: " + decryptedString );
  }
}
```


----------



## Empire Phoenix (14. Apr 2009)

Wenn du mti sichern Speicher meinst, dann guck dir zb. Printstream an.

Wennes dir jedoch darum geht aus den byte[] einen String aus normalen Zeichen zu erstellen, hilft dir diese Klasse evtl weiter:


```
package src;


public class HexString {
	public static String stringToHex(String s)
	{
		byte[] stringBytes = s.getBytes();
		return HexString.bufferToHex(stringBytes);
	}

	public static String bufferToHex(byte buffer[])
	{
		return HexString.bufferToHex(buffer, 0, buffer.length);
	}

	public static String bufferToHex(byte buffer[], int startOffset, int length)
	{
		StringBuffer hexString = new StringBuffer(2*length);
		int endOffset = startOffset + length;
		for (int i=startOffset; i<endOffset; i++)
			HexString.appendHexPair(buffer[i], hexString);
		return hexString.toString();
    }

	public static String hexToString(String hexString) throws NumberFormatException
	{
		byte[] bytes = HexString.hexToBuffer(hexString);
		return new String(bytes);
	}

	public static byte[] hexToBuffer(String hexString) throws NumberFormatException
	{
		int length = hexString.length();
		byte[] buffer = new byte[(length+1)/2];
		boolean evenByte = true;
		byte nextByte = 0;
		int bufferOffset = 0;

		if ((length%2)==1)
			evenByte = false;
		for (int i=0; i<length; i++) {
			char c = hexString.charAt(i);
			int nibble;
			if ((c>='0')&&(c<='9'))
				nibble = c - '0';
			else if ((c>='A')&&(c<='F'))
				nibble = c - 'A' + 0x0A;
			else if ((c>='a')&&(c<='f'))
				nibble = c - 'a' + 0x0A;
			else throw new NumberFormatException("Invalid hex digit '"+c+"'.");
			if (evenByte) {
				nextByte = (byte)(nibble<<4);
			} else {
				nextByte += (byte)nibble;
				buffer[bufferOffset++] = nextByte;
			}
			evenByte = !evenByte;
        }
		return buffer;
	}
		
	private static void appendHexPair(byte b, StringBuffer hexString)
	{
		char highNibble = kHexChars[(b&0xF0)>>4];
		char lowNibble = kHexChars[b&0x0F];
		hexString.append(highNibble);
		hexString.append(lowNibble);
	}
	private static final char kHexChars[] = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
}
```


----------



## daslicht (14. Apr 2009)

Vielen Dank für die Antwort,
teste ich gleich mal aus.

Ich habe das jetzt einfach so gelöst, siehst Du iregndwelche Nachteile / Schwachstellen?

```
package security;


import java.security.*;
import java.security.spec.InvalidKeySpecException;

import javax.crypto.*;
import javax.crypto.spec.*;
import java.io.*;

/**
* This program generates a AES key, retrieves its raw bytes, and
* then reinstantiates a AES key from the key bytes.
* The reinstantiated key is used to initialize a AES cipher for
* encryption and decryption.
*/

public class AES {

  byte[] rawKey = null; 
  byte[] encryptedData = null;

  public void saveKeyFile() throws 	IOException,
  									NoSuchAlgorithmException, 
  									InvalidKeyException,
  									InvalidKeySpecException
  {
	  // Get the KeyGenerator
	  KeyGenerator kgen = KeyGenerator.getInstance("AES");
	  kgen.init(128); // 192 and 256 bits may not be available
	  
	  // Generate the secret key specs.
	  SecretKey skey = kgen.generateKey();
	  byte[] raw = skey.getEncoded();
	  
	  File f = new File("key"); //file to write
	  
	  // Write the raw key to the file
	  FileOutputStream out = new FileOutputStream(f);
	  out.write(raw);
	  out.close();
  }
  
  public void readKeyFile() throws 	IOException,
									NoSuchAlgorithmException, 
									InvalidKeyException,
									InvalidKeySpecException
  {
	  File f = new File("key"); //file to read
	 
	  // Read the raw bytes from the keyfile
	  DataInputStream in = new DataInputStream( new FileInputStream(f) );
	  rawKey = new byte[(int) f.length()];
	  in.readFully( rawKey );
	  in.close();
  }
  
  public void encrypt() throws Exception
  {
	  String dataToEncrypt="My secret Data";
	  SecretKeySpec skeySpec = new SecretKeySpec(rawKey, "AES");
	// Instantiate the cipher
	    Cipher cipher = Cipher.getInstance("AES");
	  
	    //encrypt **********************************************************************
	    cipher.init( Cipher.ENCRYPT_MODE, skeySpec );
	    byte[] encrypted = cipher.doFinal( dataToEncrypt.getBytes() );
	    
	    String encryptedString = new String( encrypted );
	    System.out.println("Encrypted string: " + encryptedString ); 
	    decrypt( encrypted );
  }
  
  public void decrypt(byte[] toDecrypt) throws Exception
  {
	 
	  SecretKeySpec skeySpec = new SecretKeySpec(rawKey, "AES");
	// Instantiate the cipher
	    Cipher cipher = Cipher.getInstance("AES");
	    
	    //decrypt **********************************************************************
	    cipher.init(Cipher.DECRYPT_MODE, skeySpec);
	    byte[] decrypted = cipher.doFinal( toDecrypt );
	    
	    String decryptedString = new String( decrypted );
	    System.out.println("Decrypted string: " + decryptedString );
  }
  
  public static void main(String[] args) throws Exception 
  {
	AES a = new AES();
	//a.saveKeyFile();
	a.readKeyFile();
	a.decrypt("ÜS∫êÊ‘@È∏ÿ92ƒ".getBytes());
  }  
}
```


----------

