簡體   English   中英

AES加密.Net到Android移動版

[英]AES encryption .Net to Android for mobile

我提到了下面的鏈接AES Encryption .net到swift

但是,將其應用於ANDROID時,我的代碼無法通過版本(PBKDF2)轉換獲得正確的AES加密。 需要幫忙。

public static String Encrypt(String PlainText) throws Exception {

        try {
            byte[] salt = new byte[] { 0x49, 0x76, 0x61, 0x6E, 0x20, 0x4D,
                    0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 };
            System.out.println("Exception setting up cipher: "+pbkdf2("<keyname>",salt.toString(),1024,128));
            Cipher _aesCipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
            byte[] keyBytes =pbkdf2("<keyname>",salt.toString(),1024,128).getBytes();
            SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
            byte[] iv ="OFRna73m*aze01xY".getBytes();//pbkdf2("<keyname>",salt.toString(),2,64).getBytes();
            IvParameterSpec ivSpec = new IvParameterSpec(iv);
            _aesCipher.init(1, keySpec, ivSpec);
            byte[] plainText = PlainText.getBytes();
            byte[] result = _aesCipher.doFinal(plainText);
            return Base64.encodeToString(result, Base64.DEFAULT);//Base64.encode(result,1));
        } catch (Exception ex1) {
            System.out.println("Exception setting up cipher: "
                    + ex1.getMessage() + "\r\n");
            ex1.printStackTrace();
            return "";
        }
    }

    public static String pbkdf2(String password, String salt, int iterations, int keyLength) throws NoSuchAlgorithmException, InvalidKeySpecException {
        char[] chars = password.toCharArray();

        PBEKeySpec spec = new PBEKeySpec(chars, salt.getBytes(), iterations, keyLength);
        SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        byte[] hash = skf.generateSecret(spec).getEncoded();
        return toHex(hash);
    }

    // Converts byte array to a hexadecimal string
    private static String toHex(byte[] array) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < array.length; i++) {
            sb.append(Integer.toString((array[i] & 0xff) + 0x100, 16).substring(1));
        }
        return sb.toString();
    }

請檢查以下代碼。 我已經為它創建了Singletone類,以便可以在應用程序中的任何位置訪問它。

以下幾點應與.net或swift相同

重要點IVSALTPASSWORD請也檢查此PBKDF2WithHmacSHA1

SecretKeyFactory工廠= SecretKeyFactory.getInstance(“ PBKDF2WithHmacSHA1”);

生成密鑰,我們使用了這個

KeySpec spec = new PBEKeySpec(password, salt, 2, 256);

重要點是(密碼,鹽,迭代次數,字節),該點必須與您正在使用的其他平台(如.net或swift)相同

public class AesBase64Wrapper {

    private static String IV = "it should be same like server or other platform";
    private static String PASSWORD = "it should be same like server or other platform";
    private static String SALT = "it should be same like server or other platform";


    private static volatile AesBase64Wrapper sSoleInstance = new AesBase64Wrapper();

    //private constructor.
    private AesBase64Wrapper() {

    }

    public static AesBase64Wrapper getInstance() {

        return sSoleInstance;

    }

    // For Encryption
    public String encryptAndEncode(String raw) {
        try {
         Cipher c = getCipher(Cipher.ENCRYPT_MODE);
         byte[] encryptedVal = c.doFinal(getBytes(raw));

    //String retVal = Base64.encodeToString(encryptedVal, Base64.DEFAULT);

         String retVal = Base64.encodeToString(encryptedVal, Base64.NO_WRAP);
         return retVal;
        }catch (Throwable t) {
            throw new RuntimeException(t);
        }
    }

    public String decodeAndDecrypt(String encrypted) throws Exception {
//        byte[] decodedValue = Base64.decode(getBytes(encrypted),Base64.DEFAULT);
        byte[] decodedValue = Base64.decode(getBytes(encrypted), Base64.NO_WRAP);

        Cipher c = getCipher(Cipher.DECRYPT_MODE);
        byte[] decValue = c.doFinal(decodedValue);
        return new String(decValue);
    }

    private String getString(byte[] bytes) throws UnsupportedEncodingException {
        return new String(bytes, "UTF-8");
    }

    private byte[] getBytes(String str) throws UnsupportedEncodingException {
        return str.getBytes("UTF-8");
    }

    private Cipher getCipher(int mode) throws Exception {
        Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
        byte[] iv = getBytes(IV);
        String xyz = String.valueOf(generateKey());
        Log.i("generateKey", xyz);
        c.init(mode, generateKey(), new IvParameterSpec(iv));
        return c;
    }

    private Key generateKey() throws Exception {
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        char[] password = PASSWORD.toCharArray();
        byte[] salt = getBytes(SALT);

        KeySpec spec = new PBEKeySpec(password, salt, 2, 256);
        SecretKey tmp = factory.generateSecret(spec);
        byte[] encoded = tmp.getEncoded();
        byte b = encoded[1];
        Log.e("Secrete Key", String.valueOf(encoded));
        return new SecretKeySpec(encoded, "CBC");
    }


}

在活動中,您可以像

String EncryptString = AesBase64Wrapper.getInstance().encryptAndEncode("hello");
String DecryptString = AesBase64Wrapper.getInstance().encryptAndEncode(EncryptString);
// You will Get Output in Decrypted String

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM