Шифрование и дешифрование данных для приложения-клиента Android - PullRequest
2 голосов
/ 06 декабря 2011

С этим способом Я конвертирую изображение в строку. Теперь я хочу зашифровать эту строку перед отправкой данных на сервер. Есть ли простой способ зашифровать и расшифровать строку?

Ответы [ 3 ]

10 голосов
/ 06 декабря 2011

javax.crypto

Этот пакет предоставляет классы и интерфейсы для криптографических приложений, реализующих алгоритмы шифрования, дешифрования или согласования ключей.

Потоковые шифры поддерживаются кака также асимметричные, симметричные и блочные шифры.Реализации шифров от разных поставщиков могут быть интегрированы с использованием абстрактных классов SPI (Service Provider Interface).С классом SealedObject программист может защитить объект, зашифровав его с помощью шифра.

Аутентификация может быть основана на MAC (код аутентификации сообщения), таком как HMAC (Hash MAC, то есть с хэш-функцией SHA-1).

Пример:

Простой вспомогательный класс для шифрования и дешифрования строк с использованием AES128.Результат в кодировке Ascii (фактически шестнадцатеричный, без base64), поэтому не нужно хранить ни одного байта [].Значение SEED используется в качестве общего секрета («Мастер-пароль»).Только с тем же SEED сохраненные значения могут быть расшифрованы.

<code>package com.xxx;

import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

