1. 程式人生 > >BASE64加密字串總結

BASE64加密字串總結

BASE64加密字串,當編碼的位元組較長時,encode出來的字串會自動加入\n\r進行自動換行。針對這個問題,原因是rfc規範規定76個字元換一次行。 

我們可以使用replaceAll("\r\n", "")來進行替換。

具體示例程式碼如下:

package com.zfsoft.setup.encrypt;


import java.io.ByteArrayOutputStream;
import java.util.Properties;


import javax.crypto.Cipher;


import org.springframework.beans.factory.FactoryBean;


import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;


public class DBEncrypt implements FactoryBean {


private Properties properties;



public Object getObject() throws Exception {
return getProperties();
}


@SuppressWarnings("unchecked")
public Class getObjectType() {
return java.util.Properties.class;
}


public boolean isSingleton() {
return true;
}


public Properties getProperties() {
return properties;
}


public void setProperties(Properties inProperties) {
this.properties = inProperties;
String originalUsername = properties.getProperty("user");
String originalPassword = properties.getProperty("password");
if (originalUsername != null) {
String newUsername = deEncryptUsername(originalUsername);
properties.put("user", newUsername);
}
if (originalPassword != null) {
String newPassword = deEncryptPassword(originalPassword);
properties.put("password", newPassword);
}
}


private String deEncryptUsername(String originalUsername) {
return dCode(originalUsername.getBytes());
}


private String deEncryptPassword(String originalPassword) {
return dCode(originalPassword.getBytes());
}


public String eCode(String needEncrypt){
byte result[] = null;
try {
Cipher enCipher = Cipher.getInstance("DES");
javax.crypto.SecretKey key = Key.loadKey();
enCipher.init(1, key);
result = enCipher.doFinal(needEncrypt.getBytes());
BASE64Encoder b = new BASE64Encoder();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
b.encode(result, bos);
result = bos.toByteArray();
} catch (Exception e) {
throw new IllegalStateException("System doesn't support DES algorithm.");
}
return new String(result);
}


public String dCode(byte result[]){
String s = null;
try {
Cipher deCipher = Cipher.getInstance("DES");
deCipher.init(2, Key.loadKey());
BASE64Decoder d = new BASE64Decoder();
result = d.decodeBuffer(new String(result));
byte strByte[] = deCipher.doFinal(result);
s = new String(strByte);
} catch (Exception e) {
e.printStackTrace();
//throw new IllegalStateException("System doesn't support DES algorithm.");
}
return s;
}


public static void main(String[] args){
    String s = "jdbc:oracle:thin:zfsoft_jyxt/[email protected]:1521:orcl";
    DBEncrypt p = new DBEncrypt();
    String afterE = p.eCode(s);
    //如果超長,存在換行,則進行替換
    System.out.println(afterE.replaceAll("\r\n", ""));
    System.out.println(p.dCode("nD9i2ZemQbY+nbO1DlivFg==".getBytes()));
//    System.out.println(p.dCode("Kbs2u6NELkMD+i6RnR+aSRYguMAm9SijwCfX1bT8Fg4HkVsh0SdX85+Y60A4RnMl".getBytes()));
    //System.out.println(p.dCode("".getBytes()));
   
    }
}