在Android中加密/解密字符串的简便方法

时间:2016-10-19 05:57:46

标签: android encryption

我的问题是如何加密字符串

String AndroidId;

@Override
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.download_movie_activity);

  cancel = (Button)findViewById(R.id.img_cancle);

  linear= (LinearLayout)findViewById(R.id.progress);
  linear.setVisibility(View.GONE);

  String encrypted = "MzIyNTE2" + "OTQNzM4NTQ=";

  Log.e("Encrypt", encrypted);

  WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
  WifiInfo wInfo = wifiManager.getConnectionInfo();
  AndroidId = wInfo.getMacAddress();

  AndroidId=encrypted;

U如何加密我存储MAC地址的AndroidId。

7 个答案:

答案 0 :(得分:30)

您可以使用Cipher

此类提供用于加密和解密的加密密码的功能。它构成了Java Cryptographic Extension(JCE)框架的核心。

加密和解密示例:

public static SecretKey generateKey() 
    throws NoSuchAlgorithmException, InvalidKeySpecException 
{ 
    return secret = new SecretKeySpec(password.getBytes(), "AES"); 
}

public static byte[] encryptMsg(String message, SecretKey secret)
    throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidParameterSpecException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException 
{ 
   /* Encrypt the message. */
   Cipher cipher = null; 
   cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
   cipher.init(Cipher.ENCRYPT_MODE, secret); 
   byte[] cipherText = cipher.doFinal(message.getBytes("UTF-8")); 
   return cipherText; 
}

public static String decryptMsg(byte[] cipherText, SecretKey secret) 
    throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidParameterSpecException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException 
{
    /* Decrypt the message, given derived encContentValues and initialization vector. */
    Cipher cipher = null;
    cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
    cipher.init(Cipher.DECRYPT_MODE, secret); 
    String decryptString = new String(cipher.doFinal(cipherText), "UTF-8");
    return decryptString; 
}

加密:

SecretKey secret = generateKey();
EncUtil.encryptMsg(String toEncrypt, secret))

解密:

EncUtil.decryptMsg(byte[] toDecrypt, secret))

答案 1 :(得分:15)

使用这些帮助程序类,您可以在Android中以简单的方式加密和解密字符串,但这仅适用于Android 7.0以下,对于 Android 8.0 以上,您可以从here <找到/ p>

import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class AESHelper {

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","Crypto");
    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));
}
}

下面是您对字符串进行加密和解密的方法,

public String encryption(String strNormalText){
    String seedValue = "YourSecKey";
    String normalTextEnc="";
    try {
        normalTextEnc = AESHelper.encrypt(seedValue, strNormalText);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return normalTextEnc;
}
public String decryption(String strEncryptedText){
    String seedValue = "YourSecKey";
    String strDecryptedText="";
    try {
        strDecryptedText = AESHelper.decrypt(seedValue, strEncryptedText);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return strDecryptedText;
}

最后你可以使用如:

String encryptedString = encryption("Input Normal String");
String decryptedString = decryption("Input Encrypted String");

答案 2 :(得分:7)

请仔细阅读

新版Android SDK不再支持Crypto提供商。

如果您的应用依赖于setSeed()从字符串派生密钥,那么您 应切换到使用SecretKeySpec直接加载原始密钥字节 OR 使用真正的密钥派生函数(KDF)。

请参阅此处的建议:

http://android-developers.blogspot.com/2016/06/security-crypto-provider-deprecated-in.html

答案 3 :(得分:0)

使用BlueFish算法,您可以简单地加密和解密任何字符串。密钥大小从128位到448位的Blowfish,被认为是一种更好的更快算法。尝试如下

public class CryptUtil {
private static final String ALGORITHM = "Blowfish";
private static final String MODE = "Blowfish/CBC/PKCS5Padding";
private static final String IV = "abcdefgh";
private static final String KEY= "MyKey";

public static  String encrypt(String value ) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
    SecretKeySpec secretKeySpec = new SecretKeySpec(KEY.getBytes(), ALGORITHM);
    Cipher cipher = Cipher.getInstance(MODE);
    cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, new IvParameterSpec(IV.getBytes()));
    byte[] values = cipher.doFinal(value.getBytes());
    return Base64.encodeToString(values, Base64.DEFAULT);
}

public static  String decrypt(String value) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
    byte[] values = Base64.decode(value, Base64.DEFAULT);
    SecretKeySpec secretKeySpec = new SecretKeySpec(KEY.getBytes(), ALGORITHM);
    Cipher cipher = Cipher.getInstance(MODE);
    cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, new IvParameterSpec(IV.getBytes()));
    return new String(cipher.doFinal(values));
  }

}

