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/zfsoft_jyxt@10.71.32.190: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()));
}
}