importjava.io.FileInputStream;importjava.io.FileOutputStream;importjava.io.ObjectInputStream;importjava.io.ObjectOutputStream;importjava.security.Key;importjava.security.KeyFactory;importjava.security.KeyPair;importjava.security.KeyPairGenerator importjava.security.PrivateKey;importjava.security.PublicKey;importjava.security.SecureRandom;importjava.security.Signature;importjava.security.spec.PKCS8EncodedKeySpec;importjava.security.spec.X509EncodedKeySpec;importjavax.crypto.Cipher;importun .misc .BASE64Decoder;importsun.misc.BASE64Encoder;/*** RSA encryption, supports fragment encryption
*
* BCD code (Binary-Coded Decimal) is also known as binary coded decimal or binary-decimal code.
* Use 4-digit binary numbers to represent the 10 numbers from 0 to 9 in 1-digit decimal numbers.
* is a binary form of number encoding, using binary coded decimal codes.
* Note: Most of the BCD codes mentioned in daily life refer to the 8421BCD code format
*@authorMing
**/
public classRSAUtil {/**Specify the encryption algorithm as RSA*/
private static String ALGORITHM = “RSA”;/**Specify the size of the key*/
private static int KEYSIZE = 1024;/**Specify the public key storage file*/
private static String PUBLIC_KEY_FILE = “d:/PublicKey”;/**Specify the private key storage file*/
private static String PRIVATE_KEY_FILE = “d:/PrivateKey”; public static final String KEY_ALGORITHM = “RSA”;/**Customize a string*/
public static final String SIGNATURE_ALGORITHM = “shihaiming@#!RSA”;/*** generate key pair*/
public static void generateKeyPair() throwsException {if (getpublickey() == null || getprivatekey() == null) {/**RSA algorithm requires a trusted source of random numbers*/SecureRandom sr= newSecureRandom( );/**Create a KeyPairGenerator object for the RSA algorithm*/KeyPairGenerator kpg=KeyPairGenerator.getInstance(ALGORITHM);/**Use the above random data source to initialize the KeyPairGenerator object*/kpg.initialize(KEYSIZE, sr);/* *Generate key pair*/KeyPair kp=kpg.generateKeyPair();/**Get public key*/Key publicKey=kp.getPublic();/**Get private key*/Key privateKey=kp.getPrivate(); /**Write the generated key to a file using an object stream*/ObjectOutputStream oos1= new ObjectOutputStream(newFileOutputStream(PUBLIC_KEY_FILE));
ObjectOutputStream oos2= new ObjectOutputStream(newFileOutputStream(PRIVATE_KEY_FILE));
oos1.writeObject(publicKey);
oos2.writeObject(privateKey);/**Clear the cache, close the file output stream*/oos1.close();
oos2. close();
}
}/*** generate signature
*
*@paramdata
*@paramprivateKey
*@return*@throwsException*/
public static String sign(byte[] data, String privateKey) throwsException {//Decrypt the private key encoded by base64
byte[] keyBytes =decryptBASE64(privateKey);//construct PKCS8EncodedKeySpec object
PKCS8EncodedKeySpec pkcs8KeySpec = newPKCS8EncodedKeySpec(keyBytes);//Key_ALGORITHM specified encryption algorithm
KeyFactory keyFactory =KeyFactory.getInstance(KEY_ALGORITHM);//Get private key object
PrivateKey priKey =keyFactory.generatePrivate(pkcs8KeySpec);//Use the private key to generate a digital signature for the information
Signature signature =Signature. getInstance(SIGNATURE_ALGORITHM);
signature.initSign(priKey);
signature.update(data);returnencryptBASE64(signature.sign());
}/*** verify signature
*
*@paramdata
*@parampublicKey
*@paramsign
*@return*@throwsException*/
public static boolean verify(byte[] data, String publicKey, String sign) throwsException {//Decrypt the public key encoded by base64
byte[] keyBytes =decryptBASE64(publicKey);//construct X509EncodedKeySpec object
X509EncodedKeySpec keySpec = newX509EncodedKeySpec(keyBytes);//Key_ALGORITHM specified encryption algorithm
KeyFactory keyFactory =KeyFactory.getInstance(KEY_ALGORITHM);//Get the public key object
PublicKey pubKey =keyFactory.generatePublic(keySpec);
Signature signature=Signature. getInstance(SIGNATURE_ALGORITHM);
signature.initVerify(pubKey);
signature.update(data);//Verify whether the signature is valid
returnsignature. verify(decryptBASE64(sign));
}/*** BASE64 decryption
*
*@paramkey
*@return*@throwsException*/
public static byte[] decryptBASE64(String key) throwsException {return (newBASE64Decoder()).decodeBuffer(key);
}/*** BASE64 encryption
*
*@paramkey
*@return*@throwsException*/
public static String encryptBASE64(byte[] key) throwsException {return (newBASE64Encoder()).encodeBuffer(key);
}/*** encryption method source: source data*/
public static String encrypt(String source) throwsException {/**Read out the public key object in the file*/ObjectInputStream ois= new ObjectInputStream(newFileInputStream(PUBLIC_KEY_FILE));
Key key=(Key) ois. readObject();
ois.close();/**Get Cipher object to implement RSA encryption of source data*/Cipher cipher=Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, key);int MaxBlockSize = KEYSIZE / 8;int len = (MaxBlockSize – 11) / 8;
String[] datas=splitString(source, len);
StringBuffer mi= newStringBuffer();for(String s : datas) {
mi.append(bcd2Str(cipher.doFinal(s.getBytes())));
}return mi.toString();
}/*** String Fragmentation
*
*@paramstring
* source string
*@paramlen
* The length of a single slice (keysize/8)
*@return
*/
public static String[] splitString(String string, intlen) {int x = string.length() /len;int y = string.length() %len;int z = 0;if (y != 0) {
z= 1;
}
String[] strings= new String[x +z];
String str=””;for (int i = 0; i < x + z; i++) {if (i == x + z – 1 && y != 0) {
str= string.substring(i * len, i * len +y);
}else{
str= string.substring(i * len, i * len +len);
}
strings[i]=str;
}return strings;
}/*** bcd to Str
*
*@parambytes
*@return
*/
public static String bcd2Str(byte[] bytes) { char temp[] = new char[bytes. length * 2], val; for (int i = 0; i < bytes. length; i++) {
val= (char) (((bytes[i] & 0xf0) >> 4) & 0x0f);
temp[i* 2] = (char) (val > 9 ? val + ‘A’ – 10 : val + ‘0’);
val= (char) (bytes[i] & 0x0f);
temp[i* 2 + 1] = (char) (val > 9 ? val + ‘A’ – 10 : val + ‘0’);
}return newString(temp);
}/*** Decrypt
*
*@paramcryptograph
* : ciphertext
*@return decrypted plaintext
*@throwsException*/
public static String decrypt(String cryptograph) throwsException {/**Read out the private key object in the file*/@SuppressWarnings(“resource”)
ObjectInputStream ois= new ObjectInputStream(newFileInputStream(PRIVATE_KEY_FILE));
Key key=(Key) ois.readObject();/**Get the Cipher object to perform RSA decryption on the data encrypted with the public key*/Cipher cipher=Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, key);int key_len = KEYSIZE / 8;byte[] bytes =cryptograph.getBytes();byte[] bcd =ASCII2BCD(bytes, bytes.length);
StringBuffer sBuffer= newStringBuffer();byte[][] arrays =splitArray(bcd, key_len);for (byte[] arr : arrays) {
sBuffer.append(newString(cipher.doFinal(arr)));
}returnsBuffer.toString();
}/*** ASCII to BCD
*
*@paramascii
*@paramasc_len
*@return
*/
public static byte[] ASCII2BCD(byte[] ascii, intasc_len) {byte[] bcd = new byte[asc_len / 2];int j = 0; for (int i = 0; i < (asc_len + 1) / 2; i++) {
bcd[i]= asc2bcd(ascii[j++]);
bcd[i]= (byte) (((j >= asc_len) ? 0x00 : asc2bcd(ascii[j++])) + (bcd[i] << 4));
}return bcd;
}/*** asc to bcd
*
*@paramasc
*@return
*/
public static byte asc2bcd(byteasc) {bytebcd;if ((asc >= ‘0’) && (asc <= '9'))
bcd= (byte) (asc – ‘0’);else if ((asc >= ‘A’) && (asc <= 'F'))
bcd= (byte) (asc – ‘A’ + 10);else if ((asc >= ‘a’) && (asc <= 'f'))
bcd= (byte) (asc – ‘a’ + 10); elsebcd= (byte) (asc – 48);returnbcd;
}/*** Byte array fragmentation
*
*@paramdata
*@paramlen
*@return
*/
public static byte[][] splitArray(byte[] data, intlen) {int x = data.length /len;int y = data.length %len;int z = 0;if (y != 0) {
z= 1;
}byte[][] arrays = new byte[x +z][];byte[] arr;for (int i = 0; i < x + z; i++) {
arr= new byte[len];if (i == x + z – 1 && y != 0) {
System. arraycopy(data, i* len, arr, 0, y);
}else{
System. arraycopy(data, i* len, arr, 0, len);
}
arrays[i]=arr;
}return arrays;
}/**Read out the public key object in the file*/
public staticString getpublickey() {try{
@SuppressWarnings(“resource”)
ObjectInputStream ois= new ObjectInputStream(newFileInputStream(PUBLIC_KEY_FILE));
Key key=(Key) ois. readObject();
String publickey=encryptBASE64(key.getEncoded());return publickey;
} catch(Exception e) {
e. printStackTrace();
}return null;
}/**Read out the private key object in the file*/
public staticString getprivatekey() {try{
@SuppressWarnings(“resource”)
ObjectInputStream ois= new ObjectInputStream(newFileInputStream(PRIVATE_KEY_FILE));
Key key=(Key) ois. readObject();
String privatekey=encryptBASE64(key.getEncoded());returnprivatekey;
} catch(Exception e) {
e. printStackTrace();
}return null;
}public static voidmain(String[] args) {try{//generate public key, private key file//generateKeyPair();
String s= encrypt(“https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=1&rsv_idx=1&ch=3”);
System.out.println(“Encryption: “+s);
System.out.println(“Decryption: “+decrypt(s));//Use base64 to encrypt and decrypt
String a =encryptBASE64(s. getBytes());
System.out.println(a);
String b= newString(decryptBASE64(a));
System.out.println(b);
System.out.println(“Decrypt b: “+decrypt(b));
} catch(Exception e) {
e. printStackTrace();
}
}
}
ecryptBASE64(a));
System.out.println(b);
System.out.println(“Decrypt b: “+decrypt(b));
} catch(Exception e) {
e. printStackTrace();
}
}
}