为Android应用客户端加密和解密数据 [英] Encrypt and decrypt data for Android app-client

查看:128
本文介绍了为Android应用客户端加密和解密数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用此方式
我将一个图像转换成一个字符串。
现在我想在服务器中发送数据之前加密这个字符串。有没有一种简单的方式加密和解密字符串?

With this way I convert an image into a String. Now I want to encrypt this string before send the data in server. Is there a simple way to encrypt and decrypt the string?

推荐答案

javax.crypto

此软件包提供加密应用程序实现加密,解密或密钥协议算法的类和接口。

This package provides the classes and interfaces for cryptographic applications implementing algorithms for encryption, decryption, or key agreement.

流密码被支持以及非对称,对称和块密码。可以使用SPI(服务提供者接口)抽象类集成来自不同提供者的密码实现。对于类SealedObject,程序员可以通过使用密码加密来保护对象。

Stream ciphers are supported as well as asymmetric, symmetric and block ciphers. Cipher implementations from different providers can be integrated using the SPI (Service Provider Interface) abstract classes. With class SealedObject a programmer can secure an object by encrypting it with a cipher.

认证可以基于MAC(消息认证码),如HMAC(Hash MAC,ie使用SHA-1散列函数)。

Authentication may be based on MAC (Message Authentication Code) such as HMAC (Hash MAC, i.e. with a SHA-1 hash function).

示例:

类使用AES128加密和解密字符串。结果是Ascii编码(实际上是hex,没有base64),所以不需要存储byte []。 SEED值用作共享密钥(主密码)。只有使用相同的SEED,存储的值才能被解密。

Simple helper class to encrypt and decrypt strings using AES128. The result is Ascii-encoded (actually hex, no base64), so no byte[] has to be stored. A SEED value is used as a shared secret ("Master-Password"). Only with the same SEED the stored values can be decrypted.

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)
 * </pre>
 * @author ferenc.hechler
 */
public class SimpleCrypto {

    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));
    }

}

有关更多信息,请查看 Android Security
如何加密和解密字符串?
Android& BouncyCastle

For more info look at Android Security How to encrypt and decrypt strings? and Encryption on Android & BouncyCastle

这篇关于为Android应用客户端加密和解密数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