/**
 * Usage:
 * <pre>
 * String crypto = SimpleCrypto.encrypt(masterpassword, cleartext)
 * ...
 * String cleartext = SimpleCrypto.decrypt(masterpassword, crypto)
 * 
* @author ferenc.hechler * / public class SimpleCrypto {public static String encrypt (String seed, String cleartext) выдает исключение {byte [] rawKey = getRawKey(seed.getBytes ());byte [] result = encrypt (rawKey, cleartext.getBytes ());возврат к Hex (результат);} public static String decrypt (String seed, String encrypted) создает исключение {byte [] rawKey = getRawKey (seed.getBytes ());byte [] enc = toByte (зашифрованный);byte [] result = decrypt (rawKey, enc);вернуть новую строку (результат);} закрытый статический byte [] getRawKey (byte [] seed) создает исключение {KeyGenerator kgen = KeyGenerator.getInstance ("AES");SecureRandom sr = SecureRandom.getInstance ("SHA1PRNG", "Crypto");sr.setSeed (семян);kgen.init (128, ср);// 192 и 256 битов могут быть недоступны SecretKey skey = kgen.generateKey ();byte [] raw = skey.getEncoded ();вернуть сырье;} private static byte [] encrypt (byte [] raw, byte [] clear) создает исключение {SecretKeySpec skeySpec = new SecretKeySpec (raw, "AES");Cipher cipher = Cipher.getInstance ("AES");cipher.init (Cipher.ENCRYPT_MODE, skeySpec);byte [] encrypted = cipher.doFinal (clear);возврат зашифрован;} частный статический byte [] decrypt (byte [] raw, byte [] зашифрованный) создает исключение {SecretKeySpec skeySpec = new SecretKeySpec (raw, "AES");Cipher cipher = Cipher.getInstance ("AES");cipher.init (Cipher.DECRYPT_MODE, skeySpec);byte [] decrypted = cipher.doFinal (зашифрованный);возврат расшифрован;} public static String toHex (String txt) {return toHex (txt.getBytes ());} public static String fromHex (String hex) {return new String (toByte (hex));} открытый статический byte [] toByte (String hexString) {int len ​​= hexString.length () / 2;байт [] результат = новый байт [лен];для (int i = 0; i > 4) & 0x0f)). append (HEX.charAt (b & 0x0f));}}

Для получения дополнительной информации см. Безопасность Android. Как шифровать и дешифровать строки? и Шифрование на Android & BouncyCastle

0 голосов
/ 07 августа 2014
package com.duplicate;



   public class RSAEncryptionDescription {


 private static final String PUBLIC_KEY_FILE = "Public.key";  
 private static final String PRIVATE_KEY_FILE = "Private.key";  

 public static void main(String[] args) throws IOException {  

  try {  
   System.out.println("-------GENRATE PUBLIC and PRIVATE KEY-------------");  
   KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");  
   keyPairGenerator.initialize(2048); //1024 used for normal securities  
   KeyPair keyPair = keyPairGenerator.generateKeyPair();  
   PublicKey publicKey = keyPair.getPublic();  
   PrivateKey privateKey = keyPair.getPrivate();  
   System.out.println("Public Key - " + publicKey);  
   System.out.println("Private Key - " + privateKey);

   //Pullingout parameters which makes up Key  
   System.out.println("\n------- PULLING OUT PARAMETERS WHICH MAKES KEYPAIR----------\n");  
   KeyFactory keyFactory = KeyFactory.getInstance("RSA");  
   RSAPublicKeySpec rsaPubKeySpec = keyFactory.getKeySpec(publicKey, RSAPublicKeySpec.class);  
   RSAPrivateKeySpec rsaPrivKeySpec = keyFactory.getKeySpec(privateKey, RSAPrivateKeySpec.class);  
   System.out.println("PubKey Modulus : " + rsaPubKeySpec.getModulus());  
   System.out.println("PubKey Exponent : " + rsaPubKeySpec.getPublicExponent());  
   System.out.println("PrivKey Modulus : " + rsaPrivKeySpec.getModulus());  
   System.out.println("PrivKey Exponent : " + rsaPrivKeySpec.getPrivateExponent());  

   //Share public key with other so they can encrypt data and decrypt thoses using private key(Don't share with Other)  
   System.out.println("\n--------SAVING PUBLIC KEY AND PRIVATE KEY TO FILES-------\n");  
   RSAEncryptionDescription rsaObj = new RSAEncryptionDescription();  
   rsaObj.saveKeys(PUBLIC_KEY_FILE, rsaPubKeySpec.getModulus(), rsaPubKeySpec.getPublicExponent());  
   rsaObj.saveKeys(PRIVATE_KEY_FILE, rsaPrivKeySpec.getModulus(), rsaPrivKeySpec.getPrivateExponent());  

   //Encrypt Data using Public Key  
   byte[] encryptedData = rsaObj.encryptData("Anuj Patel - Classified Information !");  

   //Descypt Data using Private Key  
   rsaObj.decryptData(encryptedData);  

  } catch (NoSuchAlgorithmException e) {  
   e.printStackTrace();  
  }catch (InvalidKeySpecException e) {  
   e.printStackTrace();  
  }  

 }  

 /** 
  * Save Files 
  * @param fileName 
  * @param mod 
  * @param exp 
  * @throws IOException 
  */  
 private void saveKeys(String fileName,BigInteger mod,BigInteger exp) throws IOException{  
  FileOutputStream fos = null;  
  ObjectOutputStream oos = null;  

  try {  
   System.out.println("Generating "+fileName + "...");  
   fos = new FileOutputStream(fileName);  
   oos = new ObjectOutputStream(new BufferedOutputStream(fos));  

   oos.writeObject(mod);  
   oos.writeObject(exp);     

   System.out.println(fileName + " generated successfully");  
  } catch (Exception e) {  
   e.printStackTrace();  
  }  
  finally{  
   if(oos != null){  
    oos.close();  

    if(fos != null){  
     fos.close();  
    }  
   }  
  }    
 }  

 /** 
  * Encrypt Data 
  * @param data 
  * @throws IOException 
  */  
 private byte[] encryptData(String data) throws IOException {  
  System.out.println("\n----------------ENCRYPTION STARTED------------");  

  System.out.println("Data Before Encryption :" + data);  
  byte[] dataToEncrypt = data.getBytes();  
  byte[] encryptedData = null;  
  try {  
   PublicKey pubKey = readPublicKeyFromFile(PUBLIC_KEY_FILE);  
   Cipher cipher = Cipher.getInstance("RSA");  
   cipher.init(Cipher.ENCRYPT_MODE, pubKey);  
   encryptedData = cipher.doFinal(dataToEncrypt);  
   System.out.println("Encryted Data: " + encryptedData);  

  } catch (Exception e) {  
   e.printStackTrace();  
  }   

  System.out.println("----------------ENCRYPTION COMPLETED------------");    
  return encryptedData;  
 }  

 /** 
  * Encrypt Data 
  * @param data 
  * @throws IOException 
  */  
 private void decryptData(byte[] data) throws IOException {  
  System.out.println("\n----------------DECRYPTION STARTED------------");  
  byte[] descryptedData = null;  

  try {  
   PrivateKey privateKey = readPrivateKeyFromFile(PRIVATE_KEY_FILE);  
   Cipher cipher = Cipher.getInstance("RSA");  
   cipher.init(Cipher.DECRYPT_MODE, privateKey);  
   descryptedData = cipher.doFinal(data);  
   System.out.println("Decrypted Data: " + new String(descryptedData));  

  } catch (Exception e) {  
   e.printStackTrace();  
  }   

  System.out.println("----------------DECRYPTION COMPLETED------------");    
 }  

 /** 
  * read Public Key From File 
  * @param fileName 
  * @return PublicKey 
  * @throws IOException 
  */  
 public PublicKey readPublicKeyFromFile(String fileName) throws IOException{  
  FileInputStream fis = null;  
  ObjectInputStream ois = null;  
  try {  
   fis = new FileInputStream(new File(fileName));  
   ois = new ObjectInputStream(fis);  

   BigInteger modulus = (BigInteger) ois.readObject();  
      BigInteger exponent = (BigInteger) ois.readObject();  

      //Get Public Key  
      RSAPublicKeySpec rsaPublicKeySpec = new RSAPublicKeySpec(modulus, exponent);  
      KeyFactory fact = KeyFactory.getInstance("RSA");  
      PublicKey publicKey = fact.generatePublic(rsaPublicKeySpec);  

      return publicKey;  

  } catch (Exception e) {  
   e.printStackTrace();  
  }  
  finally{  
   if(ois != null){
    ois.close();  
    if(fis != null){
     fis.close();
    }
   }  
  }  
  return null;  
 }  

 /** 
  * read Public Key From File 
  * @param fileName 
  * @return 
  * @throws IOException 
  */  
 public PrivateKey readPrivateKeyFromFile(String fileName) throws IOException{  
  FileInputStream fis = null;  
  ObjectInputStream ois = null;  
  try {  
   fis = new FileInputStream(new File(fileName));  
   ois = new ObjectInputStream(fis);  

   BigInteger modulus = (BigInteger) ois.readObject();  
      BigInteger exponent = (BigInteger) ois.readObject();  

      //Get Private Key  
      RSAPrivateKeySpec rsaPrivateKeySpec = new RSAPrivateKeySpec(modulus, exponent);  
      KeyFactory fact = KeyFactory.getInstance("RSA");  
      PrivateKey privateKey = fact.generatePrivate(rsaPrivateKeySpec);  

      return privateKey;  

  } catch (Exception e) {  
   e.printStackTrace();  
  }  
  finally{  
   if(ois != null){  
    ois.close();  
    if(fis != null){  
     fis.close();  
    }  
   }  
  }  
  return null;  
 }  
}  
0 голосов
/ 06 декабря 2011
public class SecureCredentialsCrypto {