答案 4 :(得分:0)

尝试下面的代码为我工作。

AES加密

public static String getEncryptedString(String value) {
        try {
          byte[] key = your Key in byte array;
          byte[] input = sault in byte array

            return Base64.encodeToString(encrypt(value.getBytes("UTF-8"), key, input), Base64.DEFAULT);
        } catch (UnsupportedEncodingException e) {
            return "";
        }
    }


 public static byte[] encrypt(byte[] data, byte[] key, byte[] ivs) {
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
            byte[] finalIvs = new byte[16];
            int len = ivs.length > 16 ? 16 : ivs.length;
            System.arraycopy(ivs, 0, finalIvs, 0, len);
            IvParameterSpec ivps = new IvParameterSpec(finalIvs);
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivps);
            return cipher.doFinal(data);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

答案 5 :(得分:0)

public static String encrypt(String value) {
    String key = "aesEncryptionKey";
    String initVector = "encryptionIntVec";
    try {
        IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
        SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");

        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);

        byte[] encrypted = cipher.doFinal(value.getBytes());
        return Base64.encode(encrypted);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return null;
}
public static String decrypt(String value) {
    String key = "aesEncryptionKey";
    String initVector = "encryptionIntVec";
    try {
        IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
        SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");

        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
        cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
        byte[] original = cipher.doFinal(Base64.decode(value));

        return new String(original);
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    return null;
}

答案 6 :(得分:0)

        package <yourpackagename>;

        import android.util.Base64;

        import java.io.UnsupportedEncodingException;
        import java.security.InvalidAlgorithmParameterException;
        import java.security.InvalidKeyException;
        import java.security.MessageDigest;
        import java.security.NoSuchAlgorithmException;
        import java.security.SecureRandom;
        import java.security.spec.InvalidKeySpecException;
        import java.security.spec.KeySpec;

        import javax.crypto.BadPaddingException;
        import javax.crypto.Cipher;
        import javax.crypto.IllegalBlockSizeException;
        import javax.crypto.NoSuchPaddingException;
        import javax.crypto.SecretKey;
        import javax.crypto.SecretKeyFactory;
        import javax.crypto.spec.IvParameterSpec;
        import javax.crypto.spec.PBEKeySpec;
        import javax.crypto.spec.SecretKeySpec;

        /**
         * A class to make more easy and simple the encrypt routines, this is the core of Encryption library
         */
        public class Encryption {


            private final Builder mBuilder;


            private Encryption(Builder builder) {
                mBuilder = builder;
            }

            public static Encryption getDefault(String key, String salt, byte[] iv) {
                try {
                    return Builder.getDefaultBuilder(key, salt, iv).build();
                } catch (NoSuchAlgorithmException e) {
                    e.printStackTrace();
                    return null;
                }
            }


            public String encrypt(String data) throws UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, InvalidKeyException, InvalidKeySpecException, BadPaddingException, IllegalBlockSizeException {
                if (data == null) return null;
                SecretKey secretKey = getSecretKey(hashTheKey(mBuilder.getKey()));
                byte[] dataBytes = data.getBytes(mBuilder.getCharsetName());
                Cipher cipher = Cipher.getInstance(mBuilder.getAlgorithm());
                cipher.init(Cipher.ENCRYPT_MODE, secretKey, mBuilder.getIvParameterSpec(), mBuilder.getSecureRandom());
                return Base64.encodeToString(cipher.doFinal(dataBytes), mBuilder.getBase64Mode());
            }

            public String encryptOrNull(String data) {
                try {
                    return encrypt(data);
                } catch (Exception e) {
                    e.printStackTrace();
                    return null;
                }
            }


            public void encryptAsync(final String data, final Callback callback) {
                if (callback == null) return;
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            String encrypt = encrypt(data);
                            if (encrypt == null) {
                                callback.onError(new Exception("Encrypt return null, it normally occurs when you send a null data"));
                            }
                            callback.onSuccess(encrypt);
                        } catch (Exception e) {
                            callback.onError(e);
                        }
                    }
                }).start();
            }


            public String decrypt(String data) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
                if (data == null) return null;
                byte[] dataBytes = Base64.decode(data, mBuilder.getBase64Mode());
                SecretKey secretKey = getSecretKey(hashTheKey(mBuilder.getKey()));
                Cipher cipher = Cipher.getInstance(mBuilder.getAlgorithm());
                cipher.init(Cipher.DECRYPT_MODE, secretKey, mBuilder.getIvParameterSpec(), mBuilder.getSecureRandom());
                byte[] dataBytesDecrypted = (cipher.doFinal(dataBytes));
                return new String(dataBytesDecrypted);
            }


            public String decryptOrNull(String data) {
                try {
                    return decrypt(data);
                } catch (Exception e) {
                    e.printStackTrace();
                    return null;
                }
            }


            public void decryptAsync(final String data, final Callback callback) {
                if (callback == null) return;
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            String decrypt = decrypt(data);
                            if (decrypt == null) {
                                callback.onError(new Exception("Decrypt return null, it normally occurs when you send a null data"));
                            }
                            callback.onSuccess(decrypt);
                        } catch (Exception e) {
                            callback.onError(e);
                        }
                    }
                }).start();
            }


            private SecretKey getSecretKey(char[] key) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeySpecException {
                SecretKeyFactory factory = SecretKeyFactory.getInstance(mBuilder.getSecretKeyType());
                KeySpec spec = new PBEKeySpec(key, mBuilder.getSalt().getBytes(mBuilder.getCharsetName()), mBuilder.getIterationCount(), mBuilder.getKeyLength());
                SecretKey tmp = factory.generateSecret(spec);
                return new SecretKeySpec(tmp.getEncoded(), mBuilder.getKeyAlgorithm());
            }


            private char[] hashTheKey(String key) throws UnsupportedEncodingException, NoSuchAlgorithmException {
                MessageDigest messageDigest = MessageDigest.getInstance(mBuilder.getDigestAlgorithm());
                messageDigest.update(key.getBytes(mBuilder.getCharsetName()));
                return Base64.encodeToString(messageDigest.digest(), Base64.NO_PADDING).toCharArray();
            }

            public interface Callback {


                void onSuccess(String result);


                void onError(Exception exception);

            }


            public static class Builder {

                private byte[] mIv;
                private int mKeyLength;
                private int mBase64Mode;
                private int mIterationCount;
                private String mSalt;
                private String mKey;
                private String mAlgorithm;
                private String mKeyAlgorithm;
                private String mCharsetName;
                private String mSecretKeyType;
                private String mDigestAlgorithm;
                private String mSecureRandomAlgorithm;
                private SecureRandom mSecureRandom;
                private IvParameterSpec mIvParameterSpec;


                public static Builder getDefaultBuilder(String key, String salt, byte[] iv) {
                    return new Builder()
                            .setIv(iv)
                            .setKey(key)
                            .setSalt(salt)
                            .setKeyLength(128)
                            .setKeyAlgorithm("AES")
                            .setCharsetName("UTF8")
                            .setIterationCount(1)
                            .setDigestAlgorithm("SHA1")
                            .setBase64Mode(Base64.DEFAULT)
                            .setAlgorithm("AES/CBC/PKCS5Padding")
                            .setSecureRandomAlgorithm("SHA1PRNG")
                            .setSecretKeyType("PBKDF2WithHmacSHA1");
                }

                public Encryption build() throws NoSuchAlgorithmException {
                    setSecureRandom(SecureRandom.getInstance(getSecureRandomAlgorithm()));
                    setIvParameterSpec(new IvParameterSpec(getIv()));
                    return new Encryption(this);
                }


                private String getCharsetName() {
                    return mCharsetName;
                }

                public Builder setCharsetName(String charsetName) {
                    mCharsetName = charsetName;
                    return this;
                }


                private String getAlgorithm() {
                    return mAlgorithm;
                }


                public Builder setAlgorithm(String algorithm) {
                    mAlgorithm = algorithm;
                    return this;
                }


                private String getKeyAlgorithm() {
                    return mKeyAlgorithm;
                }


                public Builder setKeyAlgorithm(String keyAlgorithm) {
                    mKeyAlgorithm = keyAlgorithm;
                    return this;
                }


                private int getBase64Mode() {
                    return mBase64Mode;
                }


                public Builder setBase64Mode(int base64Mode) {
                    mBase64Mode = base64Mode;
                    return this;
                }


                private String getSecretKeyType() {
                    return mSecretKeyType;
                }


                public Builder setSecretKeyType(String secretKeyType) {
                    mSecretKeyType = secretKeyType;
                    return this;
                }


                private String getSalt() {
                    return mSalt;
                }


                public Builder setSalt(String salt) {
                    mSalt = salt;
                    return this;
                }


                private String getKey() {
                    return mKey;
                }


                public Builder setKey(String key) {
                    mKey = key;
                    return this;
                }

                private int getKeyLength() {
                    return mKeyLength;
                }

                public Builder setKeyLength(int keyLength) {
                    mKeyLength = keyLength;
                    return this;
                }

                private int getIterationCount() {
                    return mIterationCount;
                }

                public Builder setIterationCount(int iterationCount) {
                    mIterationCount = iterationCount;
                    return this;
                }


                private String getSecureRandomAlgorithm() {
                    return mSecureRandomAlgorithm;
                }

                public Builder setSecureRandomAlgorithm(String secureRandomAlgorithm) {
                    mSecureRandomAlgorithm = secureRandomAlgorithm;
                    return this;
                }

                private byte[] getIv() {
                    return mIv;
                }
                public Builder setIv(byte[] iv) {
                    mIv = iv;
                    return this;
                }

                private SecureRandom getSecureRandom() {
                    return mSecureRandom;
                }
                public Builder setSecureRandom(SecureRandom secureRandom) {
                    mSecureRandom = secureRandom;
                    return this;
                }

                private IvParameterSpec getIvParameterSpec() {
                    return mIvParameterSpec;
                }

                public Builder setIvParameterSpec(IvParameterSpec ivParameterSpec) {
                    mIvParameterSpec = ivParameterSpec;
                    return this;
                }

                private String getDigestAlgorithm() {
                    return mDigestAlgorithm;
                }

                public Builder setDigestAlgorithm(String digestAlgorithm) {
                    mDigestAlgorithm = digestAlgorithm;
                    return this;
                }

            }
        }


    Step 2: **Encrypt Process..**

    Here i am encrypting username (EditText)

    EditText edittextvalue = (EditText) findviewbyid (R.id.edittextvalue);

    Example 1:   
    Encryption encryption = Encryption.getDefault("Key", "Salt", new byte[16]);
    String encryptUsername = 
                encryption.encryptOrNull(edittextvalue.getText().toString().trim());

    **Sharing the value through Shared Prefernece:**

    SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); 
    editor = pref.edit();
    editor.putString("userID", encryptUsername);
    editor.commit();


 **Step 3: Decrypt process...**

   Example 1:

  **getting the value from shared preferences:**

    SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); 
    decryptLoginNo = pref.getString("userID", null);  

    **Decrypting the value:**
    Encryption encryption = Encryption.getDefault("Key", "Salt", new byte[16]);
    String decryptValue = encryption.decryptOrNull(decryptLoginNo);

Any confusing message me... 

@Ambilpura