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
020package org.apache.shiro.crypto.cipher;
021
022import org.apache.shiro.lang.util.ByteSource;
023import org.apache.shiro.lang.util.Destroyable;
024
025import java.io.IOException;
026
027import org.apache.shiro.lang.util.ByteSourceWrapper;
028import org.apache.shiro.lang.util.ByteUtils;
029
030/**
031 * A simple implementation that maintains cipher service, ciphertext and key for decrypting it later.
032 * {@link #useBytes(ByteSourceUser)} guarantees the sensitive data in byte array will be erased at end of use.
033 */
034public class SimpleByteSourceBroker implements ByteSourceBroker, Destroyable {
035    private JcaCipherService cipherService;
036    private byte[] ciphertext;
037    private byte[] key;
038    private boolean destroyed;
039
040    public SimpleByteSourceBroker(JcaCipherService cipherService, byte[] ciphertext, byte[] key) {
041        this.cipherService = cipherService;
042        this.ciphertext = ciphertext.clone();
043        this.key = key.clone();
044    }
045
046    public synchronized void useBytes(ByteSourceUser user) {
047        if (destroyed || user == null) {
048            return;
049        }
050        ByteSource byteSource = cipherService.decryptInternal(ciphertext, key);
051
052        try (ByteSourceWrapper temp = ByteSourceWrapper.wrap(byteSource.getBytes())) {
053            user.use(temp.getBytes());
054        } catch (IOException e) {
055            // ignore
056        }
057
058    }
059
060    public byte[] getClonedBytes() {
061        ByteSource byteSource = cipherService.decryptInternal(ciphertext, key);
062        // this's a newly created byte array
063        return byteSource.getBytes();
064    }
065
066    public void destroy() throws Exception {
067        if (!destroyed) {
068            synchronized (this) {
069                destroyed = true;
070                cipherService = null;
071                ByteUtils.wipe(ciphertext);
072                ciphertext = null;
073                ByteUtils.wipe(key);
074                key = null;
075            }
076        }
077    }
078}