001 /*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements. See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership. The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License. You may obtain a copy of the License at
009 *
010 * http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing,
013 * software distributed under the License is distributed on an
014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015 * KIND, either express or implied. See the License for the
016 * specific language governing permissions and limitations
017 * under the License.
018 */
019 package org.apache.shiro.util;
020
021 import org.apache.shiro.codec.Base64;
022 import org.apache.shiro.codec.Hex;
023
024 import java.util.Arrays;
025
026 /**
027 * Very simple {@link ByteSource ByteSource} implementation that maintains an internal {@code byte[]} array and uses the
028 * {@link Hex Hex} and {@link Base64 Base64} codec classes to support the
029 * {@link #toHex() toHex()} and {@link #toBase64() toBase64()} implementations.
030 *
031 * @author Les Hazlewood
032 * @since 1.0
033 */
034 public class SimpleByteSource implements ByteSource {
035
036 private final byte[] bytes;
037
038 public SimpleByteSource(byte[] bytes) {
039 this.bytes = bytes;
040 }
041
042 public byte[] getBytes() {
043 return this.bytes;
044 }
045
046 public String toHex() {
047 return Hex.encodeToString(getBytes());
048 }
049
050 public String toBase64() {
051 return Base64.encodeToString(getBytes());
052 }
053
054 public String toString() {
055 return toBase64();
056 }
057
058 public int hashCode() {
059 return toBase64().hashCode();
060 }
061
062 public boolean equals(Object o) {
063 if (o == this) {
064 return true;
065 }
066 if (o instanceof SimpleByteSource) {
067 SimpleByteSource bs = (SimpleByteSource) o;
068 return Arrays.equals(getBytes(), bs.getBytes());
069 }
070 return false;
071 }
072 }