RSA 加密算法備忘


import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.RSAPublicKeySpec;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

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

public class RSAUtil {

    /** @DESC RSA加密算法 */
    public String rsaCrypt(String modeHex, String exponentHex, String messageg)
            throws IllegalBlockSizeException, BadPaddingException,
            NoSuchAlgorithmException, InvalidKeySpecException,
            NoSuchPaddingException, InvalidKeyException,
            UnsupportedEncodingException {

        KeyFactory factory = KeyFactory.getInstance("RSA");

        BigInteger m = new BigInteger(modeHex, 16);
        BigInteger e = new BigInteger(exponentHex, 16); 
        RSAPublicKeySpec spec = new RSAPublicKeySpec(m, e);

        RSAPublicKey pub = (RSAPublicKey) factory.generatePublic(spec);
        Cipher enc = Cipher.getInstance("RSA");
        enc.init(Cipher.ENCRYPT_MODE, pub);

        byte[] encryptedContentKey = enc.doFinal(messageg.getBytes("GB2312"));

        return new String(Hex.encodeHex(encryptedContentKey));
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章