base64.java
来自「JAVA 所有包」· Java 代码 · 共 812 行 · 第 1/2 页
JAVA
812 行
/* * Copyright 1999-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */package com.sun.org.apache.xml.internal.security.utils;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.io.StringReader;import java.math.BigInteger;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;import org.w3c.dom.Document;import org.w3c.dom.Element;import org.w3c.dom.Node;import org.w3c.dom.Text;import org.xml.sax.InputSource;/** * Implementation of MIME's Base64 encoding and decoding conversions. * Optimized code. (raw version taken from oreilly.jonathan.util, * and currently com.sun.org.apache.xerces.internal.ds.util.Base64) * * @author Raul Benito(Of the xerces copy, and little adaptations). * @author Anli Shundi * @author Christian Geuer-Pollmann * @see <A HREF="ftp://ftp.isi.edu/in-notes/rfc2045.txt">RFC 2045</A> * @see com.sun.org.apache.xml.internal.security.transforms.implementations.TransformBase64Decode */public class Base64 { /** {@link java.util.logging} logging facility */ static java.util.logging.Logger log = java.util.logging.Logger.getLogger(Base64.class.getName()); /** Field BASE64DEFAULTLENGTH */ public static final int BASE64DEFAULTLENGTH = 76; /** Field _base64length */ static int _base64length = Base64.BASE64DEFAULTLENGTH; private Base64() { // we don't allow instantiation } /** * Returns a byte-array representation of a <code>{@link BigInteger}<code>. * No sign-bit is outputed. * * <b>N.B.:</B> <code>{@link BigInteger}<code>'s toByteArray * retunrs eventually longer arrays because of the leading sign-bit. * * @param big <code>BigInteger<code> to be converted * @param bitlen <code>int<code> the desired length in bits of the representation * @return a byte array with <code>bitlen</code> bits of <code>big</code> */ static byte[] getBytes(BigInteger big, int bitlen) { //round bitlen bitlen = ((bitlen + 7) >> 3) << 3; if (bitlen < big.bitLength()) { throw new IllegalArgumentException(I18n .translate("utils.Base64.IllegalBitlength")); } byte[] bigBytes = big.toByteArray(); if (((big.bitLength() % 8) != 0) && (((big.bitLength() / 8) + 1) == (bitlen / 8))) { return bigBytes; } // some copying needed int startSrc = 0; // no need to skip anything int bigLen = bigBytes.length; //valid length of the string if ((big.bitLength() % 8) == 0) { // correct values startSrc = 1; // skip sign bit bigLen--; // valid length of the string } int startDst = bitlen / 8 - bigLen; //pad with leading nulls byte[] resizedBytes = new byte[bitlen / 8]; System.arraycopy(bigBytes, startSrc, resizedBytes, startDst, bigLen); return resizedBytes; } /** * Encode in Base64 the given <code>{@link BigInteger}<code>. * * @param big * @return String with Base64 encoding */ public static String encode(BigInteger big) { return encode(getBytes(big, big.bitLength())); } /** * Returns a byte-array representation of a <code>{@link BigInteger}<code>. * No sign-bit is outputed. * * <b>N.B.:</B> <code>{@link BigInteger}<code>'s toByteArray * retunrs eventually longer arrays because of the leading sign-bit. * * @param big <code>BigInteger<code> to be converted * @param bitlen <code>int<code> the desired length in bits of the representation * @return a byte array with <code>bitlen</code> bits of <code>big</code> */ public static byte[] encode(BigInteger big, int bitlen) { //round bitlen bitlen = ((bitlen + 7) >> 3) << 3; if (bitlen < big.bitLength()) { throw new IllegalArgumentException(I18n .translate("utils.Base64.IllegalBitlength")); } byte[] bigBytes = big.toByteArray(); if (((big.bitLength() % 8) != 0) && (((big.bitLength() / 8) + 1) == (bitlen / 8))) { return bigBytes; } // some copying needed int startSrc = 0; // no need to skip anything int bigLen = bigBytes.length; //valid length of the string if ((big.bitLength() % 8) == 0) { // correct values startSrc = 1; // skip sign bit bigLen--; // valid length of the string } int startDst = bitlen / 8 - bigLen; //pad with leading nulls byte[] resizedBytes = new byte[bitlen / 8]; System.arraycopy(bigBytes, startSrc, resizedBytes, startDst, bigLen); return resizedBytes; } /** * Method decodeBigIntegerFromElement * * @param element * @return the biginter obtained from the node * @throws Base64DecodingException */ public static BigInteger decodeBigIntegerFromElement(Element element) throws Base64DecodingException { return new BigInteger(1, Base64.decode(element)); } /** * Method decodeBigIntegerFromText * * @param text * @return the biginter obtained from the text node * @throws Base64DecodingException */ public static BigInteger decodeBigIntegerFromText(Text text) throws Base64DecodingException { return new BigInteger(1, Base64.decode(text.getData())); } /** * This method takes an (empty) Element and a BigInteger and adds the * base64 encoded BigInteger to the Element. * * @param element * @param biginteger */ public static void fillElementWithBigInteger(Element element, BigInteger biginteger) { String encodedInt = encode(biginteger); if (encodedInt.length() > 76) { encodedInt = "\n" + encodedInt + "\n"; } Document doc = element.getOwnerDocument(); Text text = doc.createTextNode(encodedInt); element.appendChild(text); } /** * Method decode * * Takes the <CODE>Text</CODE> children of the Element and interprets * them as input for the <CODE>Base64.decode()</CODE> function. * * @param element * @return the byte obtained of the decoding the element * $todo$ not tested yet * @throws Base64DecodingException */ public static byte[] decode(Element element) throws Base64DecodingException { Node sibling = element.getFirstChild(); StringBuffer sb = new StringBuffer(); while (sibling!=null) { if (sibling.getNodeType() == Node.TEXT_NODE) { Text t = (Text) sibling; sb.append(t.getData()); } sibling=sibling.getNextSibling(); } return decode(sb.toString()); } /** * Method encodeToElement * * @param doc * @param localName * @param bytes * @return an Element with the base64 encoded in the text. * */ public static Element encodeToElement(Document doc, String localName, byte[] bytes) { Element el = XMLUtils.createElementInSignatureSpace(doc, localName); Text text = doc.createTextNode(encode(bytes)); el.appendChild(text); return el; } /** * Method decode * * * @param base64 * @return the UTF bytes of the base64 * @throws Base64DecodingException * */ public static byte[] decode(byte[] base64) throws Base64DecodingException { return decodeInternal(base64); } /** * Encode a byte array and fold lines at the standard 76th character. * * @param binaryData <code>byte[]<code> to be base64 encoded * @return the <code>String<code> with encoded data */ public static String encode(byte[] binaryData) { return encode(binaryData,BASE64DEFAULTLENGTH); } /** * Base64 decode the lines from the reader and return an InputStream * with the bytes. * * * @param reader * @return InputStream with the decoded bytes * @exception IOException passes what the reader throws * @throws IOException * @throws Base64DecodingException */ public static byte[] decode(BufferedReader reader) throws IOException, Base64DecodingException { UnsyncByteArrayOutputStream baos = new UnsyncByteArrayOutputStream(); String line; while (null != (line = reader.readLine())) { byte[] bytes = decode(line); baos.write(bytes); } return baos.toByteArray(); } /** * Method main * * * @param args * * @throws Exception */ public static void main(String[] args) throws Exception { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); String testString1 = "<container><base64 value=\"Should be 'Hallo'\">SGFsbG8=</base64></container>"; InputSource inputSource = new InputSource(new StringReader(testString1)); Document doc = docBuilder.parse(inputSource); Element base64Elem = (Element) doc.getDocumentElement().getChildNodes().item(0); System.out.println(new String(decode(base64Elem))); } static private final int BASELENGTH = 255; static private final int LOOKUPLENGTH = 64; static private final int TWENTYFOURBITGROUP = 24; static private final int EIGHTBIT = 8; static private final int SIXTEENBIT = 16; static private final int FOURBYTE = 4; static private final int SIGN = -128; static private final char PAD = '='; static private final boolean fDebug = false; static final private byte [] base64Alphabet = new byte[BASELENGTH]; static final private char [] lookUpBase64Alphabet = new char[LOOKUPLENGTH]; static { for (int i = 0; i<BASELENGTH; i++) { base64Alphabet[i] = -1; } for (int i = 'Z'; i >= 'A'; i--) { base64Alphabet[i] = (byte) (i-'A'); } for (int i = 'z'; i>= 'a'; i--) { base64Alphabet[i] = (byte) ( i-'a' + 26); } for (int i = '9'; i >= '0'; i--) { base64Alphabet[i] = (byte) (i-'0' + 52); } base64Alphabet['+'] = 62; base64Alphabet['/'] = 63; for (int i = 0; i<=25; i++) lookUpBase64Alphabet[i] = (char)('A'+i); for (int i = 26, j = 0; i<=51; i++, j++) lookUpBase64Alphabet[i] = (char)('a'+ j); for (int i = 52, j = 0; i<=61; i++, j++) lookUpBase64Alphabet[i] = (char)('0' + j); lookUpBase64Alphabet[62] = '+'; lookUpBase64Alphabet[63] = '/'; } protected static final boolean isWhiteSpace(byte octect) { return (octect == 0x20 || octect == 0xd || octect == 0xa || octect == 0x9); } protected static final boolean isPad(byte octect) { return (octect == PAD); } /** * Encodes hex octects into Base64 * * @param binaryData Array containing binaryData * @return Encoded Base64 array */ /** * Encode a byte array in Base64 format and return an optionally * wrapped line. * * @param binaryData <code>byte[]</code> data to be encoded * @param length <code>int<code> length of wrapped lines; No wrapping if less than 4. * @return a <code>String</code> with encoded data */ public static String encode(byte[] binaryData,int length) {
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?