首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >您好,我正在尝试做AES加密使用JAVA代码帮助我在转换?

您好,我正在尝试做AES加密使用JAVA代码帮助我在转换?
EN

Stack Overflow用户
提问于 2016-06-07 14:02:13
回答 2查看 191关注 0票数 0

我正在尝试将JAVA代码转换为Objective -C语言。我有一个要求,我应该使用相同的代码,Android开发人员正在使用。代码如下所示

代码语言:javascript
运行
复制
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

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

import org.apache.commons.codec.binary.Base64;



public class EncDec {

    public static void main(String args[])
    {


        String reqMessage="{\"accountType\":\"ALL\",\"uId\":\"c8ff46be-a083-4009-8a33-fc2d22cc40e3|123456784\",\"deviceId\":\"qvxy1234\"}";
        Map requestMap=new HashMap();
        requestMap.put("body", reqMessage);
        String bodyString=(String) requestMap.get("body");
        String authKey="M/98hZivBqJQftMHsPvMgg&&";

         String encString= encode(authKey,bodyString);
         System.out.println("encString ::: "+ encString);

         String decString= decode(authKey,encString);  
         System.out.println("decString ::: "+ decString);



    }
    public static String encode(String keyString, String stringToEncode) throws NullPointerException {
        if (keyString.length() == 0 || keyString == null) {
            throw new NullPointerException("Please give Password");
        }

        if (stringToEncode.length() == 0 || stringToEncode == null) {
            throw new NullPointerException("Please give text");
        }

        try {
            SecretKeySpec skeySpec = getKey(keyString);
            byte[] clearText = stringToEncode.getBytes("UTF8");

            // IMPORTANT TO GET SAME RESULTS ON iOS and ANDROID
            final byte[] iv = new byte[16];
            Arrays.fill(iv, (byte) 0x00);
            IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);

            // Cipher is not thread safe
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivParameterSpec);
            byte[] encryptedByte=cipher.doFinal(clearText); 
            String encrypedValue = new String(Base64.encodeBase64(encryptedByte));
           System.out.println("Encrypted: " + stringToEncode + " -> " + encrypedValue);
            return encrypedValue;

        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (InvalidAlgorithmParameterException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * Decodes a String using AES-128 and Base64
     *
     * @param context
     * @param password
     * @param text
     * @return desoded String
     */
    public static String decode(String password, String text) throws NullPointerException {

        if (password.length() == 0 || password == null) {
            throw new NullPointerException("Please give Password");
        }

        if (text.length() == 0 || text == null) {
            throw new NullPointerException("Please give text");
        }

        try {
            SecretKey key = getKey(password);

            // IMPORTANT TO GET SAME RESULTS ON iOS and ANDROID
            final byte[] iv = new byte[16];
            Arrays.fill(iv, (byte) 0x00);
            IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);

            byte[] encrypedPwdBytes = Base64.decodeBase64(text.getBytes());
            // cipher is not thread safe
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            cipher.init(Cipher.DECRYPT_MODE, key, ivParameterSpec);
            byte[] decrypedValueBytes = (cipher.doFinal(encrypedPwdBytes));

            String decrypedValue = new String(decrypedValueBytes);
            System.out.println("Decrypted: " + text + " -> " + decrypedValue);
            return decrypedValue;

        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (InvalidAlgorithmParameterException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * Generates a SecretKeySpec for given password
     *
     * @param password
     * @return SecretKeySpec
     * @throws UnsupportedEncodingException
     */
    private static SecretKeySpec getKey(String password) throws UnsupportedEncodingException {

        // You can change it to 256 if you wish
        int keyLength = 128;
        byte[] keyBytes = new byte[keyLength / 8];
        // explicitly fill with zeros
        Arrays.fill(keyBytes, (byte) 0x0);

        // if password is shorter then key length, it will be zero-padded
        // to key length
        byte[] passwordBytes = password.getBytes("UTF-8");
        int length = passwordBytes.length < keyBytes.length ? passwordBytes.length : keyBytes.length;
        System.arraycopy(passwordBytes, 0, keyBytes, 0, length);
        SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
        return key;
    }


}

所以我想把这个转换成目标C,我不知道该怎么做。帮我一把!

我在JAVA中搜索了一些代码,并尝试这样做。但问题是,它会给出一些其他的解密数据,但不是使用这个代码给出的确切数据。因此,如果我转换相同的东西,我可能会得到确切的代码,我猜。在这里,人们可能既了解JAVA,也了解Objective C。我想这些人能帮到我。

EN

回答 2

Stack Overflow用户

发布于 2016-06-07 14:19:57

我不确定,但你可以试试:)。

对于编码阶段:

代码语言:javascript
运行
复制
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
// Cipher is not thread safe
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivParameterSpec);
byte[] encryptedByte=cipher.doFinal(clearText); 
String encrypedValue = new String(Base64.encodeBase64(encryptedByte));

在Obj-C中使用CCCrypt:

代码语言:javascript
运行
复制
CCCryptorStatus CCCrypt(
CCOperation op,         //is kCCEncrypt in your case
CCAlgorithm alg,        //is kCCAlgorithmAES128
CCOptions options,      //is kCCModeCBC
const void *key,        //may be skeySpec
size_t keyLength,
const void *iv,         // is your iv key : ivParameterSpec
const void *dataIn,     
size_t dataInLength,
void *dataOut,          /* data RETURNED here */
size_t dataOutAvailable,
size_t *dataOutMoved)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_2_0);

请参考:CCCrypt decrypting in AES CBC works even without IV了解更多信息,希望这能对你有所帮助。

票数 0
EN

Stack Overflow用户

发布于 2016-06-10 14:54:08

嘿,我得到了答案,通过下面的链接,你会得到Android和IOS的确切代码…

https://gist.github.com/m1entus/f70d4d1465b90d9ee024

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37671623

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档