github.com/adnan-c/fabric_e2e_couchdb@v0.6.1-preview.0.20170228180935-21ce6b23cf91/accesscontrol/crypto/utils/keys.go (about) 1 /* 2 Copyright IBM Corp. 2016 All Rights Reserved. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package utils 18 19 import ( 20 "crypto/rand" 21 "crypto/x509" 22 "encoding/pem" 23 "errors" 24 "fmt" 25 ) 26 27 // PEMtoAES extracts from the PEM an AES key 28 func PEMtoAES(raw []byte, pwd []byte) ([]byte, error) { 29 if len(raw) == 0 { 30 return nil, errors.New("Invalid PEM. It must be different from nil") 31 } 32 block, _ := pem.Decode(raw) 33 if block == nil { 34 return nil, fmt.Errorf("Failed decoding [% x]", raw) 35 } 36 37 if x509.IsEncryptedPEMBlock(block) { 38 if len(pwd) == 0 { 39 return nil, errors.New("Encrypted Key. Need a password!!!") 40 } 41 42 decrypted, err := x509.DecryptPEMBlock(block, pwd) 43 if err != nil { 44 return nil, err 45 } 46 return decrypted, nil 47 } 48 49 return block.Bytes, nil 50 } 51 52 // AEStoPEM encapsulates an AES key in the PEM format 53 func AEStoPEM(raw []byte) []byte { 54 return pem.EncodeToMemory(&pem.Block{Type: "AES PRIVATE KEY", Bytes: raw}) 55 } 56 57 // AEStoEncryptedPEM encapsulates an AES key in the encrypted PEM format 58 func AEStoEncryptedPEM(raw []byte, pwd []byte) ([]byte, error) { 59 if len(raw) == 0 { 60 return nil, errors.New("Invalid key. It must be different from nil") 61 } 62 if len(pwd) == 0 { 63 return AEStoPEM(raw), nil 64 } 65 66 block, err := x509.EncryptPEMBlock( 67 rand.Reader, 68 "AES PRIVATE KEY", 69 raw, 70 pwd, 71 x509.PEMCipherAES256) 72 73 if err != nil { 74 return nil, err 75 } 76 77 return pem.EncodeToMemory(block), nil 78 }