            public static String encrypt(String seed, String cleartext) throws Exception {
                    byte[] rawKey = getRawKey(seed.getBytes());
                    byte[] result = encrypt(rawKey, cleartext.getBytes());
                    return toHex(result);
            }

            public static String decrypt(String seed, String encrypted) throws Exception {
                    byte[] rawKey = getRawKey(seed.getBytes());
                    byte[] enc = toByte(encrypted);
                    byte[] result = decrypt(rawKey, enc);
                    return new String(result);
            }

            private static byte[] getRawKey(byte[] seed) throws Exception {
                    KeyGenerator kgen = KeyGenerator.getInstance("AES");
                    SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
                    sr.setSeed(seed);
                kgen.init(128, sr); // 192 and 256 bits may not be available
                SecretKey skey = kgen.generateKey();
                byte[] raw = skey.getEncoded();
                return raw;
            }


            private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
                SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
                    Cipher cipher = Cipher.getInstance("AES");
                cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
                byte[] encrypted = cipher.doFinal(clear);
                    return encrypted;
            }

            private static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception {
                SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
                    Cipher cipher = Cipher.getInstance("AES");
                cipher.init(Cipher.DECRYPT_MODE, skeySpec);
                byte[] decrypted = cipher.doFinal(encrypted);
                    return decrypted;
            }

            public static String toHex(String txt) {
                    return toHex(txt.getBytes());
            }
            public static String fromHex(String hex) {
                    return new String(toByte(hex));
            }

            public static byte[] toByte(String hexString) {
                    int len = hexString.length()/2;
                    byte[] result = new byte[len];
                    for (int i = 0; i < len; i++)
                            result[i] = Integer.valueOf(hexString.substring(2*i, 2*i+2), 16).byteValue();
                    return result;
            }

            public static String toHex(byte[] buf) {
                    if (buf == null)
                            return "";
                    StringBuffer result = new StringBuffer(2*buf.length);
                    for (int i = 0; i < buf.length; i++) {
                            appendHex(result, buf[i]);
                    }
                    return result.toString();
            }
            private final static String HEX = "0123456789ABCDEF";
            private static void appendHex(StringBuffer sb, byte b) {
                    sb.append(HEX.charAt((b>>4)&0x0f)).append(HEX.charAt(b&0x0f));
            }

    }

//for storing encrypt it
String crypto_email = SecureCredentialsCrypto.encrypt("secure", email.toString().trim());

//for reading  decrypt it
//crypto is object name to read 


String correctEmail=SecureCredentialsCrypto.decrypt("secure", crypto);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...