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();
122 * Use this to create special case Case Sets and/or Line breaks
124 * If you don't know why you need this, use the Singleton Method
129 public Symm(char[] codeset, int split, String charset, boolean useEndEquals) {
130 this.codeset = codeset;
131 splitLinesAt = split;
133 endEquals = useEndEquals;
134 char prev = 0, curr=0, first = 0;
135 int offset=Integer.SIZE; // something that's out of range for integer array
137 // There can be time efficiencies gained when the underlying keyset consists mainly of ordered
138 // data (i.e. abcde...). Therefore, we'll quickly analyze the keyset. If it proves to have
139 // too much entropy, the "Unordered" algorithm, which is faster in such cases is used.
140 ArrayList<int[]> la = new ArrayList<int[]>();
141 for(int i=0;i<codeset.length;++i) {
143 if(prev+1==curr) { // is next character in set
146 if(offset!=Integer.SIZE) { // add previous range
147 la.add(new int[]{first,prev,offset});
153 la.add(new int[]{first,curr,offset});
154 if(la.size()>codeset.length/3) {
155 convert = new Unordered(codeset);
156 } else { // too random to get speed enhancement from range algorithm
157 int[][] range = new int[la.size()][];
159 convert = new Ordered(range);
163 public Symm copy(int lines) {
164 return new Symm(codeset,lines,encoding,endEquals);
167 // Only used by keygen, which is intentionally randomized. Therefore, always use unordered
168 private Symm(char[] codeset, Symm parent) {
169 this.codeset = codeset;
170 splitLinesAt = parent.splitLinesAt;
171 endEquals = parent.endEquals;
172 encoding = parent.encoding;
173 convert = new Unordered(codeset);
177 * Obtain the base64() behavior of this class, for use in standard BASIC AUTH mechanism, etc.
181 public static final Symm base64() {
186 * Obtain the base64() behavior of this class, for use in standard BASIC AUTH mechanism, etc.
191 public static final Symm base64noSplit() {
192 return base64noSplit;
196 * Obtain the base64 "URL" behavior of this class, for use in File Names, etc. (no "/")
199 public static final Symm base64url() {
204 * Obtain a special ASCII version for Scripting, with base set of base64url use in File Names, etc. (no "/")
206 public static final Symm baseCrypt() {
210 public <T> T exec(SyncExec<T> exec) throws Exception {
212 if(keyBytes == null) {
213 keyBytes = new byte[AES.AES_KEY_SIZE/8];
214 int offset = (Math.abs(codeset[0])+47)%(codeset.length-keyBytes.length);
215 for(int i=0;i<keyBytes.length;++i) {
216 keyBytes[i] = (byte)codeset[i+offset];
220 return exec.exec(new AES(keyBytes,0,keyBytes.length));
223 public interface Encryption {
224 public CipherOutputStream outputStream(OutputStream os, boolean encrypt);
225 public CipherInputStream inputStream(InputStream is, boolean encrypt);
228 public static interface SyncExec<T> {
229 public T exec(Encryption enc) throws IOException, Exception;
232 public byte[] encode(byte[] toEncrypt) throws IOException {
233 if(toEncrypt==null) {
236 ByteArrayOutputStream baos = new ByteArrayOutputStream((int)(toEncrypt.length*1.25));
237 encode(new ByteArrayInputStream(toEncrypt),baos);
238 return baos.toByteArray();
242 public byte[] decode(byte[] encrypted) throws IOException {
243 ByteArrayOutputStream baos = new ByteArrayOutputStream((int)(encrypted.length*1.25));
244 decode(new ByteArrayInputStream(encrypted),baos);
245 return baos.toByteArray();
249 * Helper function for String API of "Encode"
250 * use "getBytes" with appropriate char encoding, etc.
254 * @throws IOException
256 public String encode(String str) throws IOException {
258 boolean useDefaultEncoding = false;
260 array = str.getBytes(encoding);
261 } catch (IOException e) {
262 array = str.getBytes(); // take default
263 useDefaultEncoding = true;
265 // Calculate expected size to avoid any buffer expansion copies within the ByteArrayOutput code
266 ByteArrayOutputStream baos = new ByteArrayOutputStream((int)(array.length*1.363)); // account for 4 bytes for 3 and a byte or two more
268 encode(new ByteArrayInputStream(array),baos);
269 if (useDefaultEncoding) {
270 return baos.toString();
272 return baos.toString(encoding);
276 * Helper function for the String API of "Decode"
277 * use "getBytes" with appropriate char encoding, etc.
280 * @throws IOException
282 public String decode(String str) throws IOException {
284 boolean useDefaultEncoding = false;
286 array = str.getBytes(encoding);
287 } catch (IOException e) {
288 array = str.getBytes(); // take default
289 useDefaultEncoding = true;
291 // Calculate expected size to avoid any buffer expansion copies within the ByteArrayOutput code
292 ByteArrayOutputStream baos = new ByteArrayOutputStream((int)(array.length*.76)); // Decoding is 3 bytes for 4. Allocate slightly more than 3/4s
293 decode(new ByteArrayInputStream(array), baos);
294 if (useDefaultEncoding) {
295 return baos.toString();
297 return baos.toString(encoding);
301 * Convenience Function
303 * encode String into InputStream and call encode(InputStream, OutputStream)
307 * @throws IOException
309 public void encode(String string, OutputStream out) throws IOException {
310 encode(new ByteArrayInputStream(string.getBytes()),out);
314 * Convenience Function
316 * encode String into InputStream and call decode(InputStream, OutputStream)
320 * @throws IOException
322 public void decode(String string, OutputStream out) throws IOException {
323 decode(new ByteArrayInputStream(string.getBytes()),out);
326 public void encode(InputStream is, OutputStream os, byte[] prefix) throws IOException {
332 * encode InputStream onto Output Stream
337 * @throws IOException
339 public void encode(InputStream is, OutputStream os) throws IOException {
340 // StringBuilder sb = new StringBuilder((int)(estimate*1.255)); // try to get the right size of StringBuilder from start.. slightly more than 1.25 times
342 int read, idx=0, line=0;
347 if(line>=splitLinesAt) {
351 switch(++idx) { // 1 based reading, slightly faster ++
352 case 1: // ptr is the first 6 bits of read
353 os.write(codeset[read>>2]);
356 case 2: // ptr is the last 2 bits of prev followed by the first 4 bits of read
357 os.write(codeset[((prev & 0x03)<<4) | (read>>4)]);
361 // Char 1 is last 4 bits of prev plus the first 2 bits of read
362 // Char 2 is the last 6 bits of read
363 os.write(codeset[(((prev & 0xF)<<2) | (read>>6))]);
364 if(line==splitLinesAt) { // deal with line splitting for two characters
368 os.write(codeset[(read & 0x3F)]);
374 } else { // deal with any remaining bits from Prev, then pad
376 case 1: // just the last 2 bits of prev
377 os.write(codeset[(prev & 0x03)<<4]);
378 if(endEquals)os.write(DOUBLE_EQ);
380 case 2: // just the last 4 bits of prev
381 os.write(codeset[(prev & 0xF)<<2]);
382 if(endEquals)os.write('=');
391 public void decode(InputStream is, OutputStream os, int skip) throws IOException {
392 if(is.skip(skip)!=skip) {
393 throw new IOException("Error skipping on IOStream in Symm");
399 * Decode InputStream onto OutputStream
402 * @throws IOException
404 public void decode(InputStream is, OutputStream os) throws IOException {
407 while((read = is.read())>=0) {
408 index = convert.convert(read);
410 switch(++idx) { // 1 based cases, slightly faster ++
411 case 1: // index goes into first 6 bits of prev
414 case 2: // write second 2 bits of into prev, write byte, last 4 bits go into prev
415 os.write((byte)(prev|(index>>4)));
418 case 3: // first 4 bits of index goes into prev, write byte, last 2 bits go into prev
419 os.write((byte)(prev|(index>>2)));
422 default: // (3+) | prev and last six of index
423 os.write((byte)(prev|(index&0x3F)));
432 * Interface to allow this class to choose which algorithm to find index of character in Key
436 private interface Convert {
437 public int convert(int read) throws IOException;
441 * Ordered uses a range of orders to compare against, rather than requiring the investigation
442 * of every character needed.
446 private static final class Ordered implements Convert {
447 private int[][] range;
448 public Ordered(int[][] range) {
451 public int convert(int read) throws IOException {
459 for(int i=0;i<range.length;++i) {
460 if(read >= range[i][0] && read<=range[i][1]) {
461 return read-range[i][2];
464 throw new IOException("Unacceptable Character in Stream");
469 * Unordered, i.e. the key is purposely randomized, simply has to investigate each character
470 * until we find a match.
474 private static final class Unordered implements Convert {
475 private char[] codec;
476 public Unordered(char[] codec) {
479 public int convert(int read) throws IOException {
486 for(int i=0;i<codec.length;++i) {
487 if(codec[i]==read)return i;
489 // don't give clue in Encryption mode
490 throw new IOException("Unacceptable Character in Stream");
495 * Generate a 2048 based Key from which we extract our code base
498 * @throws IOException
500 public static byte[] keygen() throws IOException {
501 byte inkey[] = new byte[0x600];
502 new SecureRandom().nextBytes(inkey);
503 ByteArrayOutputStream baos = new ByteArrayOutputStream(0x800);
504 base64url.encode(new ByteArrayInputStream(inkey), baos);
505 return baos.toByteArray();
508 // A class allowing us to be less predictable about significant digits (i.e. not picking them up from the
509 // beginning, and not picking them up in an ordered row. Gives a nice 2048 with no visible patterns.
510 private class Obtain {
516 private Obtain(Symm b64, byte[] key) {
517 skip = Math.abs(key[key.length-13]%key.length);
518 if((key.length&0x1) == (skip&0x1)) { // if both are odd or both are even
521 length = b64.codeset.length;
522 last = 17+length%59; // never start at beginning
527 return Math.abs(key[(++last*skip)%key.length])%length;
532 * Obtain a Symm from "keyfile" (Config.KEYFILE) property
536 * @throws IOException
537 * @throws CadiException
539 public static Symm obtain(Access access) throws CadiException {
540 Symm symm = Symm.baseCrypt();
542 String keyfile = access.getProperty(Config.CADI_KEYFILE,null);
544 File file = new File(keyfile);
546 access.log(Level.INIT, Config.CADI_KEYFILE,"points to",file.getCanonicalPath());
547 } catch (IOException e1) {
548 access.log(Level.INIT, Config.CADI_KEYFILE,"points to",file.getAbsolutePath());
552 FileInputStream fis = new FileInputStream(file);
554 symm = Symm.obtain(fis);
558 } catch (IOException e) {
561 } catch (IOException e) {
562 access.log(e, "Cannot load keyfile");
567 filename = file.getCanonicalPath();
568 } catch (IOException e) {
569 filename = file.getAbsolutePath();
571 throw new CadiException("ERROR: " + filename + " does not exist!");
577 * Create a new random key
579 public Symm obtain() throws IOException {
580 byte inkey[] = new byte[0x800];
581 new SecureRandom().nextBytes(inkey);
582 return obtain(inkey);
586 * Obtain a Symm from 2048 key from a String
590 * @throws IOException
592 public static Symm obtain(String key) throws IOException {
593 return obtain(new ByteArrayInputStream(key.getBytes()));
597 * Obtain a Symm from 2048 key from a Stream
601 * @throws IOException
603 public static Symm obtain(InputStream is) throws IOException {
604 ByteArrayOutputStream baos = new ByteArrayOutputStream();
606 base64url.decode(is, baos);
607 } catch (IOException e) {
609 throw new IOException("Invalid Key");
611 byte[] bkey = baos.toByteArray();
612 if(bkey.length<0x88) { // 2048 bit key
613 throw new IOException("Invalid key");
615 return baseCrypt().obtain(bkey);
619 * Convenience for picking up Keyfile
623 * @throws IOException
625 public static Symm obtain(File f) throws IOException {
626 FileInputStream fis = new FileInputStream(f);
634 * Decrypt into a String
640 * @throws IOException
642 public String enpass(String password) throws IOException {
643 ByteArrayOutputStream baos = new ByteArrayOutputStream();
644 enpass(password,baos);
645 return new String(baos.toByteArray());
649 * Create an encrypted password, making sure that even short passwords have a minimum length.
653 * @throws IOException
655 public void enpass(final String password, final OutputStream os) throws IOException {
656 final ByteArrayOutputStream baos = new ByteArrayOutputStream();
657 DataOutputStream dos = new DataOutputStream(baos);
658 byte[] bytes = password.getBytes();
659 if(this.getClass().getSimpleName().startsWith("base64")) { // don't expose randomization
663 Random r = new SecureRandom();
666 for(int i=0;i<3;++i) {
667 dos.writeByte(b=(byte)r.nextInt());
671 for(int i=0;i<start;++i) {
672 dos.writeByte(r.nextInt());
674 dos.writeInt((int)System.currentTimeMillis());
675 int minlength = Math.min(0x9,bytes.length);
676 dos.writeByte(minlength); // expect truncation
677 if(bytes.length<0x9) {
678 for(int i=0;i<bytes.length;++i) {
679 dos.writeByte(r.nextInt());
680 dos.writeByte(bytes[i]);
682 // make sure it's long enough
683 for(int i=bytes.length;i<0x9;++i) {
684 dos.writeByte(r.nextInt());
691 // 7/21/2016 Jonathan add AES Encryption to the mix
693 exec(new SyncExec<Void>() {
695 public Void exec(Encryption enc) throws Exception {
696 CipherInputStream cis = enc.inputStream(new ByteArrayInputStream(baos.toByteArray()), true);
706 } catch (IOException e) {
708 } catch (Exception e) {
709 throw new IOException(e);
714 * Decrypt a password into a String
720 * @throws IOException
722 public String depass(String password) throws IOException {
723 if(password==null)return null;
724 ByteArrayOutputStream baos = new ByteArrayOutputStream();
725 depass(password,baos);
726 return new String(baos.toByteArray());
737 * @throws IOException
739 public long depass(final String password, final OutputStream os) throws IOException {
740 int offset = password.startsWith(ENC)?4:0;
741 final ByteArrayOutputStream baos = new ByteArrayOutputStream();
742 final ByteArrayInputStream bais = new ByteArrayInputStream(password.getBytes(),offset,password.length()-offset);
744 exec(new SyncExec<Void>() {
746 public Void exec(Encryption enc) throws IOException {
747 CipherOutputStream cos = enc.outputStream(baos, false);
749 cos.close(); // flush
753 } catch (IOException e) {
755 } catch (Exception e) {
756 throw new IOException(e);
759 byte[] bytes = baos.toByteArray();
760 DataInputStream dis = new DataInputStream(new ByteArrayInputStream(bytes));
762 if(this.getClass().getSimpleName().startsWith("base64")) { // don't expose randomization
767 for(int i=0;i<3;++i) {
768 start+=Math.abs(dis.readByte());
771 for(int i=0;i<start;++i) {
774 time = (dis.readInt() & 0xFFFF)|(System.currentTimeMillis()&0xFFFF0000);
775 int minlength = dis.readByte();
777 DataOutputStream dos = new DataOutputStream(os);
778 for(int i=0;i<minlength;++i) {
780 dos.writeByte(dis.readByte());
783 int pre =((Byte.SIZE*3+Integer.SIZE+Byte.SIZE)/Byte.SIZE)+start;
784 os.write(bytes, pre, bytes.length-pre);
790 public static String randomGen(int numBytes) {
791 return randomGen(passChars,numBytes);
794 public static String randomGen(char[] chars ,int numBytes) {
796 StringBuilder sb = new StringBuilder(numBytes);
797 for(int i=0;i<numBytes;++i) {
798 rint = random.nextInt(chars.length);
799 sb.append(chars[rint]);
801 return sb.toString();
803 // Internal mechanism for helping to randomize placement of characters within a Symm codeset
804 // Based on an incoming data stream (originally created randomly, but can be recreated within
805 // 2048 key), go after a particular place in the new codeset. If that codeset spot is used, then move
806 // right or left (depending on iteration) to find the next available slot. In this way, key generation
807 // is speeded up by only enacting N iterations, but adds a spreading effect of the random number stream, so that keyset is also
808 // shuffled for a good spread. It is, however, repeatable, given the same number set, allowing for
809 // quick recreation when the official stream is actually obtained.
810 public Symm obtain(byte[] key) throws IOException {
811 int filled = codeset.length;
812 char[] seq = new char[filled];
815 boolean right = true;
817 Obtain o = new Obtain(this,key);
821 if(index<0 || index>=codeset.length) {
822 System.out.println("uh, oh");
824 if(right) { // alternate going left or right to find the next open slot (keeps it from taking too long to hit something)
825 for(int j=index;j<end;++j) {
827 seq[j]=codeset[filled];
834 for(int j=index;j>=0;--j) {
836 seq[j]=codeset[filled];
844 Symm newSymm = new Symm(seq,this);
847 newSymm.keyBytes = new byte[AES.AES_KEY_SIZE/8];
848 int offset = (Math.abs(key[(47%key.length)])+137)%(key.length-newSymm.keyBytes.length);
849 for(int i=0;i<newSymm.keyBytes.length;++i) {
850 newSymm.keyBytes[i] = key[i+offset];
852 } catch (Exception e) {
853 throw new IOException(e);