2 * ============LICENSE_START====================================================
4 * ===========================================================================
5 * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
6 * ===========================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END====================================================
22 package org.onap.aaf.cadi;
24 import java.io.ByteArrayInputStream;
25 import java.io.ByteArrayOutputStream;
26 import java.io.DataInputStream;
27 import java.io.DataOutputStream;
29 import java.io.FileInputStream;
30 import java.io.IOException;
31 import java.io.InputStream;
32 import java.io.OutputStream;
33 import java.security.SecureRandom;
34 import java.util.ArrayList;
35 import java.util.Random;
37 import javax.crypto.CipherInputStream;
38 import javax.crypto.CipherOutputStream;
40 import org.onap.aaf.cadi.Access.Level;
41 import org.onap.aaf.cadi.config.Config;
44 * Key Conversion, primarily "Base64"
46 * Base64 is required for "Basic Authorization", which is an important part of the overall CADI Package.
48 * Note: This author found that there is not a "standard" library for Base64 conversion within Java.
49 * The source code implementations available elsewhere were surprisingly inefficient, requiring, for
50 * instance, multiple string creation, on a transaction pass. Integrating other packages that might be
51 * efficient enough would put undue Jar File Dependencies given this Framework should have none-but-Java
54 * The essential algorithm is good for a symmetrical key system, as Base64 is really just
55 * a symmetrical key that everyone knows the values.
57 * This code is quite fast, taking about .016 ms for encrypting, decrypting and even .08 for key
58 * generation. The speed quality, especially of key generation makes this a candidate for a short term token
61 * It may be used to easily avoid placing Clear-Text passwords in configurations, etc. and contains
62 * supporting functions such as 2048 keyfile generation (see keygen). This keyfile should, of course,
63 * be set to "400" (Unix) and protected as any other mechanism requires.
65 * However, this algorithm has not been tested against hackers. Until such a time, utilize more tested
66 * packages to protect Data, especially sensitive data at rest (long term).
72 private static final byte[] DOUBLE_EQ = new byte[] {'=','='};
73 public static final String ENC = "enc:";
74 private static final Object LOCK = new Object();
75 private static final SecureRandom random = new SecureRandom();
77 public final char[] codeset;
78 private final int splitLinesAt;
79 private final String encoding;
80 private final Convert convert;
81 private final boolean endEquals;
82 private byte[] keyBytes = null;
83 //Note: AES Encryption is not Thread Safe. It is Synchronized
84 //private AES aes = null; // only initialized from File, and only if needed for Passwords
87 * This is the standard base64 Key Set.
90 public static final Symm base64 = new Symm(
91 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray()
92 ,76, Config.UTF_8,true);
94 public static final Symm base64noSplit = new Symm(
95 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray()
96 ,Integer.MAX_VALUE, Config.UTF_8,true);
99 * This is the standard base64 set suitable for URLs and Filenames
102 public static final Symm base64url = new Symm(
103 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".toCharArray()
104 ,76, Config.UTF_8,true);
107 * A Password set, using US-ASCII
110 public static final Symm encrypt = new Symm(base64url.codeset,1024, "US-ASCII", false);
111 private static final byte[] EMPTY = new byte[0];
114 * A typical set of Password Chars
115 * Note, this is too large to fit into the algorithm. Only use with PassGen
117 private static char passChars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+!@#$%^&*(){}[]?:;,.".toCharArray();
120 private static Symm internalOnly = null;
123 * Use this to create special case Case Sets and/or Line breaks
125 * If you don't know why you need this, use the Singleton Method
130 public Symm(char[] codeset, int split, String charset, boolean useEndEquals) {
131 this.codeset = codeset;
132 splitLinesAt = split;
134 endEquals = useEndEquals;
135 char prev = 0, curr=0, first = 0;
136 int offset=Integer.SIZE; // something that's out of range for integer array
138 // There can be time efficiencies gained when the underlying keyset consists mainly of ordered
139 // data (i.e. abcde...). Therefore, we'll quickly analyze the keyset. If it proves to have
140 // too much entropy, the "Unordered" algorithm, which is faster in such cases is used.
141 ArrayList<int[]> la = new ArrayList<>();
142 for(int i=0;i<codeset.length;++i) {
144 if(prev+1==curr) { // is next character in set
147 if(offset!=Integer.SIZE) { // add previous range
148 la.add(new int[]{first,prev,offset});
154 la.add(new int[]{first,curr,offset});
155 if(la.size()>codeset.length/3) {
156 convert = new Unordered(codeset);
157 } else { // too random to get speed enhancement from range algorithm
158 int[][] range = new int[la.size()][];
160 convert = new Ordered(range);
164 public Symm copy(int lines) {
165 return new Symm(codeset,lines,encoding,endEquals);
168 // Only used by keygen, which is intentionally randomized. Therefore, always use unordered
169 private Symm(char[] codeset, Symm parent) {
170 this.codeset = codeset;
171 splitLinesAt = parent.splitLinesAt;
172 endEquals = parent.endEquals;
173 encoding = parent.encoding;
174 convert = new Unordered(codeset);
178 * Obtain the base64() behavior of this class, for use in standard BASIC AUTH mechanism, etc.
182 public static final Symm base64() {
187 * Obtain the base64() behavior of this class, for use in standard BASIC AUTH mechanism, etc.
192 public static final Symm base64noSplit() {
193 return base64noSplit;
197 * Obtain the base64 "URL" behavior of this class, for use in File Names, etc. (no "/")
200 public static final Symm base64url() {
205 * Obtain a special ASCII version for Scripting, with base set of base64url use in File Names, etc. (no "/")
207 public static final Symm baseCrypt() {
211 public <T> T exec(SyncExec<T> exec) throws Exception {
213 if(keyBytes == null) {
214 keyBytes = new byte[AES.AES_KEY_SIZE/8];
215 int offset = (Math.abs(codeset[0])+47)%(codeset.length-keyBytes.length);
216 for(int i=0;i<keyBytes.length;++i) {
217 keyBytes[i] = (byte)codeset[i+offset];
221 return exec.exec(new AES(keyBytes,0,keyBytes.length));
224 public interface Encryption {
225 public CipherOutputStream outputStream(OutputStream os, boolean encrypt);
226 public CipherInputStream inputStream(InputStream is, boolean encrypt);
229 public static interface SyncExec<T> {
230 public T exec(Encryption enc) throws IOException, Exception;
233 public byte[] encode(byte[] toEncrypt) throws IOException {
234 if(toEncrypt==null) {
237 ByteArrayOutputStream baos = new ByteArrayOutputStream((int)(toEncrypt.length*1.25));
238 encode(new ByteArrayInputStream(toEncrypt),baos);
239 return baos.toByteArray();
243 public byte[] decode(byte[] encrypted) throws IOException {
244 ByteArrayOutputStream baos = new ByteArrayOutputStream((int)(encrypted.length*1.25));
245 decode(new ByteArrayInputStream(encrypted),baos);
246 return baos.toByteArray();
250 * Helper function for String API of "Encode"
251 * use "getBytes" with appropriate char encoding, etc.
255 * @throws IOException
257 public String encode(String str) throws IOException {
259 boolean useDefaultEncoding = false;
261 array = str.getBytes(encoding);
262 } catch (IOException e) {
263 array = str.getBytes(); // take default
264 useDefaultEncoding = true;
266 // Calculate expected size to avoid any buffer expansion copies within the ByteArrayOutput code
267 ByteArrayOutputStream baos = new ByteArrayOutputStream((int)(array.length*1.363)); // account for 4 bytes for 3 and a byte or two more
269 encode(new ByteArrayInputStream(array),baos);
270 if (useDefaultEncoding) {
271 return baos.toString();
273 return baos.toString(encoding);
277 * Helper function for the String API of "Decode"
278 * use "getBytes" with appropriate char encoding, etc.
281 * @throws IOException
283 public String decode(String str) throws IOException {
285 boolean useDefaultEncoding = false;
287 array = str.getBytes(encoding);
288 } catch (IOException e) {
289 array = str.getBytes(); // take default
290 useDefaultEncoding = true;
292 // Calculate expected size to avoid any buffer expansion copies within the ByteArrayOutput code
293 ByteArrayOutputStream baos = new ByteArrayOutputStream((int)(array.length*.76)); // Decoding is 3 bytes for 4. Allocate slightly more than 3/4s
294 decode(new ByteArrayInputStream(array), baos);
295 if (useDefaultEncoding) {
296 return baos.toString();
298 return baos.toString(encoding);
302 * Convenience Function
304 * encode String into InputStream and call encode(InputStream, OutputStream)
308 * @throws IOException
310 public void encode(String string, OutputStream out) throws IOException {
311 encode(new ByteArrayInputStream(string.getBytes()),out);
315 * Convenience Function
317 * encode String into InputStream and call decode(InputStream, OutputStream)
321 * @throws IOException
323 public void decode(String string, OutputStream out) throws IOException {
324 decode(new ByteArrayInputStream(string.getBytes()),out);
327 public void encode(InputStream is, OutputStream os, byte[] prefix) throws IOException {
333 * encode InputStream onto Output Stream
338 * @throws IOException
340 public void encode(InputStream is, OutputStream os) throws IOException {
341 // StringBuilder sb = new StringBuilder((int)(estimate*1.255)); // try to get the right size of StringBuilder from start.. slightly more than 1.25 times
343 int read, idx=0, line=0;
348 if(line>=splitLinesAt) {
352 switch(++idx) { // 1 based reading, slightly faster ++
353 case 1: // ptr is the first 6 bits of read
354 os.write(codeset[read>>2]);
357 case 2: // ptr is the last 2 bits of prev followed by the first 4 bits of read
358 os.write(codeset[((prev & 0x03)<<4) | (read>>4)]);
362 // Char 1 is last 4 bits of prev plus the first 2 bits of read
363 // Char 2 is the last 6 bits of read
364 os.write(codeset[(((prev & 0xF)<<2) | (read>>6))]);
365 if(line==splitLinesAt) { // deal with line splitting for two characters
369 os.write(codeset[(read & 0x3F)]);
375 } else { // deal with any remaining bits from Prev, then pad
377 case 1: // just the last 2 bits of prev
378 os.write(codeset[(prev & 0x03)<<4]);
379 if(endEquals)os.write(DOUBLE_EQ);
381 case 2: // just the last 4 bits of prev
382 os.write(codeset[(prev & 0xF)<<2]);
383 if(endEquals)os.write('=');
392 public void decode(InputStream is, OutputStream os, int skip) throws IOException {
393 if(is.skip(skip)!=skip) {
394 throw new IOException("Error skipping on IOStream in Symm");
400 * Decode InputStream onto OutputStream
403 * @throws IOException
405 public void decode(InputStream is, OutputStream os) throws IOException {
408 while((read = is.read())>=0) {
409 index = convert.convert(read);
411 switch(++idx) { // 1 based cases, slightly faster ++
412 case 1: // index goes into first 6 bits of prev
415 case 2: // write second 2 bits of into prev, write byte, last 4 bits go into prev
416 os.write((byte)(prev|(index>>4)));
419 case 3: // first 4 bits of index goes into prev, write byte, last 2 bits go into prev
420 os.write((byte)(prev|(index>>2)));
423 default: // (3+) | prev and last six of index
424 os.write((byte)(prev|(index&0x3F)));
433 * Interface to allow this class to choose which algorithm to find index of character in Key
437 private interface Convert {
438 public int convert(int read) throws IOException;
442 * Ordered uses a range of orders to compare against, rather than requiring the investigation
443 * of every character needed.
447 private static final class Ordered implements Convert {
448 private int[][] range;
449 public Ordered(int[][] range) {
452 public int convert(int read) throws IOException {
453 // System.out.print((char)read);
462 for(int i=0;i<range.length;++i) {
463 if(read >= range[i][0] && read<=range[i][1]) {
464 return read-range[i][2];
467 throw new IOException("Unacceptable Character in Stream");
472 * Unordered, i.e. the key is purposely randomized, simply has to investigate each character
473 * until we find a match.
477 private static final class Unordered implements Convert {
478 private char[] codec;
479 public Unordered(char[] codec) {
482 public int convert(int read) throws IOException {
489 for(int i=0;i<codec.length;++i) {
490 if(codec[i]==read)return i;
492 // don't give clue in Encryption mode
493 throw new IOException("Unacceptable Character in Stream");
498 * Generate a 2048 based Key from which we extract our code base
501 * @throws IOException
503 public static byte[] keygen() throws IOException {
504 byte inkey[] = new byte[0x600];
505 new SecureRandom().nextBytes(inkey);
506 ByteArrayOutputStream baos = new ByteArrayOutputStream(0x800);
507 base64url.encode(new ByteArrayInputStream(inkey), baos);
508 return baos.toByteArray();
511 // A class allowing us to be less predictable about significant digits (i.e. not picking them up from the
512 // beginning, and not picking them up in an ordered row. Gives a nice 2048 with no visible patterns.
513 private class Obtain {
519 private Obtain(Symm b64, byte[] key) {
520 skip = Math.abs(key[key.length-13]%key.length);
521 if((key.length&0x1) == (skip&0x1)) { // if both are odd or both are even
524 length = b64.codeset.length;
525 last = 17+length%59; // never start at beginning
530 return Math.abs(key[(++last*skip)%key.length])%length;
535 * Obtain a Symm from "keyfile" (Config.KEYFILE) property
539 * @throws IOException
540 * @throws CadiException
542 public static Symm obtain(Access access) throws CadiException {
543 String keyfile = access.getProperty(Config.CADI_KEYFILE,null);
545 Symm symm = Symm.baseCrypt();
547 File file = new File(keyfile);
549 access.log(Level.INIT, Config.CADI_KEYFILE,"points to",file.getCanonicalPath());
550 } catch (IOException e1) {
551 access.log(Level.INIT, Config.CADI_KEYFILE,"points to",file.getAbsolutePath());
555 FileInputStream fis = new FileInputStream(file);
557 symm = Symm.obtain(fis);
561 } catch (IOException e) {
564 } catch (IOException e) {
565 access.log(e, "Cannot load keyfile");
570 filename = file.getCanonicalPath();
571 } catch (IOException e) {
572 filename = file.getAbsolutePath();
574 throw new CadiException("ERROR: " + filename + " does not exist!");
579 return internalOnly();
580 } catch (IOException e) {
581 throw new CadiException(e);
586 * Create a new random key
588 public Symm obtain() throws IOException {
589 byte inkey[] = new byte[0x800];
590 new SecureRandom().nextBytes(inkey);
591 return obtain(inkey);
595 * Obtain a Symm from 2048 key from a String
599 * @throws IOException
601 public static Symm obtain(String key) throws IOException {
602 return obtain(new ByteArrayInputStream(key.getBytes()));
606 * Obtain a Symm from 2048 key from a Stream
610 * @throws IOException
612 public static Symm obtain(InputStream is) throws IOException {
613 ByteArrayOutputStream baos = new ByteArrayOutputStream();
615 base64url.decode(is, baos);
616 } catch (IOException e) {
618 throw new IOException("Invalid Key");
620 byte[] bkey = baos.toByteArray();
621 if(bkey.length<0x88) { // 2048 bit key
622 throw new IOException("Invalid key");
624 return baseCrypt().obtain(bkey);
628 * Convenience for picking up Keyfile
632 * @throws IOException
634 public static Symm obtain(File f) throws IOException {
635 FileInputStream fis = new FileInputStream(f);
643 * Decrypt into a String
649 * @throws IOException
651 public String enpass(String password) throws IOException {
652 ByteArrayOutputStream baos = new ByteArrayOutputStream();
653 enpass(password,baos);
654 return new String(baos.toByteArray());
658 * Create an encrypted password, making sure that even short passwords have a minimum length.
662 * @throws IOException
664 public void enpass(final String password, final OutputStream os) throws IOException {
665 final ByteArrayOutputStream baos = new ByteArrayOutputStream();
666 DataOutputStream dos = new DataOutputStream(baos);
667 byte[] bytes = password.getBytes();
668 if(this.getClass().getSimpleName().startsWith("base64")) { // don't expose randomization
672 Random r = new SecureRandom();
675 for(int i=0;i<3;++i) {
676 dos.writeByte(b=(byte)r.nextInt());
680 for(int i=0;i<start;++i) {
681 dos.writeByte(r.nextInt());
683 dos.writeInt((int)System.currentTimeMillis());
684 int minlength = Math.min(0x9,bytes.length);
685 dos.writeByte(minlength); // expect truncation
686 if(bytes.length<0x9) {
687 for(int i=0;i<bytes.length;++i) {
688 dos.writeByte(r.nextInt());
689 dos.writeByte(bytes[i]);
691 // make sure it's long enough
692 for(int i=bytes.length;i<0x9;++i) {
693 dos.writeByte(r.nextInt());
700 // 7/21/2016 Jonathan add AES Encryption to the mix
702 exec(new SyncExec<Void>() {
704 public Void exec(Encryption enc) throws Exception {
705 CipherInputStream cis = enc.inputStream(new ByteArrayInputStream(baos.toByteArray()), true);
715 } catch (IOException e) {
717 } catch (Exception e) {
718 throw new IOException(e);
723 * Decrypt a password into a String
729 * @throws IOException
731 public String depass(String password) throws IOException {
732 if(password==null)return null;
733 ByteArrayOutputStream baos = new ByteArrayOutputStream();
734 depass(password,baos);
735 return new String(baos.toByteArray());
746 * @throws IOException
748 public long depass(final String password, final OutputStream os) throws IOException {
749 int offset = password.startsWith(ENC)?4:0;
750 final ByteArrayOutputStream baos = new ByteArrayOutputStream();
751 final ByteArrayInputStream bais = new ByteArrayInputStream(password.getBytes(),offset,password.length()-offset);
753 exec(new SyncExec<Void>() {
755 public Void exec(Encryption enc) throws IOException {
756 CipherOutputStream cos = enc.outputStream(baos, false);
758 cos.close(); // flush
762 } catch (IOException e) {
764 } catch (Exception e) {
765 throw new IOException(e);
768 byte[] bytes = baos.toByteArray();
769 DataInputStream dis = new DataInputStream(new ByteArrayInputStream(bytes));
771 if(this.getClass().getSimpleName().startsWith("base64")) { // don't expose randomization
776 for(int i=0;i<3;++i) {
777 start+=Math.abs(dis.readByte());
780 for(int i=0;i<start;++i) {
783 time = (dis.readInt() & 0xFFFF)|(System.currentTimeMillis()&0xFFFF0000);
784 int minlength = dis.readByte();
786 DataOutputStream dos = new DataOutputStream(os);
787 for(int i=0;i<minlength;++i) {
789 dos.writeByte(dis.readByte());
792 int pre =((Byte.SIZE*3+Integer.SIZE+Byte.SIZE)/Byte.SIZE)+start;
793 os.write(bytes, pre, bytes.length-pre);
799 public static String randomGen(int numBytes) {
800 return randomGen(passChars,numBytes);
803 public static String randomGen(char[] chars ,int numBytes) {
805 StringBuilder sb = new StringBuilder(numBytes);
806 for(int i=0;i<numBytes;++i) {
807 rint = random.nextInt(chars.length);
808 sb.append(chars[rint]);
810 return sb.toString();
812 // Internal mechanism for helping to randomize placement of characters within a Symm codeset
813 // Based on an incoming data stream (originally created randomly, but can be recreated within
814 // 2048 key), go after a particular place in the new codeset. If that codeset spot is used, then move
815 // right or left (depending on iteration) to find the next available slot. In this way, key generation
816 // is speeded up by only enacting N iterations, but adds a spreading effect of the random number stream, so that keyset is also
817 // shuffled for a good spread. It is, however, repeatable, given the same number set, allowing for
818 // quick recreation when the official stream is actually obtained.
819 public Symm obtain(byte[] key) throws IOException {
820 int filled = codeset.length;
821 char[] seq = new char[filled];
824 boolean right = true;
826 Obtain o = new Obtain(this,key);
830 if(index<0 || index>=codeset.length) {
831 System.out.println("uh, oh");
833 if(right) { // alternate going left or right to find the next open slot (keeps it from taking too long to hit something)
834 for(int j=index;j<end;++j) {
836 seq[j]=codeset[filled];
843 for(int j=index;j>=0;--j) {
845 seq[j]=codeset[filled];
853 Symm newSymm = new Symm(seq,this);
856 newSymm.keyBytes = new byte[AES.AES_KEY_SIZE/8];
857 int offset = (Math.abs(key[(47%key.length)])+137)%(key.length-newSymm.keyBytes.length);
858 for(int i=0;i<newSymm.keyBytes.length;++i) {
859 newSymm.keyBytes[i] = key[i+offset];
861 } catch (Exception e) {
862 throw new IOException(e);
869 * This Symm is generated for internal JVM use. It has no external keyfile, but can be used
870 * for securing Memory, as it remains the same ONLY of the current JVM
872 * @throws IOException
874 public static synchronized Symm internalOnly() throws IOException {
875 if(internalOnly==null) {
876 ByteArrayInputStream baos = new ByteArrayInputStream(keygen());
878 internalOnly = Symm.obtain(baos);